How to set an if statement to True in a Django template?

Issue

I have a Django form that corresponds with a model and allows the user to add or remove an item from his watchlist. I want the submit button to say "Add to Watchlist" if the user has not added the item to his watchlist and "Remove from Watchlist" if the listing is already on the user’s watchlist. Currently, the button says "Remove from Watchlist" (whether or not it has been added) and changes to "Add to Watchlist" once it has been clicked once. Then the button does not change.

html

<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
        {% csrf_token %}
        {{ watchlistForm }}
        {% if watchlist %}
            <input type = "submit" value = "{{ watchlist }}">
        {% else %}
            <input type = "submit" value = "Remove from Watchlist">
        {% endif %}
    </form>

views.py

@login_required(login_url='login')
def listing(request, id):
    #gets listing
    listing = get_object_or_404(Listings.objects, pk=id)
    #code for comment and bid forms
    listing_price = listing.bid
    sellar = listing.user
    comment_obj = Comments.objects.filter(listing=listing)
    #types of forms
    comment_form = CommentForm()
    bid_form = BidsForm()
    watchlist_form = WatchListForm()
    closelisting_form = CloseListingForm()
    #comment_form = CommentForm(request.POST)
    #watchlist_form = WatchListForm(request.POST)
    #bid_form = BidsForm(request.POST)

    #code for the bid form
    bid_obj = Bids.objects.filter(listing=listing)
    other_bids = bid_obj.all()
    max_bid =0
    for bid in other_bids:
        if listing.bid > max_bid:
            max_bid = listing.bid

     #checks if request method is post for all the forms
    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        bid_form = BidsForm(request.POST)
        watchlist_form = WatchListForm(request.POST)
        closelisting_form = CloseListingForm(request.POST)

        #checks if comment form is valid
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.listing = listing
            comment.user = request.user
            comment.save()

        #checks if bid form is valid
        if bid_form.is_valid():
            new_bid = bid_form.cleaned_data.get("bid")
            if (new_bid >= listing_price) and (new_bid > max_bid):
                bid = bid_form.save(commit=False)
                bid.listing = listing
                bid.user = request.user
                bid.save()
            else:
                return render(request, "auctions/listing.html",{
                    "auction_listing": listing,
                    "form": comment_form,
                    "comments": comment_obj,
                    "bidForm": bid_form,
                    "bids": bid_obj,
                    "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids.",
                    "watchlistForm": watchlist_form
                })

        #checks if watchlist form is valid
        if watchlist_form.is_valid():
            if watchlist_form.instance.add_to_watchlist == False:
                watchlist_form.instance.user = request.user
                watchlist_form.instance.add_to_watchlist = True
                watchlist = watchlist_form.save()
                watchlist.listings.add(listing)
                return render(request, "auctions/listing.html",{
                    "auction_listing": listing,
                    "form": comment_form,
                    "comments": comment_obj,
                    "bidForm": bid_form,
                    "bids": bid_obj,
                    "watchlistForm": watchlist_form,
                    "watchlist": "Add to Watchlist"
                })
                #return redirect('listing', id=id)
            else:
                watchlist_form.instance.user = request.user
                watchlist_form.instance.add_to_watchlist = False
                watchlist = watchlist_form.save()
                watchlist.listings.delete(listing)
                return redirect('listing', id=id)
            
        #checks if closelisting form is valid
        if closelisting_form.is_valid():
            return render(request, "auctions/listing.html",{
                "auction_listing": listing,
                "form": comment_form,
                "comments": comment_obj,
                "bidForm": bid_form,
                "bids": bid_obj,
                "watchlistForm": watchlist_form
            })
        
        #what to do if none of the forms are submitted
        else:
            return render(request, "auctions/listing.html",{
                "auction_listing": listing,
                "form": comment_form,
                "comments": comment_obj,
                "bidForm": bid_form,
                "bids": bid_obj,
                "watchlistForm": watchlist_form
            })
    return render(request, "auctions/listing.html",{
        "auction_listing": listing,
        "form": comment_form,
        "comments": comment_obj,
        "bidForm": bid_form,
        "bids": bid_obj,
        "watchlistForm": watchlist_form
    })

models.py

