我试图检索所有预订所作的登录用户。我得到以下错误:无法分配“'leonie'":“Customer.user”必须是“User”示例。我不明白的是,这不是用户模型的示例。
Views.py
from django.shortcuts import render, get_object_or_404
from .forms import CustomerForm, BookingForm
from django.contrib.auth.models import User
from .models import Booking, Customer
# Create your views here.
# https://stackoverflow.com/questions/77218397/how-to-access-instances-of-models-in-view-in-order-to-save-both-forms-at-once?noredirect=1&lq=1
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() and booking_form.is_valid():
customer = customer_form.save(commit=False)
customer.user = request.user.username
customer.save()
booking = booking_form.save(commit=False)
booking.customer = customer
booking.save()
customer_form = CustomerForm()
booking_form = BookingForm()
else:
customer_form = CustomerForm(prefix='customer')
booking_form = BookingForm(prefix='booking')
context = {
'customer_form': customer_form,
'booking_form': booking_form,
}
return render(request, 'booking.html', context)
def display_booking(request):
bookings = Booking.objects.filter(customer=request.user)
context = {
'bookings': bookings,
}
return render(request, 'booking.html', context)
models.py
from django.db import models
from django.contrib.auth.models import User
# 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)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.user}"
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(User, on_delete=models.CASCADE)
def __str__(self):
return f"Booking by {self.customer}"
我尝试将客户模型中的外键约束更改为客户而不是用户,但我仍然得到相同的错误消息。我相信有一个更好的方法来完成检索所有预订的用户登录。
1条答案
按热度按时间j2datikz1#
你应该直接使用
request.user
来检索user
对象,而不是request.user.username
。