-3

I have a Django template that contains a message with a variable, but the words that are not in the variable appear all the time. I think it has something to do with the conditional if closeListing == True. I explicitly state when I want it to be True, so I don't know what's happening.

views.py

@login_required(login_url='login')
def listing(request, id):
    #gets listing
    listing = get_object_or_404(Listings.objects, pk=id)
    sellar = listing.user

    #close listing code
    if sellar == request.user:
        closeListingButton = True
    else: 
        closeListingButton = False

    closeListing = ''

    try:
        has_closed = get_list_or_404(CloseListing, Q(user=request.user) & Q(listings=listing))
    except:
        has_closed = False

    if has_closed:
        closeListing = False
    else: 
        closeListing = True

   if request.method == "POST":
        #close listing code
        if request.POST.get('close'):
            CloseListing.objects.create(user=request.user, listings=listing)
            closeListing = True
            closeListingButton = False
            add_or_remove_watchlist = True
            winning_bid = Bids.objects.aggregate(Max('bid'))
            winning_bid = Bids.objects.latest('bid')
            winner = winning_bid.user

            return render(request, "auctions/listing.html",{
                        "auction_listing": listing,
                        "comments": comment_obj,
                        "bids": bid_obj,
                        "closeListingButton": closeListingButton,
                        "closeListing": closeListing,
                        "closedMessage": "This listing is closed.",
                        "winner": winner
            })

   return render(request, "auctions/listing.html",{
                 "auction_listing": listing,
                 "closeListingButton": closeListingButton, 
                 "closeListing": closeListing
  })

listing.html

{% if closeListing == True %}
     <div>
          {{ closedMessage }}
          <br>
          {{ winner }} has won the auction!
     </div>
{% endif %}
Damoiskii
  • 1,328
  • 1
  • 5
  • 20
skateb2020
  • 129
  • 11
  • Try putting {{ closeListing == True }} in your code and see what it evaluates as. Also try this link: https://stackoverflow.com/questions/8433450/why-doesnt-my-condition-logic-work-as-expected-in-jinja2-cherrypy – moosearch Jun 14 '22 at 19:44
  • 1
    You should use `{% if closeListing %}`. Please format your code because we can only guess identations. Maybe from your algorithm it's always True. – NixonSparrow Jun 14 '22 at 19:45
  • @moosearch, {{ closeListing == True }} created an error while using a lowercase t causes it to never show up. – skateb2020 Jun 14 '22 at 19:51
  • @NixonSparrow, the way I have the code is how it is supposed to be indented. Your code works, but when you leave that particular webpage and come back to it the variables are missing and only the other text is visible. How do I make the variables show up all the time? – skateb2020 Jun 14 '22 at 19:54
  • 2
    @skateb2020 Could you explain the double return statements in your code? Formatting error? Could be causing your missing variables if ```request.POST.get('close')``` is ```None``` – moosearch Jun 14 '22 at 20:06
  • @skateb2020 If identations are correct, then second `return` is unreachable. So `closeListing = True` will be always like that. – NixonSparrow Jun 14 '22 at 20:08
  • @moosearch, I should not have included that. I have other forms that come after the closeListing code that I have not included that is the return for them. – skateb2020 Jun 14 '22 at 20:08
  • closeListing will be ```True``` if either the object is not in the CloseList table or ```request.POST.get('close')``` is not ```None```. Is that your intended behaviour? – moosearch Jun 14 '22 at 20:21
  • @moosearch, no, I want it to be True if it is in the CloseListing Model or if ```request.POST.get('close')``` has happened. – skateb2020 Jun 14 '22 at 20:47
  • @skateb2020 "I want it to be True if it is in the CloseListing Model". Look at ```if has_closed:``` and you will see ```closeListing``` be False if it exists – moosearch Jun 14 '22 at 23:34

1 Answers1

0

