0

In Django, what is the best option to check if a product belongs to a user?

I usually use this one:

def deleteProduct(request, pk):
    product= get_object_or_404(Product, pk=pk)
    if product.user.id == request.user.id:
       product.deleted=True
       product.save()
    else:
       raise PermissionDenied
Alasdair
  • 298,606
  • 55
  • 578
  • 516
Jota
  • 697
  • 10
  • 24
  • 1
    Your way seems good. In addition, `product.user == request.user` gives the same result. In fact, comparing model instances means comparing their primary keys, in your case, it is the `id` field of `django.contrib.auth.models.User'. have a look at https://stackoverflow.com/questions/2513342/django-comparing-model-instances-for-equality SO question, and https://docs.djangoproject.com/en/dev/topics/db/queries/#comparing-objects Django documentation. – ohannes Aug 15 '17 at 20:41
  • You might want to use the `login_required` decorator, so that only logged-in users can access the view. – Alasdair Aug 15 '17 at 21:38

0 Answers0