开发者

Decrement model value in django

It's my first time using django to clear my schoolwork, I want to lower Stock in my Book class by Quantity value, ex. Stock = 10 and Quantity = 1 Stock = 9 because 10 - 1 for Stock - Quantity this is my code

main.html

{% load static %}
<html>
    <head>
        <title>
            Bookstore Management System
        </title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    </head>
    <body>        
        {% include 'book/navbar.html' %}
        {% block content %}   
        {% endblock %}
        <br>
       
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    </body>
</html>

home.html

{% extends 'book/main.html' %}
{% block content %}
<br>
    <div class="container jumbotron">
        <div class="container row">
            <div class="col-lg-10">
                <table class="table table-sm">
                    <tr>
                        <th>title</th>
                        <th>Author</th>
                        <th>Edition</th>
                        <th>Stock</th>
                        <th>Price</th>
                    </tr>
                    {% for book in books %}
                    <tr>
                        <td>{{book.title}}</td>
                        <td>{{book.Author}}</td>
                        <td>{{book.Edition}}</td>
                        <td>{{book.Stock}}</td>
                        <td>{{book.Price}}</td>
                        <td><a class="btn btn-sm btn-info" href="{% url 'addtocart' book.id %}">Add to cart</a></td>
                    </tr>
                    {% endfor %}
                </table>
            </div>
        </div>
    </div>
{% endblock %}

viewcart.html

{% extends 'book/ma开发者_JS百科in.html' %}
{% load static %}
{% block content %}
<div class="container">
    <div class="row">
        <div class="col-lg-10"></div>
        <br>
        <h5>BOOKS:</h5>
        <div class="card card-body">
            <table>
                <tr>
                    <th>title</th>
                    <th>Author</th>
                    <th>Edition</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Total</th>

                </tr>
                {% for book in cart.books.all %}
                <tr>
                    <td>{{book.title}}</td>
                    <td>{{book.Author}}</td>
                    <td>{{book.Edition}}</td>
                    <td>{{book.Quantity}}</td>
                    <td>{{book.Price}}</td>
                    <td>{{book.Total}}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
    </div>
</div>
{% endblock %}

Model.py

from django.db import models
from django.db.models import F
from django.contrib.auth.models import User

class Book(models.Model):
    title=models.CharField(max_length=300, null=True)
    Author=models.CharField(max_length=300, null=True)
    Edition=models.IntegerField()
    Price=models.IntegerField()
    Stock=models.IntegerField()
    Quantity=models.IntegerField()
    Total=models.IntegerField()
    def decrementStock(self):
        self.Quantity += 1
        self.update(Stock=F('Stock') - F('Quantity'))
        self.save()
    def Tprice(self):
        self.update(Total=F('Price') * F('Quantity'))
        self.save()
    def _str_(self):
        return str(self.title)

class Customer(models.Model):
    user=models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name=models.CharField(max_length=200, null=True)
    phone=models.CharField(max_length=200, null=True)
    email=models.CharField(max_length=200, null=True)
    date_created=models.DateTimeField(auto_now_add=True, null=True)
    def _str_ (self):
        return str(self.name)    

class Cart(models.Model):
    customer=models.OneToOneField(Customer, null=True, on_delete=models.CASCADE)
    books=models.ManyToManyField(Book)
    def _str_ (self):
        return str(self.customer)

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.contrib.auth import login,logout,authenticate
from .forms import *

def home(request):
    books=Book.objects.all()
    context={'books':books}
    if request.user.is_staff:
        return render(request, 'book/adminhome.html', context)
    else:
        return render(request, 'book/home.html', context)

def logoutPage(request):
    logout(request)
    return redirect('/')

def loginPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        if request.method=="POST":
            username=request.POST.get('username')
            password=request.POST.get('password')
            user=authenticate(request,username=username, password=password)
            if user is not None:
                print("working")
                login(request,user)
                return redirect('/')
        context ={}
        return render(request,'book/login.html',context)

def registerPage(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        form=createuserform()
        cust_form=createcustomerform()
        if request.method=='POST':
            form=createuserform(request.POST)
            cust_form=createcustomerform(request.POST)
            if form.is_valid() and cust_form.is_valid:
                user=form.save()
                customer=cust_form.save(commit=False)
                customer.user=user
                customer.save()
                return redirect('login')
        context={
            'form':form,
            'cust_form':cust_form
        }
        return render(request,'book/register.html', context)

def addbook(request):
    form=createbookform()
    if request.method=='POST':
        form=createbookform(request.POST)
        if form.is_valid():
            form.save()
        return redirect('/')
    context={'form':form}
    return render(request,'book.addbook.html', context)

def viewcart(request):
    cust=Customer.objects.filter(user=request.user)
    for c in cust:
        carts=Cart.objects.all()
        for cart in carts:
            if(cart.customer==c):
                context={
                    'cart':cart
                }
                return render(request, 'book/viewcart.html', context)
        else:
            return render(request,'book/emptycart.html')

def addtocart(request,pk):
    book=Book.objects.get(id=pk)
    Book.objects.get(Quantity=pk).decrementStock()
    cust=Customer.objects.filter(user=request.user)
    
    for c in cust:       
        carts=Cart.objects.all()
        reqcart=''
        for cart in carts:
            if(cart.customer==c):
                reqcart=cart
                break
        if(reqcart==''):
            reqcart=Cart.objects.create(
                customer=c,
            )
        reqcart.books.add(book)    
    return redirect('/')

in model.py and views.py are wrong but i dont know to fix it sorry for my bad english writing and i thank you for poeple to helped me.

I try by editing model.py by using this but its failed and get these error `

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/addtocart/1

Django Version: 3.2
Python Version: 3.10.7
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'book']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\coding python\MHB\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\coding python\MHB\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\coding python\MHB\Scripts\bookstore\book\views.py", line 80, in addtocart
    Book.objects.get(Quantity=pk).decrementStock()
  File "C:\coding python\MHB\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\coding python\MHB\lib\site-packages\django\db\models\query.py", line 435, in get
    raise self.model.DoesNotExist(

Exception Type: DoesNotExist at /addtocart/1
Exception Value: Book matching query does not exist.

`

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