Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

python - No buttons are appearing when they are supposed to appear - django template language

So it is supposed to show remove from cart when user has that item in their cart and add to cart when they don't, I am trying to use django template language for this but both buttons are not appearing, home function handles the page i am talking about, It passes all the variables to home.html.

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>
    {% for usercart in cart %}
        {% if book == usercart.book %}
<form method="POST" action="/removefromcartforhome/">
    {% csrf_token %}
    <button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button>
</form>
         
        {% elif book != usercart.book  %}
<form method="POST" action="/addtocartforhome/">
    {% csrf_token %}
    <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button>
</form>
  {% else %}
  <form method="POST" action="/addtocartforhome/">
    {% csrf_token %}
    <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button>
</form>
{% endif %}
    {% endfor %}
{% endfor %}

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, OrderItem
from django.contrib.auth.decorators import login_required
from .forms import BookForm
from django.core.exceptions import ObjectDoesNotExist
import random
# Create your views here.

removederror = ''


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, 'error':'', 'cart':oof})
    else:
        books = Book.objects.all()
        return render(request, 'main/home.html', {'books':books})


@login_required
def addtocartforhome(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 CartItem.objects.filter(user=request.user, book=Book.objects.get(pk=request.POST['bookid'])).exists():
            return render(request, 'main/home.html', {'books':books, 'error':'That book is already in your cart!', 'price':fianlprice})
            
        else:
            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')
            
    elif request.method == 'GET':
        return render(request, 'main/signinuser.html', {'form':BookForm})
                                            

@login_required
def addtocartforproducts(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 CartItem.objects.filter(user=request.user, book=Book.objects.get(pk=request.POST['bookid'])).exists():
            return render(request, 'main/products.html', {'books':books, 'error':'That book is already in your cart!', 'price':fianlprice})
            
        else:
            try:
                book = Book.objects.get(pk=request.POST['bookid'])
            except Book.DoesNotExist:
                return redirect('showproducts')
            cart_item = CartItem.objects.create(book=book, user=request.user)
            return redirect('showproducts')
            
    elif request.method == 'GET':
        return render(request, 'main/signinuser.html', {'form':BookForm})

@login_required
def removefromcartforcart(request):
    if request.method == 'POST':
        oof = CartItem.objects.filter(user=request.user)
        fianlprice = 0
        for item in oof:
            fianlprice += item.book.price
        books = Book.objects.all()
        removebook = Book.objects.get(pk=request.POST['removeid'])
        try:
            cart_item = CartItem.objects.get(book=removebook, user=request.user).delete()
        except ObjectDoesNotExist:
            return render(request, 'main/cart.html', {'books':books, 'error':'That item is not in your cart!', 'price':fianlprice})
        return redirect('showcart')
    else:
        pass

@login_required
def removefromcartforhome(request):
    if request.method == 'POST':
        oof = CartItem.objects.filter(user=request.user)
        fianlprice = 0
        for item in oof:
            fianlprice += item.book.price
        books = Book.objects.all()
        removebook = Book.objects.get(pk=request.POST['removeid'])
        try:
            cart_item = CartItem.objects.get(book=removebook, user=request.user).delete()
        except ObjectDoesNotExist:
            removederror = 'That item is not in your cart!'
            return redirect('home')
        return redirect('home')
    else:
        pass

@login_required
def removefromcartforproducts(request):
    if request.method == 'POST':
        oof = CartItem.objects.filter(user=request.user)
        fianlprice = 0
        for item in oof:
            fianlprice += item.book.price
        books = Book.objects.all()
        removebook = Book.objects.get(pk=request.POST['removeid'])
        try:
            cart_item = CartItem.objects.get(book=removebook, user=request.user).delete()
        except ObjectDoesNotExist:
            return render(request, 'main/products.html', {'books':books, 'error':'That item is not in your cart!', 'price':fianlprice})
        return redirect('showproducts')
    else:
        pass


def showproducts(request):
    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/products.html', {'books':books, 'price':fianlprice})


@login_required
def showcart(request):
    oof = CartItem.objects.filter(user=request.user)
    fianlprice = 0
    for item in oof:
        fianlprice += item.book.price
    oof = CartItem.objects.filter(user=request.user)
    return render(request, 'main/cart.html', {'cart':oof, 'price':fianlprice})

@login_required
def makeorder(request):
    if request.method == 'POST':
        request_cart = CartItem.objects.filter(user=request.user)
        if not CartItem.objects.filter(user=request.user).exists():
            return render(request, 'main/orderdone.html', {'error':'Your cart is empty'})
        else:
            for item in request_cart:
                if OrderItem.objects.filter(user=item.user, book=item.book):
                    return render(request, 'main/orderdone.html', {'error':'You already own this book!'})
                else:
                    for item in request_cart:
                        createorder(item.book, item.user)
                    request_cart.delete()
                    return render(request, 'main/orderdone.html', {'error':'Your order has been placed!'})
    else:
        return redirect('home')


def createorder(product, user):
    order_item = Book.objects.get(pk=product.id)
    order_user = User.objects.get(username=user.username)
    unique_id = ''
    for x in range(10):
        letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        numbers = ['1','2','3','4','5','6','7','8','9','10']
        choice =  random.randint(1,5)
        if choice == 1:
            unique_id += letters[random.randint(0,25)]
        elif choice == 2:
            unique_id += numbers[random.randint(0,9)]
        elif choice == 3:
            unique_id += letters[random.randint(0,25)]
        elif choice == 4:
            unique_id += numbers[random.randint(0,9)]
        elif choice == 5:
            unique_id += letters[random.randint(0,25)]
    OrderItem.objects.create(user=order_user, book=order_item, order_id=unique_id)



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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...