Django 中带有 OneToOneField 的 ModelForm [英] ModelForm with OneToOneField in Django

查看:29
本文介绍了Django 中带有 OneToOneField 的 ModelForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django 中有两个与 OneToOneField(PrinterProfilePrinterAdress)相关的模型.我正在尝试使用 PrinterProfileForm 做一个表单,但由于某种原因它没有将 PrinterAddress 字段传递到表单中(它不是由模板中的 Django魔术"呈现).

I have two models in Django that are related with a OneToOneField (PrinterProfile and PrinterAdress). I am trying to do a form with PrinterProfileForm, but for some reason it does NOT pass the PrinterAddress fields into the form (it's not rendered by Django "magic" in the template).

我应该怎么做才能让我的 PrinterProfileForm 包括来自 PrinterAddress(其相关的 OneToOneField)的字段?

What should I do so that my PrinterProfileForm include as well the fields from PrinterAddress (its related 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']

推荐答案

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

You have to create second form for PrinterAddress and handle both forms in you view:

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()

当然,在模板中,您需要在一个

标签下显示两个表单:-)

Of course in the template you need to show both forms under one <form> tag :-)

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

这篇关于Django 中带有 OneToOneField 的 ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