class Listings(models.Model):
    CATEGORY = [
    ("Miscellaneous", "Miscellaneous"),
    ("Movies and Television", "Movies and Television"),
    ("Sports", "Sports"),
    ("Arts and Crafts", "Arts and Crafts"),
    ("Clothing", "Clothing"),
    ("Books", "Books"),
]
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=500)
    bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
    image = models.URLField(null=True, blank=True)
    category = models.CharField(max_length=64, choices=CATEGORY, default=None)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")

class Comments(models.Model):
    listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    comment = models.CharField(max_length=500)

class Bids(models.Model):
    listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)

class WatchList(models.Model):
    listings = models.ManyToManyField(Listings)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    add_to_watchlist = models.BooleanField(default=False)

class CloseListing(models.Model):
    listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    close_listing = models.BooleanField(default=False, null=False)

watchListForm

class WatchListForm(forms.ModelForm):
    class Meta:
        model = WatchList
        fields = ['add_to_watchlist']
        widgets = {'add_to_watchlist': forms.HiddenInput()}

The following is the current code that I am using that still does not fix the problem of changing the button.

views.py

@login_required(login_url='login')
def listing(request, id):
    #gets listing
    listing = get_object_or_404(Listings.objects, pk=id)
    #code for comment and bid forms
    listing_price = listing.bid
    sellar = listing.user
    comment_obj = Comments.objects.filter(listing=listing)
    #types of forms
    comment_form = CommentForm()
    bid_form = BidsForm()
    #watchlist_form = WatchListForm()
    closelisting_form = CloseListingForm()
   
   #watchlist code
    add_or_remove_watchlist = ''
    try:
        has_watchlists = get_object_or_404(WatchList, Q(
            user=request.user) & Q(listing=listing))
    except:
        has_watchlists = False

    if has_watchlists:
        add_or_remove_watchlist = True
    else:
        add_or_remove_watchlist = False

    #code for the bid form
    bid_obj = Bids.objects.filter(listing=listing)
    other_bids = bid_obj.all()
    max_bid =0
    for bid in other_bids:
        if listing.bid > max_bid:
            max_bid = listing.bid

    #watchlist code
    if request.POST.get('add'):
        WatchList.objects.create(user=request.user, listing=listing)
        add_or_remove_watchlist = False
    elif request.POST.get('remove'):
        add_or_remove_watchlist = True
        has_watchlist.delete()

     #checks if request method is post for all the forms
    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        bid_form = BidsForm(request.POST)
        closelisting_form = CloseListingForm(request.POST)

        #checks if comment form is valid
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.listing = listing
            comment.user = request.user
            comment.save()

        #checks if bid form is valid
        if bid_form.is_valid():
            new_bid = bid_form.cleaned_data.get("bid")
            if (new_bid >= listing_price) and (new_bid > max_bid):
                bid = bid_form.save(commit=False)
                bid.listing = listing
                bid.user = request.user
                bid.save()
            else:
                return render(request, "auctions/listing.html",{
                    "auction_listing": listing,
                    "form": comment_form,
                    "comments": comment_obj,
                    "bidForm": bid_form,
                    "bids": bid_obj,
                    "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids."
                })

        #checks if closelisting form is valid
        if closelisting_form.is_valid():
            return render(request, "auctions/listing.html",{
                "auction_listing": listing,
                "form": comment_form,
                "comments": comment_obj,
                "bidForm": bid_form,
                "bids": bid_obj
            })
        
        #what to do if none of the forms are submitted
        else:
            return render(request, "auctions/listing.html",{
                "auction_listing": listing,
                "form": comment_form,
                "comments": comment_obj,
                "bidForm": bid_form,
                "bids": bid_obj
            })
    return render(request, "auctions/listing.html",{
        "auction_listing": listing,
        "form": comment_form,
        "comments": comment_obj,
        "bidForm": bid_form,
        "bids": bid_obj
    })

listing.html

