django 如何访问视图中的模型示例,以便同时保存这两个窗体

ffvjumwh  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(118)

我正试着把两种型号合并组合成一种形式。但是我不能保存这个表单,因为它不是模型的示例。我所追求的是一种将模型作为示例访问然后保存的方法。我使用脆的形式,我已经描述了我在底部的职位尝试,我不知道为什么这是不工作,所以一如既往的任何帮助是赞赏。
这是我的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()

和我的view.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”

px9o7tmv

px9o7tmv1#

在视图中示例化这两个表单,只需向其中至少一个表单添加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_namebooking-booking_time等。

相关问题