列中的空值" content_type_id"违反非空约束

时间:2018-02-13 03:00:53

标签: python django django-forms

我在使用django的通用关系和表格方面遇到了困难。我使用crispyforms渲染我的HTML。

这是我得到的错误。不知道为什么每次我保存记录时它都在寻找content_type_id。我尝试使用管理面板创建一个新的公司记录,它的工作原理。这个错误只出现在我使用crispy form

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

以下是我的代码。

Forms.py `

        class CompanyFormHelper(FormHelper):
            form_tag = False
            render_required_fields = True
            disable_csrf = True
            render_required_fields = False
            layout = Layout(
                Fieldset(
                    _('Company'),
                    Div(InlineField('name'), css_class='col-sm-12'),
                    Div(InlineField('email'), css_class='col-sm-12'),
                    Div(InlineField('phone'), css_class='col-xs-6'),
                    Div(InlineField('type'), css_class='col-xs-6'),
                    Div(InlineField('is_partner'), css_class='col-xs-6'),
                    Div(InlineField('is_company'), css_class='col-xs-6'),
                    Row(
                        Formset('company_location_form', 'company_location_form_helper'),
                    ),
                    Submit('submit','Submit'),
                ),
            )


        class CompanyForm(ModelFormBase):

            def __init__(self,*args,**kwargs):
                super().__init__(*args,**kwargs)
                self.helper = CompanyFormHelper()

            class Meta:
                model = Company
                fields = ('name','email','phone','type','is_partner','is_company')
                widgets = {}


        class CompanyLocationFormsHelper(FormHelper):
            form_tag = False
            disable_csrf = True
            layout = Layout(
                Fieldset(
                    _('Company Address'),
                    Div(InlineField('line_first'), css_class='col-sm-12'),
                    Div(InlineField('line_second'), css_class='col-sm-12'),
                    Div(InlineField('city'), css_class='col-xs-6'),
                    Div(InlineField('province'), css_class='col-xs-6'),
                    Div(InlineField('postal_code'), css_class='col-xs-6'),
                    Div(InlineField('country'), css_class='col-xs-6'),
                ),
            )
            # template = 'is_portal/core/crispy_form/table_inline_formset.html'
            render_required_fields = True



        class CompanyLocationForm(ModelFormBase):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper = CompanyLocationFormsHelper()

            class Meta:
                model = Address
                fields = ('line_first','line_second','city','province','postal_code','country')
                widgets = {
                    'line_first': forms.TextInput(attrs={'required':'required'}),
                    'city': forms.TextInput(attrs={'required':'required'}),
                    'country': forms.Select(attrs={'class':'select required'}),
                }


        CompanyLocationFormset = generic_inlineformset_factory(
            Company,
            form=CompanyLocationForm,
            can_delete=True,
            fields='__all__',
            extra=1,
            min_num=1,
        )

`

Models.py

`

class Company(AbstractHistory):

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)

    object_id = models.UUIDField(
        primary_key=False,
        unique=False,
        default=uuid.uuid4,
        blank=True,
        null=True,
        )

    content_object = GenericForeignKey("content_type", "object_id")

    name = models.CharField(
        _("Name"),
        max_length=255,
        )

    address = GenericRelation(
        Address,
        null=True,
        blank=True,
        )

    email = models.CharField(
        _("Email"),
        max_length=255,
        blank=True,
        null=True,
        )

    phone = models.CharField(
        _("Phone"),
        max_length=255,
        blank=True,
        null=True,
        )

    type = models.CharField(
        _("Company Type"),
        max_length=255,
        choices=CHOICES_COMPANY_TYPE,
        default=CHOICES_COMPANY_TYPE.seller
    )

    is_partner = models.BooleanField(
        _('Is Partner'),
        default=False,
    )

    is_company = models.BooleanField(
        _('Is Company'),
        default=False,
    )

    class Meta:
        verbose_name_plural = _('Companies')

    def __str__(self):
        return '{}'.format(self.name)

`

Views.py

`

class CreateNewCompany(LoginRequiredMixin, CreateView):
model=Company
form_class=CompanyForm
template_name = 'create_company.html'
success_url = 'success'


def dispatch(self, request, *args, **kwargs):
    return super().dispatch(request, *args, **kwargs)


def get_context_data(self,**kwargs):
    context = super().get_context_data(**kwargs)

    context['company_location_form'] = CompanyLocationForm(prefix='company_location')
    context['company_location_form_helper'] = CompanyLocationFormsHelper

    return context


def get_success_url(self):
    return reverse('sales_project:summarycreate_step_other_information', kwargs={'slug':'project-20'})


def form_valid(self,form):


    try:
        with transaction.atomic():
            company = form.save()



            #formset = SalesProjectLocationFormset(self.request.POST, self.request.FILES, instance=company, prefix='company_location')

            # if formset.is_valid() and formset.has_changed():
            #     formset.save()

            # self.company = company

    except IntegrityError as e:
        print(e)
        messages.error(self.request, _('Unable to create company, please contact the admin. \r\n Error: {} '.format(e)))
        return redirect('company:create_company')

    return super().form_invalid(form(self.request.POST))

`

0 个答案:

没有答案