cyb*_*oac 24 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']
Run Code Online (Sandbox Code Playgroud)
cat*_*ran 32
您必须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()
Run Code Online (Sandbox Code Playgroud)
当然在模板中你需要在一个<form>标签下显示两个表格:-)
<form action="" method="post">
{% csrf_token %}
{{ profile_form }}
{{ address_form }}
</form>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11250 次 |
| 最近记录: |