{% block body %}

    <img src ="{{ auction_listing.image }}" style = "height: 10%; width: 10%;">
    <h4 class = "text">{{ auction_listing.title }}</h4>
    <h6>Description: {{ auction_listing.description }}</h6>
    <h6>Category: {{ auction_listing.category }}</h6> 
    <h6>By: {{ auction_listing.user }}</h6>
    <h6>Price: ${{ auction_listing.bid }}</h6>

    {% if closeListingForm %}
        <form action = "{% url 'listing' auction_listing.id %}" method = "POST">
            {% csrf_token %}
            {{ closeListingForm }}
        </form>
    {% endif %}


    <!--watchlist form-->
    {% if watchlist_message %}
        <div>{{ watchlist_message }}</div>
    {% endif %}

    <form action = "{% url 'listing' auction_listing.id %}" method = "POST">
        {% csrf_token %}
        {% if watchlist %}
            <input type="submit" value='Remove from watchlist' name='remove'>
        {% else %}
            <input type="submit" value='Add to watchlist' name='add'>
        {% endif %}
    </form>
    
    <br>
    <!--bid form-->
    {% if message %}
        <div>{{ message }}</div>
    {% endif %}

    <form action = "{% url 'listing' auction_listing.id %}" method = "POST" name = "newBid">
        {% csrf_token %}
        {{ bidForm }}
        <input type = "submit" value = "Place Bid">
    </form>

    <br>
    {% for bid in bids %}
        <h6>${{ bid.bid }} <div style = "font-family: monospace;">Bid By: {{ bid.user }}</div></h6>
    {% endfor %} 

    <!--comment form-->
    <br>
    <form action = "{% url 'listing' auction_listing.id %}" method = "POST">
        {% csrf_token %}
        {{ form }}
        <input type = "submit" value = "Add Comment">
    </form>

    <br>
    {% for comment in comments %}
        <h6> {{ comment.comment }} <div style = "font-family: monospace;">Comment By: {{ comment.user }}</div></h6>
    {% endfor %}

{% endblock %}

I have removed the WatchListForm.

Solution

I have another approach, by creating listing field a ForeignKey in WatchList model and no need to make add_to_watchlist field.

models.py

class WatchList(models.Model):
    listing = models.ForeignKey(Listings, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default='')

admin.py

from some_app_name.models import WatchList
@admin.register(WatchList)
class WatchListAdmin(admin.ModelAdmin):
    list_display = ['id', 'listing', 'user']

listing.html or template file:

<form action = "{% url 'listing' auction_listing.id %}" method = "POST">
    {% csrf_token %}
    {% if watchlist %}
        <input type="submit" value='Remove from watchlist' name='remove'>
    {% else %}
        <input type="submit" value='Add to watchlist' name='add'>
    {% endif %}
</form>

views.py

def listing(request, id):
    # gets listing
    listing = get_object_or_404(Listings, pk=id)
    # code for comment and bid forms
    listing_price = listing.bid
    sellar = listing.user
    comment_obj = Comments.objects.filter(listing=listing)
    # types of forms
    comment_form = CommentsForm()
    bid_form = BidsForm()
    closelisting_form = CloseListingForm()
    
    """-----------------This below code is handling the watchlist--------------------"""
    
    add_or_remove_watchlist = ''
    try:
        has_watchlists = get_object_or_404(WatchList, Q(
            user=request.user) & Q(listing=listing))
    except:
        has_watchlists = False

    if has_watchlists:
        add_or_remove_watchlist = True
    else:
        add_or_remove_watchlist = False
    
    """-----------------This above code is handling the watchlist--------------------"""
    bid_obj = Bids.objects.filter(listing=listing)
    other_bids = bid_obj.all()
    max_bid = 0
    for bid in other_bids:
        if listing.bid > max_bid:
            max_bid = listing.bid

    if request.method == "POST":
        comment_form = CommentsForm(request.POST)
        bid_form = BidsForm(request.POST)
        closelisting_form = CloseListingForm(request.POST)
   """-----------------This below code is handling watchlist--------------------"""
        
        if request.POST.get('add'):
            WatchList.objects.create(user=request.user, listing=listing)
            add_or_remove_watchlist = False
        elif request.POST.get('remove'):
            add_or_remove_watchlist = True
            has_watchlists.delete()
        
