1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] I have a persistent 'FOREIGN KEY CONSTRAINT failed' error with shopping cart app, is...

Discussão em 'Python' iniciado por Stack, Outubro 3, 2024 às 19:42.

  1. Stack

    Stack Membro Participativo

    So I'm working with a group trying to code a kind of library. We're using django to create the web application, but I keep seeing this error occur.enter image description here

    Here's the model I'm using in the cart app:

    from django.db import models
    from video_rental.models import Movie, CustomUser
    from django.conf import settings

    class CartItem(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=0)
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
    return f'{self.quantity} x {self.movie.title}'


    Here are the views:

    from django.shortcuts import render
    from django.shortcuts import render, redirect
    from .models import CartItem
    from video_rental.models import Movie

    def movie_list(request):
    movies = Movie.objects.all()
    return render(request, 'myapp/index.html', {'products': movies})

    def view_cart(request):
    cart_items = CartItem.objects.filter(user=request.user)
    return render(request, 'myapp/cart.html', {'cart_items': cart_items})

    def add_to_cart(request, title):
    movie= Movie.objects.get(title=title)
    cart_item, created = CartItem.objects.get_or_create(movie=movie, user=request.user)
    cart_item.quantity += 1
    cart_item.save()
    return redirect('cart:view_cart')

    def remove_from_cart(request, title):
    cart_item = CartItem.objects.get(title=title)
    cart_item.delete()
    return redirect('cart:view_cart')


    def home(request):
    return HttpResponse('Hello, World!')



    This persistently happens in the admin panel when I'm trying to add things to a cart and save it. What should I do from here? Movie is defined in the video_rental app so I imported the model from there. I'm wondering what this Foreign Key error and how I can make it work.

    I've tried resolving it by correcting the models file, (I realized that the user that was specified in the model was a user that was never defined, so I once again imported the model that was being used in the video_rental app). This didn't seem to work though.

    Continue reading...

Compartilhe esta Página