4

我有一个带有两个 modelForms 的表单。其中一个具有另一个的通用外键。保存表单时出现以下错误。

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

这是我的代码。

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',)

这是我保存表格的地方

@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)

错误发生在这一行

openinghours_form.save()

有人能告诉我我在这里想念什么吗?

4

1 回答 1

3

该行不正确:

openinghours_form.content_object = restrant

应该是这样的:

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

您也可以使用更明确的名称:

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')
于 2014-09-08T04:54:46.923 回答