一尘不染

Django中具有OneToOneField的ModelForm

django

我在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']

阅读 557

收藏
2020-04-01

共1个答案

一尘不染

你必须为其创建第二个表单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>
2020-04-01