在Django中,从两个不同的模型对象创建表单对象可以通过以下步骤实现:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Address(models.Model):
street = models.CharField(max_length=100)
city = models.CharField(max_length=50)
state = models.CharField(max_length=2)
zip_code = models.CharField(max_length=10)
forms.ModelForm
创建表单对象。例如:from django import forms
from .models import Person, Address
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ['first_name', 'last_name']
class AddressForm(forms.ModelForm):
class Meta:
model = Address
fields = ['street', 'city', 'state', 'zip_code']
from django.shortcuts import render
from .forms import PersonForm, AddressForm
def create_person_and_address(request):
person_form = PersonForm(request.POST or None)
address_form = AddressForm(request.POST or None)
if person_form.is_valid() and address_form.is_valid():
person = person_form.save()
address = address_form.save()
# 在此处添加其他逻辑,例如将地址与人员关联起来
context = {
'person_form': person_form,
'address_form': address_form,
}
return render(request, 'create_person_and_address.html', context)
form
标签渲染表单字段。例如,在create_person_and_address.html
文件中:<form method="post">
{% csrf_token %}
{{ person_form.as_p }}
{{ address_form.as_p }}
<button type="submit">Submit</button>
</form>
from django.urls import path
from . import views
urlpatterns = [
path('create_person_and_address/', views.create_person_and_address, name='create_person_and_address'),
]
现在,当用户访问/create_person_and_address/
URL时,他们将看到两个表单:一个用于创建人员,另一个用于创建地址。这就是如何在Django中从两个不同的模型对象创建表单对象。
领取专属 10元无门槛券
手把手带您无忧上云