sami
sami

Reputation: 19

How to write a condition use django queryset

I write a if else statement to user but it not working. I get data form database use Post.objects.get(sno = delpk). Then i writer a condition request.user.username == Post.author

def postdelapi(request):
 if request.method == 'POST':
    delpk = request.POST['delpk']
    deletepost = Post.objects.get(sno = delpk)
    print(Post.author)
    if request.user.username == Post.author :
        deletepost.delete()
    else:
        HttpResponse('eroor')
 else:
    pass
 return redirect('home')

Upvotes: 0

Views: 47

Answers (2)

FluidLight
FluidLight

Reputation: 471

Post.author is most likely a User model (check your models.py to confirm) therefore should be compared with an equivalent User model which is request.user and not request.user.username:

if request.user == Post.author :
        deletepost.delete()

It is best if you compare the User instance instead of usernames in the case of users changing usernames and/or having duplicate usernames.

Upvotes: 0

Kimhong Muong
Kimhong Muong

Reputation: 96

you need to compare request.user.username with Post's object which is deletepost.

if request.user.username == deletepost.author.username :
    deletepost.delete()

Upvotes: 1

Related Questions