因此,当我尝试将其添加到购物车时,我得到CartItem匹配查询不存在错误,我正在尝试检查用户的购物车中是否已有该商品,如果没有,则应该添加该商品,如果他们这样做了然后将不会再次添加,当我单击添加到购物车时,它给我的CartItem匹配查询不存在。
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.db import IntegrityError
from .models import Book, CartItem
from django.contrib.auth.decorators import login_required
from .forms import BookForm
# Create your views here.
def calculate(request):
oof = CartItem.objects.filter(user=request.user)
fianlprice = 0
for item in oof:
fianlprice += item.book.price
def signupuser(request):
if request.user.is_authenticated:
return render(request, 'main/alreadyloggedin.html')
elif request.user != request.user.is_authenticated:
if request.method == "GET":
return render(request, 'main/signupuser.html', {'form':UserCreationForm()})
elif request.method == "POST":
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return render(request, 'main/UserCreated.html')
except IntegrityError:
return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'})
else:
return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'})
def signinuser(request):
if request.user.is_authenticated:
return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'})
elif request.user != request.user.is_authenticated:
if request.method == "GET":
return render(request, 'main/signinuser.html', {'form':AuthenticationForm()})
elif request.method == "POST":
user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
if user is None:
return render(request, 'main/signinuser.html', {'form':AuthenticationForm(), 'error':'Username and password did not match'})
else:
login(request, user)
return render(request, 'main/loggedin.html', {'error':'You are now logged in!'})
def logoutuser(request):
if request.user.is_authenticated:
if request.method == "GET":
return render(request, 'main/logoutuser.html')
elif request.method == "POST":
logout(request)
return render(request, 'main/loggedin.html', {'error':'You are now logged out!'})
elif request.user != request.user.is_authenticated:
return render(request, 'main/alreadyloggedin.html', {'error':'You are not logged in'})
def home(request):
if request.user.is_authenticated:
oof = CartItem.objects.filter(user=request.user)
fianlprice = 0
for item in oof:
fianlprice += item.book.price
books = Book.objects.all()
return render(request, 'main/home.html', {'books':books, 'price':fianlprice})
else:
books = Book.objects.all()
return render(request, 'main/home.html', {'books':books})
@login_required
def addtocart(request):
oof = CartItem.objects.filter(user=request.user)
fianlprice = 0
for item in oof:
fianlprice += item.book.price
books = Book.objects.all()
if request.method == 'POST':
if not CartItem.objects.get(user=request.user, book=Book.objects.get(pk=request.POST['bookid'])):
try:
book = Book.objects.get(pk=request.POST['bookid'])
except Book.DoesNotExist:
return redirect('home')
cart_item = CartItem.objects.create(book=book, user=request.user)
return redirect('home')
else:
return render(request, 'main/home.html', {'books':books, 'error':'That book is already in your cart!', 'price':fianlprice})
elif request.method == 'GET':
return render(request, 'main/signinuser.html', {'form':BookForm})
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Book(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
image = models.ImageField()
price = models.IntegerField()
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Order(models.Model):
order_id = models.CharField(max_length=500)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user
class CartItem(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.user.username
urls.py
"""EBook URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from core import views
urlpatterns = [
path('admin/', admin.site.urls),
path('signup/', views.signupuser, name='signupuser'),
path('login/', views.signinuser, name='signinuser'),
path('logout/', views.logoutuser, name='logoutuser'),
path('', views.home, name='home'),
path('cart/', views.addtocart, name='cart'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
home.html
<h1>Here are products</h1>
<h1>{{ error }}</h1>
<h1>Your cart currently costs ${{ price }}</h1>
{% for book in books %}
<h3>{{ book.name }}</h3>
<img src= "/media/{{ book.image }}" alt="">
<p>{{ book.description }}</p>
<form method="POST" action="/cart/">
{% csrf_token %}
<button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button>
</form>
{% endfor %}
if not CartItem.objects.get(user=request.user, book=Book.objects.get(pk=request.POST['bookid'])):
# there your code is breaking
cart_item_instance_qs = CartItem.objects.filter(user=request.user, book=Book.objects.get(pk=request.POST['bookid']))
if cart_item_instance_qs.exists():
..... do your stuff
当您尝试获取数据库django中不存在的元素时,抛出该错误
将来尝试使用.exists()
然后选择该元素,它不会引发错误+您拥有更多控制权
如果exists()
返回True
,则可以选择第一个元素
cart_item_instance = cart_item_instance_qs.first()
你可以检查计数
cart_item_instance_qs.count()
或者您可以遍历元素
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句