我正在尝试将两种模型组合成一种形式。但是我无法保存表单,因为它不是模型的实例。我所追求的是一种将模型作为实例访问然后保存的方法。我正在使用脆皮表格,我已经在帖子底部描述了我所尝试的内容,我不知道为什么这不起作用,所以一如既往地感谢任何帮助。
这是我的 model.py 文件:
from django.db import models
# Create your models here.
BOOKING_STATUS = ((0, 'To be confirmed'), (1, 'Confirmed'), (2, 'Declined'))
class Customer(models.Model):
first_name = models.CharField(max_length=80)
last_name = models.CharField(max_length=80)
email = models.EmailField()
phone_number = models.CharField(max_length=20)
def __str__(self):
return f"Customer {self.first_name + ' ' + self.last_name}"
class Booking(models.Model):
booking_date = models.DateField()
booking_time = models.TimeField()
number_attending = models.IntegerField(default=2)
booking_status = models.IntegerField(choices=BOOKING_STATUS, default=0)
customer = models.ForeignKey('Customer', on_delete=models.CASCADE)
def __str__(self):
return f"Booking by {self.customer}"
forms.py:
from .models import Customer, Booking
from django import forms
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = '__all__'
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = ('booking_date', 'booking_time', 'number_attending')
class CustomerBookingForm(forms.Form):
customer_form = CustomerForm()
booking_form = BookingForm()
和我的观点.py
from django.shortcuts import render
from .forms import CustomerBookingForm
# Create your views here.
# https://stackoverflow.com/questions/51459435/django-create-multiple-instance-of-model-with-one-form
def customer_booking(request):
if request.method == 'POST':
customer_booking_form = CustomerBookingForm(request.POST)
# if customer_booking_form.is_valid():
else:
customer_booking_form = CustomerBookingForm()
context = {
'form': customer_booking_form,
}
return render(request, 'booking.html', context)
我已经尝试过:
booking_instance = customer_booking_form.cleaned_data['booking_form'].save()
但是,这无法识别字段“customer_form”或“booking_form”
在您的视图中实例化这两种形式,只需向其中至少一种添加
prefix
参数即可。
def customer_booking(request):
if request.method == "POST":
customer_form = CustomerForm(request.POST, prefix="customer")
booking_form = BookingForm(request.POST, prefix="booking")
# if customer_form.is_valid()
# if booking_form.is_valid()
.....
else:
customer_form = CustomerForm(prefix="customer")
booking_form = BookingForm(prefix="booking")
prefix
将让Django为每个表单提供一个唯一的命名空间。因此,字段 name
值将具有该 ModelForm 的指定前缀,即 customer-first_name
、booking-booking_time
等。