29👍
Joseph’s answer is fine for your simple case, but in reality neither is_staff
nor is_superuser
is a perfect fit. Assuming your page is, say, /polls/
(a list of Poll
objects, in an app called poll
), you should test the specific poll.change_poll
and poll.delete_poll
permissions.
In a template:
{% for poll in polls %}
{% if perms.poll.change_poll %}<a href='/polls/edit/{{ poll.id }}'>Edit</a>{% endif %}
{% if perms.poll.delete_poll %}<a href='/polls/delete/{{ poll.id }}'>Delete</a>{% endif %}
{% endfor %}
Or in a view using has_perm
:
if not request.user.has_perm('poll.change_poll'):
return HttpResponseForbidden('Nope!')
Or in a view using a decorator:
@permission_required('poll.change_poll')
def edit_poll(request, poll_id):
# ....
You can assign these permissions directly to a user, to a group (and then put a user in that group) or by setting is_superuser
.
136👍
In templates:
{% if user.is_superuser %}
<p>Hello, admin.</p>
{% else %}
<p>Hello, ordinary visitor.</p>
{% endif %}
In views:
if request.user.is_superuser:
# Hello, admin.
else:
# Hello, ordinary visitor.
Depending on your needs, is_staff
might be a better fit than is_superuser
. You can read about the difference here.
- [Django]-Separation of business logic and data access in django
- [Django]-Choose test database?
- [Django]-Django order_by query set, ascending and descending
4👍
If you don’t care about the privileges a user has and just want to make sure they are logged in, you can use user.is_anonymous
, which will be true if the user is logged out and false if they are logged in.
By default, user.is_staff
is required for the user to have access to the Django Admin.
- [Django]-Django middleware difference between process_request and process_view
- [Django]-Add class to form field Django ModelForm
- [Django]-Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields