在Django中使用OneToOneField的ModelForm

时间:2015-01-08 02:34:48

标签: django one-to-one django-forms

我在Django中有两个与OneToOneField(PrinterProfile和PrinterAdress)相关的模型。 我试图用PrinterProfileForm做一个表单,但由于某种原因它不会将PrinterAddress字段传递给表单(它不会被模板中的Django“magic”渲染)。

我该怎么做才能使PrinterProfileForm包含PrinterAddress(相关的OneToOneField)中的字段?

非常感谢

class PrinterProfile(TimeStampedModel):
    user = models.OneToOneField(User)
    phone_number = models.CharField(max_length=120, null=False, blank=False)
    additional_notes = models.TextField()
    delivery = models.BooleanField(default=False)
    pickup = models.BooleanField(default=True)


# The main address of the profile, it will be where are located all the printers.    
class PrinterAddress(TimeStampedModel):
    printer_profile = models.OneToOneField(PrinterProfile)
    formatted_address = models.CharField(max_length=200, null=True)
    latitude = models.DecimalField(max_digits=25, decimal_places=20)  # NEED TO CHECK HERE THE PRECISION NEEDED.
    longitude = models.DecimalField(max_digits=25, decimal_places=20)  # NEED TO CHECK HERE THE PRECISION NEEDED.
    point = models.PointField(srid=4326)

    def __unicode__(self, ):
        return self.user.username

class PrinterProfileForm(forms.ModelForm):
    class Meta:
        model = PrinterProfile
        exclude = ['user']

2 个答案:

答案 0 :(得分:29)

您必须为PrinterAddress创建第二个表单并在您查看中处理这两个表单:

if all((profile_form.is_valid(), address_form.is_valid())):
    profile = profile_form.save()
    address = address_form.save(commit=False)
    address.printer_profile = profile
    address.save()

当然,在模板中,您需要在一个<form>标记下显示两种形式: - )

<form action="" method="post">
    {% csrf_token %}
    {{ profile_form }}
    {{ address_form }}
</form>

答案 1 :(得分:1)

补充accepted answer

如果您有自定义清理方法,则需要添加>0.5个案例。对于显示的示例,如果try/except使用address方法验证您需要将其更改为:

clean()