Home > Back-end >  Django - If statement with request.user
Django - If statement with request.user

Time:08-25

I have a problem with an if-statement. I just want to check on a page if the user who requests the listing page is the same one as the user who won the listing on that page.

My view looks like this:

def show_closed_listing(request, listing_id):
    closed_listing = InactiveListing.objects.get(id=listing_id)
    field_name = "winning_user"
    winning_user = getattr(closed_listing,field_name)
    message = False
    print(request.user)
    print(winning_user)
    if request.user == winning_user:
        print("This is good")
        message = "You have won this listing!"
    else:
        print("Not good")
    return render(request, "auctions/closed_listing.html", {
        "closed_listing" : closed_listing,
        "message" : message
    })

When I visit a page, signed in as Test2, when Test2 has won the listing, my terminal shows as follows:

  • Test2
  • Test2
  • Not good

As also can be seen here

I don't get why request.user and winning_user look the same, but the if-statement is false?

If needed, here is my model:

class InactiveListing(models.Model):
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=512, default="")
    winning_user = models.CharField(max_length=128)
    winning_price = models.DecimalField(max_digits=6, decimal_places=2, default=0.01)
    def __str__(self):
        return self.title

CodePudding user response:

winning_user is not a User instance. It would be the username, or ID, or any field, but not a User. You'd need a ForeignKey for that.

Try comparing:

winning_user == request.user.username: # Or winning_user == str(request.user) if you've edited the __str__ method like below.

They look the same, because I'm guessing you have this on your user model:

def __str__(self):
    return self.username
  • Related