gpt4 book ai didi

django - Django 中带有 OneToOneField 的 ModelForm

转载 作者:行者123 更新时间:2023-12-03 10:40:23 28 4
gpt4 key购买 nike

我在 Django 中有两个模型与 OneToOneField 相关。 ( PrinterProfilePrinterAdress )。
我想用 PrinterProfileForm 做一个表格,但由于某种原因它没有通过 PrinterAddress表单中的字段(它不是由模板中的 Django“魔术”呈现的)。

我该怎么做才能让我的 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']

最佳答案

您必须为 PrinterAddress 创建第二个表单并在您的 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()

当然,在模板中,您需要在一个 <form> 下显示两个表单。标签 :-)
<form action="" method="post">
{% csrf_token %}
{{ profile_form }}
{{ address_form }}
</form>

关于django - Django 中带有 OneToOneField 的 ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27832076/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com