Django外键未设置,因此无法保存表单

时间:2013-09-26 18:53:12

标签: django foreign-keys django-views django-forms django-1.3

我在两个表之间有一个简单的外键关系。我能够保存父节点,但无法将具有外键的子节点保存到父节点。这就是我的模型:

class Product(models.Model):
    month_choices   = tuple((m,m) for m in calendar.month_abbr[1:])
    year_choices    = tuple((str(n), str(n)) for n in range(2004, datetime.now().year +2 ))
    id              = models.AutoField(primary_key = True)
    title           = models.CharField(max_length = 1024)
    product_type    = models.ForeignKey(ProductType)
    month           = models.CharField(max_length =3, choices=month_choices)
    year            = models.CharField(choices=year_choices, max_length = 4)
    project         = models.CharField(max_length = 15, null = True, blank = True)
    url             = models.URLField(null = True, blank = True)
    export_to_xsede = models.BooleanField()
    #def __str__(self):
    #    return str(self.id)
    class Meta:
        db_table = "product"

class ProductResource(models.Model):
    CHOICES             = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E'))
    id                  = models.AutoField(primary_key = True)
    product             = models.ForeignKey(Product)
    resource            = models.CharField(choices=CHOICES, max_length = 15)

我的意见:

class PublicationForm(forms.ModelForm):
        title = forms.CharField(widget=forms.TextInput(attrs={'size':'70'}),required=False)
        url = forms.CharField(widget=forms.TextInput(attrs={'size':'70'}),required=False)
        class Meta:
            model = Product
class ResourceForm(forms.ModelForm):
        resource = forms.MultipleChoiceField(choices=ProductResource.CHOICES, widget = forms.CheckboxSelectMultiple)
        class Meta:
            model = ProductResource

我保存了父母:

saved_publication = publications_form.save()

但无法保存资源表单:

resource_form = ResourceForm(request.POST, instance = saved_publication)
resource_form.product = saved_publication
resource_form.save()

当我打印resource_form.errors时,我得到:

<ul class="errorlist"><li>product<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

我不知道为什么在这种情况下没有设置外键。

1 个答案:

答案 0 :(得分:0)

我假设您不想在表单上显示产品字段,因此您应该将其从表单中排除,以便验证通过:

class ResourceForm(forms.ModelForm):
    resource = forms.MultipleChoiceField(choices=ProductResource.CHOICES, widget = forms.CheckboxSelectMultiple)
    class Meta:
        model = ProductResource
        exclude = ['product']

然后在视图中,只需在调用is_valid()后手动设置产品即可。请务必在commit=False上传递form.save(),以便在您设置产品之前,它不会实际保存到数据库中。例如

...
saved_publication = publications_form.save()

resource_form = ResourceForm(request.POST)
if resource_form.is_valid():
    resource = resource_form.save(commit=False)
    resource.product = saved_publication
    resource.save()