Issue
I know this might be a silly question but please don't laugh at me. I am struggling to understand this simple logic. I am not understating why this logic is not working where it means if request.user is not the owner of the object or the user is not an admin user. The first part of this logic works to prevent other users from overwriting the owner object but why second part not working where a user can be overwritten object if he is an admin user?
if (request.user != comment.user) or (not request.user.is_superuser):
why my above logic only working for if user != owner of the obj ? why admin user can't edit if he is an admin?
but this logic works on both part
if not (request.user.is_superuser or (request.user == blog.blog_author)):
Solution
Those two statements act differently because they are different. You can use De Morgan's laws to prove this.
When distributing a negation across an and
or or
, you need to change the or
to an and
, and vice versa.
Stated more formally, De Morgan's laws say that
- not (A or B) = (not A) and (not B)
- not (A and B) = (not A) or (not B)
Let's apply De Morgan's laws to the second example you give, to make it look more like the first example, without changing its meaning.
if not (request.user.is_superuser or (request.user == blog.blog_author)):
# Apply De Morgan
if (not request.user.is_superuser) and (not request.user == blog.blog_author):
# Combine not and equals into not equals
if (not request.user.is_superuser) and (request.user != blog.blog_author):
# Re-order terms
if (request.user != blog.blog_author) and (not request.user.is_superuser):
You can see that this is different from your first example:
if (request.user != comment.user) or (not request.user.is_superuser):
Without more context, I can't say whether an and
or an or
is correct here, but that's why the two statements act differently.
Answered By - Nick ODell
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.