“具有ForeignKey字段的列'contact_id'不能为null”

时间:2012-08-28 19:27:12

标签: django foreign-keys

我正在寻找一种方法来将contact.id传递给我的ForeignKey字段。现在它返回一个错误,说明contact_id不能为null。

这是我的模特:

class Contact(models.Model):
    first_name = models.CharField(max_length=100, help_text="First Name")
    last_name = models.CharField(max_length=100, help_text="Last Name")
    email_address = models.EmailField(max_length=275)
    address = models.CharField(max_length=10, choices=ADDRESS_CHOICES)

    def __unicode__(self):
        return "%s %s" % (self.first_name, self.last_name)


class LetterHead(models.Model):
    contact = models.ForeignKey(Contact, related_name='letterhead')
    address = models.CharField(max_length=10, choices=ADDRESS_CHOICES)
    quantity = models.CharField(max_length=4, choices=QUANTITY_CHOICES)

以下是我的观点:

class ContactForm(forms.ModelForm):
     address = forms.ChoiceField(required=True, widget=RadioSelect(), choices=ADDRESS_CHOICES,)

    class Meta:
         model = Contact


class LetterHeadForm(forms.ModelForm):
    address = forms.ChoiceField(required=False, widget=RadioSelect(), choices=ADDRESS_CHOICES)

    class Meta:
        model = LetterHead
        exclude = ('contact',)
        widgets = {
            'quantity': forms.Select(choices=QUANTITY_CHOICES),
        }


LetterHeadFormSet = modelformset_factory(LetterHead,
    form=LetterHeadForm, extra=2, max_num=2)

以下是我的观点:

class OrderFormProcessor(object):
    def __init__(self, contact=None, contact_form_class=ContactForm,
            letterhead_form_class=LetterHeadFormSet,
            send_notification=False):
        self.contact_form_class = contact_form_class
        self.letterhead_form_class = letterhead_form_class
        self.send_notification = send_notification
        self.contact = contact

    def process(self, request, context=None):
        if not context:
            context = {}

        data = request.POST or None
        contact = self.contact

        contact_form = self.contact_form_class(data,
                instance=contact)

        forms = dict(
            contact_form=contact_form,
        )

        formsets = dict(
            letterhead_formset=self.letterhead_form_class(data, prefix='letterhead_'),
        )

        if request.method == 'POST':
            for f in forms.values() + formsets.values():
                print f.__class__, f.is_valid()

            form_is_valid = all([f.is_valid() for f in forms.values() + formsets.values()])
            if form_is_valid:
                contact = forms['contact_form'].save()

                letterhead_form = formsets['letterhead_formset']

                for lf in letterhead_form:
                    lf.contact_id = contact.id
                    lf.save()

                if self.send_notification:
                    email = OrderFormNotification(to=[settings.NO_REPLY_EMAIL_ADDRESS],
                    extra_context=data)
                    email.send()
            else:
                pass

        all_forms = chain(forms.values(), chain.from_iterable(formsets.values()))
        context = context.copy()
        context.update(forms.items() + formsets.items())
        context.update(
            error_list=list(chain.from_iterable([form.errors.values() for form in all_forms])),
        )

        return (forms, formsets), context

1 个答案:

答案 0 :(得分:1)

保存letterhead_form时

letterhead_form = formsets['letterhead_formset']

for lf in letterhead_form:
   lf.contact_id = contact.id
   lf.save()

变化

lf.contact_id = contact.id

lf.contact = contact

lf.contact__id = contact.id

您没有正确保存联系人对象。