"""-----------------The above code is handling watchlist--------------------"""

        # checks if comment form is valid
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.listing = listing
            comment.user = request.user
            comment.save()

        # checks if bid form is valid
        if bid_form.is_valid():
            new_bid = bid_form.cleaned_data.get("bid")
            if (new_bid >= listing_price) and (new_bid > max_bid):
                bid = bid_form.save(commit=False)
                bid.listing = listing
                bid.user = request.user
                bid.save()
            else:
                return render(request, "auctions/listing.html", {
                    "auction_listing": listing,
                    "form": comment_form,
                    "comments": comment_obj,
                    "bidForm": bid_form,
                    "bids": bid_obj,
                    "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids.",
                })
        if closelisting_form.is_valid():
            return render(request, "auctions/listing.html", {
                "auction_listing": listing,
                "form": comment_form,
                "comments": comment_obj,
                "bidForm": bid_form,
                "bids": bid_obj,
            })

        return redirect('listing', id=id)

    return render(request, "auctions/listing.html", {
        "auction_listing": listing,
        "form": comment_form,
        "comments": comment_obj,
        "bidForm": bid_form,
        "bids": bid_obj,
        "watchlist": add_or_remove_watchlist
    })

Also, no need to make WatchListForm so totally remove it.




Edit: Try below view

views.py

from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django import forms
from django.contrib.auth.decorators import login_required
from .models import User, Listings, Comments, Bids, WatchList, CloseListing
from .forms import ListingsForm, CommentForm, BidsForm, CloseListingForm
from django.shortcuts import get_object_or_404, redirect
from django.db.models import Q #you have not import Q


@login_required(login_url='login')
def listing(request, id):
    # gets listing
    listing = get_object_or_404(Listings, pk=id)
    # code for comment and bid forms
    listing_price = listing.bid
    sellar = listing.user
    comment_obj = Comments.objects.filter(listing=listing)
    # types of forms
    comment_form = CommentForm()
    bid_form = BidsForm()
    #watchlist_form = WatchListForm()
    closelisting_form = CloseListingForm()

   # watchlist code
    add_or_remove_watchlist = ''
    try:
        has_watchlists = get_object_or_404(WatchList, Q(
            user=request.user) & Q(listing=listing))
        print('--------------------------')
        print(has_watchlists)
        print('--------------------------')
    except:
        has_watchlists = False

    if has_watchlists:
        add_or_remove_watchlist = True
    else:
        print('it will from remove')
        add_or_remove_watchlist = False

    # code for the bid form
    bid_obj = Bids.objects.filter(listing=listing)
    other_bids = bid_obj.all()
    max_bid = 0
    for bid in other_bids:
        if listing.bid > max_bid:
            max_bid = listing.bid

     # checks if request method is post for all the forms
    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        bid_form = BidsForm(request.POST)
        closelisting_form = CloseListingForm(request.POST)

        # watchlist code
        if request.POST.get('add'):
            WatchList.objects.create(user=request.user, listing=listing)
            add_or_remove_watchlist = False
        elif request.POST.get('remove'):
            add_or_remove_watchlist = True
            has_watchlists.delete()

        # checks if comment form is valid
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.listing = listing
            comment.user = request.user
            comment.save()
        else:
            return redirect('listing', id=id)
        # checks if bid form is valid
        if bid_form.is_valid():

            new_bid = bid_form.cleaned_data.get("bid")
            if (new_bid >= listing_price) and (new_bid > max_bid):
                bid = bid_form.save(commit=False)
                bid.listing = listing
                bid.user = request.user
                bid.save()
            else:
                return render(request, "auctions/listing.html", {
                    "auction_listing": listing,
                    "form": comment_form,
                    "comments": comment_obj,
                    "bidForm": bid_form,
                    "bids": bid_obj,
                    "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids."
                })

        else:
            return redirect('listing', id=id)

        # checks if closelisting form is valid
        if closelisting_form.is_valid():
            return render(request, "auctions/listing.html", {
                "auction_listing": listing,
                "form": comment_form,
                "comments": comment_obj,
                "bidForm": bid_form,
                "bids": bid_obj
            })
        else:

            return redirect('listing', id=id)

    return render(request, "auctions/listing.html", {
        "auction_listing": listing,
        "form": comment_form,
        "comments": comment_obj,
        "bidForm": bid_form,
        "bids": bid_obj,
        "watchlist": add_or_remove_watchlist
    })

Answered By – Sunderam Dubey

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.