Skip to content
Advertisement

Field ‘id’ expected a number but got ‘Free’

i’m trying to add a form, so users can post thier own articles , but when i hit publish button it shwos Field 'id' expected a number but got 'Free'. . i wasn’t adding the package_category field to the forms because i have set a default value for it in my models.py

package_category = models.ForeignKey(Package_Category, on_delete=models.DO_NOTHING, verbose_name="Package Category", null=True, default="Free")

when i now add the package_category field to the forms.py fields = [...] it now shows this error Field 'id' expected a number but got 'Free'. . i don’t really know what is going

Views.py

@login_required
def CreateElement(request):
    user = request.user
    categories = Category.objects.all()
    info = Announcements.objects.filter(active=True)
    if request.method == "POST":
        form = CreateElementForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.creator = request.user
            element = form.save(commit=False)  # ← no commit=False
            element.slug = slugify(element.title)
            # element.package_category == "Free"
            element.save()
            messages.success(request, f'Hi, Your Element have been sent for review and would be live soon!')
            return redirect('creators:dashboard')
    else:
        form = CreateElementForm()

    context = {
        'form': form,
        'info': info,
        'categories': categories
    }
    return render(request, 'newpost.html', context)

Advertisement

Answer

When adding a default for a Foreign Key, you can’t set it to a string like “Free” or “EPS”. You have to point the default to the actual object you are referring to. In your example, you have to point it to an object created by an Package_Category class. The code below is just an example, since I don’t know how your Package_category is structured :

def get_default_category():
    # get_or_create returns a tuple and we will only need the first value, which is the object
    return Package_Category.objects.get_or_create(name="Free")[0]

package_category = models.ForeignKey(Package_Category, on_delete=models.DO_NOTHING, verbose_name="Package Category", null=True, default=get_default_category)

Note that it has to use the method get_or_create since since you won’t have the object available if the model is being run for the first time. Ensure that it gets created automatically to prevent errors.

The error trace is telling you that you have to change the default from “EPS” for file_format field as well.

Advertisement