Reputation: 32
My code:
{% if request.user.is_staff %}
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">
Create A Post
</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">
Post
</button>
</div>
</form>
</div>
{% endblock content %}
{% else %}
<head>
<meta http-equiv="refresh" content="5; url=/" />
</head>
<body>
<h1>Restricted Access To Staff!</h1>
<p>You will be redirected to the home page in 5 seconds</p>
</body>
{% endif %}
I can't figure out why it is not working, could it be something to do with the {% if request.user.is_staff %} bit?
Upvotes: 1
Views: 251
Reputation: 477684
As the documentation on template inheritance says:
If you use
{% extends %}
in a template, it must be the first template tag in that template. Template inheritance won’t work, otherwise.
You thus can not work with a {% if … %} … {% else %} … {% endif %}
template tag [Django-doc] to determine whether or not to inherit.
You can move this logic to the view, so:
def some_view(request):
# …
if request.user.is_staff:
return render(request, 'my_template.html', context)
else:
return render(request, 'my_other_template.html', context)
It might be better to develop a decorator that will automatically check if the user is a staff member, and render content properly, something like:
from functools import wraps
def requires_staff_redirect(f):
@wraps(f)
def g(request, *args, **kwargs):
if not request.user.is_staff:
return render(request, 'my_other_template.html')
else:
return f(*args, **kwargs)
return g
Then we can decorate a view like:
@requires_staff_redirect
def my_view(request):
# …
and then it will only trigger the view if the user is a staff member, otherwise it will render the my_other_template.html
page.
Upvotes: 1