Django generic foreign key

prthkms

I have a form with two modelForms. One of which has a generic foreign key to other. I'm getting the following error while saving the form.

null value in column "content_type_id" violates not-null constraint

Here's my code.

class Restraunt(models.Model):
    # model fields

class OpeningHours(models.Model):
    content_type = models.ForeignKey(ContentType, verbose_name=('content type'),related_name = 'open_shops')
    object_id = models.PositiveIntegerField(('object ID'))
    establishment = generic.GenericForeignKey('content_type', 'object_id')
    # other fields for storing timings

class RestrauntRegistrationForm(forms.ModelForm):
    class Meta:
        model = Restraunt

class OpeningHoursForm(forms.ModelForm):
    class Meta:
        model = OpeningHours
        exclude = ('content_type', 'object_id', 'establishment',)

And this is my view where I save the form

@login_required
@user_passes_test(is_owner) 
def register(request):
    if request.method == 'POST':
        restraunt_registration_form = RestrauntRegistrationForm(request.POST, prefix = 'restraunt')
        openinghours_form = OpeningHoursForm(request.POST, prefix = 'timings')
        if restraunt_registration_form.is_valid() and openinghours_form.is_valid():
            restraunt = restraunt_registration_form.save()
            openinghours_form.save(commit = False)
            openinghours_form.content_object = restraunt
            openinghours_form.save()

            return redirect('establishments.views.thanks')
        else:
            return HttpResponse('Error in form')

    else:
        restraunt_registration_form = RestrauntRegistrationForm(prefix = 'restraunt')
        openinghours_form = OpeningHoursForm(prefix = 'timings')

        c = {'restraunt_registration_form': restraunt_registration_form,
         'openinghours_form': openinghours_form,
        }
        c.update(csrf(request))

        return render_to_response('establishments/form.html', c)

The error occurs at this line

openinghours_form.save()

Can someone tell me what am I missing here ?

François Constant

That line is incorrect:

openinghours_form.content_object = restrant

Should be something like:

openinghours = openinghours_form.save(commit = False)
openinghours.establishment = restraunt
openinghours.save()

Also you could use more explicit names:

class OpeningHours(models.Model):
    establishment_type = models.ForeignKey(ContentType, verbose_name=('content type'),related_name = 'open_shops')
    establishment_id = models.PositiveIntegerField(('object ID'))
    establishment = generic.GenericForeignKey('establishment_type', 'establishment_id')

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related