If the intended behaviour is to have closeListing = True when the query of get_list_or_404(CloseListing, Q(user=request.user) & Q(listings=listing)) returned some result or if request.POST.get('close') then you should probably modify here:

if has_closed:
    closeListing = False
else: 
    closeListing = True

To...

try:
    # Returned some result
    has_closed = get_list_or_404(CloseListing, Q(user=request.user) & Q(listings=listing))
except:
    has_closed = False

# You're saying here if any results were returned then set closeListing = True
if has_closed:
    closeListing = True
else: 
    closeListing = False

I see you already have closeListing = True if the request.POST.get('close') is not None already which is good.

Then in your template, you can have:

{% if closeListing %}
     <div>
          {{ closedMessage }}
          <br>
          {{ winner }} has won the auction!
     </div>
{% endif %}

UPDATE

To facilitate the {{ winner }} and {{ closedMessage }} variables when it's a get request but info exists in the CloseListing model, then you'll have to do this within the listing view:

# I'm starting below the try block...
# I'd suggest creating a dictionary to pass as the context...
context = {}

if has_closed:
     closeListing = True
     
     # Not sure which of these you were using 'Bids.objects.aggregate(Max('bid'))' or 'Bids.objects.latest('bid')'
     winning_bid = Bids.objects.aggregate(Max('bid'))
     winning_bid = Bids.objects.latest('bid')

     winner = winning_bid.user

     # Add the winner and closedMessage to the context dictionary from here since they are in the CloseListing model
     context['winner'] = winner
     context['closedMessage'] = "This listing is closed."
else: 
     closeListing = False


if request.method == "POST":
     #close listing code
     if request.POST.get('close'):
          ...

context['auction_listing'] = listing
context['closeListingButton'] = closeListingButton
context['closeListing'] = closeListing

return render(request, "auctions/listing.html", context)

Ideally, that should solve the overall issue.

Damoiskii
  • 1,328
  • 1
  • 5
  • 20
  • what should I add where you commented modify here because I changed the rest and it still doesn't work the way I want it to. – skateb2020 Jun 15 '22 at 00:58
  • I mean you should change the assignment within the `if statement`. So `if has_closed` you should have `closeListing = True` and not `False`. – Damoiskii Jun 15 '22 at 01:18
  • I did that but if you refresh the page or go to another page and return back the ```{{ closedMessage }}``` and ```{{ winner }}``` variables no longer appear just the surrounding text. How do I make it so that whenever a listing is inside the CloseListing model, the variables and text always appears. – skateb2020 Jun 15 '22 at 02:11
  • I've updated the answer bro. See the updates. – Damoiskii Jun 15 '22 at 08:09
  • the code only works right after the button corresponding with ```request.POST.get('close')``` is pressed. How do I make it so that whenever you visit a listing that is within the CloseListing Model the messages appear because that is still not happening? – skateb2020 Jun 15 '22 at 14:25
  • Have you added the updated part of the answer? – Damoiskii Jun 15 '22 at 14:54
  • yes, I am using your updated code. If you close the listing and refresh the page, the message stays, but if you go to a different page within the web application and then return to this page the message is gone. – skateb2020 Jun 15 '22 at 15:22
  • I have little to work with here so I'm not sure I'm understanding what's the problem now... But try doing these `print` statements... `print` flag 1 inside of the `if has_closed` portion of the code. `if had_closed: print('flag 1')`, then inside the else portion `print` flag 2... `else: print('flag 2')`. Tell me which of them prints whenever you go to a different page and return. – Damoiskii Jun 15 '22 at 15:41
  • flag 1 prints. Would you like to look at my code through Github? – skateb2020 Jun 15 '22 at 16:01
  • Flag 1 would indicate that the item is in the `CloseListing model`. Yeah, you could let me take a view there. Let's take this discussion to a chatroom. – Damoiskii Jun 15 '22 at 16:08
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/245640/discussion-between-damoiskii-and-skateb2020). – Damoiskii Jun 15 '22 at 16:08