Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-views

How to retrieve all customers bookings by either their username or id. Django


I am trying to retrive all bookings made by the logged in user. I am getting the following error: Cannot assign "'leonie'": "Customer.user" must be a "User" instance. What i don't understand is how this is not an instance of the user model.

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}"

I tried changing the foreign key constraint in the customer model to customer rather than user, however I am still getting the same error message. I'm sure there is a better way to accomplish retrieving all bookings by the user that is logged in.


Solution

  • you should use request.user directly to retrieve the user object instead of request.user.username.

    Replace:
        customer.user = request.user.username
    With:
        customer.user = request.user