Monday, November 27, 2017

NOT NULL constraint failed when trying to create form with initial values

Hi. I'm trying to create a form to construct an object for my Photo class. All of the objects fields except the photo itself will be invisible to the user. So, the only thing can be seen in the form is the button to select and upload the photo.

There is no problem with creating the form page. The problem is, giving the initial values for the rest of the fields. 
This is the relevant code in my view file:

    if request.method =='POST':
        data = {'photo_id': get_latest_photo_id_plusone(),
                'contest_id': get_latest_contest_id_plusone(),
                'ownername': 'SUMMERSON',
                }
        form=PhotoForm(request.POST, initial=data)
        if form.is_valid():
            Photo = form.save()
    else:
        form = PhotoForm()

And the relevant functions:

    def get_latest_photo_id_plusone():
        max_rating = Photo.objects.all().aggregate(Max('photo_id'))['photo_id__max']
        return max_rating+1


    def get_latest_contest_id_plusone():
        max_rating =Photo.objects.all().aggregate(Max('contest_id'))['contest_id__max']
        return max_rating+1

The error arises when I click on the send button after I select the image. It says: 

IntegrityError at /photo/create/
NOT NULL constraint failed: photo_photo.contest_id_id

But I've given the contest_id value. Haven't I? Where is the problem and how can I fix it?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ad42fcc2-7c20-48c0-9770-f2408c14a4e2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment