Answer the question
In order to leave comments, you need to log in
How to check for admin in Django template?
I inherited a working site-catalog on Django. Having previously only worked with PHP on the backend, I ran into one problem regarding checking admin rights in the template (although they say that everything worked before ... as usual) I have the following in the index.html
template :
{% if is_admin %}
<a href="#" class="edit-button">Edit</a>
{% endif %}
from django.contrib.auth.models import User, Group
Answer the question
In order to leave comments, you need to log in
Let's go in order.
1. Django template engine. It accepts html as input (in fact, not only, but any text file) and a box with New Year's gifts (no) variables, the so-called context. When processing a template, the template engine replaces the special syntax {{ variable_name }} that it looks for in the context (the context is a normal key-value dictionary).
2. User. A user is a built-in user model in Django. You can replace it with your own, but 90% use this one. The authorization middleware receives the request object before it is passed to the View for processing. In 90% of cases, the built-in middleware from the django.contrib.auth module is again used. The middleware is poking around in cookies, finds the session_key and searches the database (in 90% of cases, you get it) which user this session corresponds to. After that, the property of the HttpRequest instance is added/modified. This attribute is assigned a User instance picked up from the database or, if the user is not authorized, AnonymousUser.
3. View calls the render function which takes a template and a context. to collect the context, the View class has a get_context method that collects the context into a heap. Even if you just wrote the most banal
class MyFuckingView(TemplateView):
template_name = 'some/module/template.html'
class MyFuckingView(TemplateView):
template_name = 'some/module/template.html'
def get_context(self):
ctx = super().get_context()
ctx['model_name'] = 'Sasha Grey'
ctx['category'] = 'Milf anal'
return ctx
{% if request.user.is_admin %}
<a href="#" class="edit-button">Edit</a>
{% endif %}
{% if user.is_superuser %}
# Hello, admin.
{% endif %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question