I have a form with two modelForms. One of them has a common foreign key to the other. When saving the form, I get the following error.
null value in column "content_type_id" violates not-null constraint
Here is my code.
class Restraunt(models.Model):
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')
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 when I keep in shape
@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)
Error in this line
openinghours_form.save()
Can someone tell me what I am missing here?
source
share