Issue
I have a model called properties which contains product details with the respective user IDs. The user id is called uid in the model.
I wrote a function in views.py to get the products that are only posted by logged-in user. I use the filter method in it, but it's not working. How can I solve this?
def view_products(request):
try:
user = request.user.id
c = properties.objects.filter(uid=user,status=True)
return render(request,'view_products.html',{'c':c})
except:
txt = """<script>alert('You have no properties to view...');window.location='/userhome/';</script>"""
return HttpResponse(txt)```
Solution
From what I know, AnonymousUser
does have id
field, which can be even None
, and if you use .filter()
it does not raise exception. How do you want to handle except logic?
You should write it this way:
def view_products(request):
if request.user.is_authenticated:
user = request.user.id
c = properties.objects.filter(uid=user, status=True)
return render(request, 'view_products.html', {'c': c})
txt = """<script>alert('You have no properties to view...');window.location='/userhome/';</script>"""
return HttpResponse(txt)
is_authenticated
is flag/property where you can easily handle if user is authenticated (logged in) or not.
Answered By - Patryk SzczepaĆski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.