1

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

这是我的模型:

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
4

1 回答 1

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

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

于 2012-08-28T19:36:58.190 回答