In a Laravel Blade template, I can do this to show code only if a user is logged in:
#auth
<div>Show code only if logged in.</div>
#endauth
Does Django have a template tag or something similar that does the equivalent? E.g.:
{% auth %}
<div>Show code only if logged in.</div>
{% endauth %}
In Django templates you should check for {% if user.is_authenticated %}. See this answer for more.
I'll answer my own question since I found more of what I was looking. In Django, they're called "decorators," e.g., #login_required.
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
...
Source: https://docs.djangoproject.com/en/3.2/topics/auth/default/#the-login-required-decorator
Added: 11/02/2021.
Related
How can i get the current user in a django template tags? (request object is not accessible)
Or how can i access to request object?
If you want to access the current user in a template tag, you must pass it as a parameter in the templates, like so:
{% my_template_tag user %}
Then make sure your template tag accepts this extra parameter. Check out the documentation on this topic. You should also check out simple tags.
The user is always attached to the request, in your templates you can do the following:
{% if user.is_authenticated %}
{% endif %}
You don't have to specify "request" to access its content
UPDATE:
Be aware: is_authenticated() always return True for logged user (User objects), but returns False for AnonymousUser (guest users). Read here: https://docs.djangoproject.com/en/1.7/ref/contrib/auth/
This question was already answered here:
{% if user.is_authenticated %}
<p> Welcome '{{ user.username }}'</p>
{% else %}
Login
{% endif %}
and make sure you have the request template context processor installed in your settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request',
...
)
Note:
Use request.user.get_username() in views & user.get_username in
templates. Preferred over referring username attribute directly.
Source
This template context variable is available if a RequestContext is used.
django.contrib.auth.context_processors.auth is enabled by default & contains the variable user
You do NOT need to enable django.core.context_processors.request template context processor.
Source : https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates
Suppose you have a profile page of every registered user, and you only want to show the edit link to the owner of the profile page (i.e., if the current user is accessing his/her profile page, the user can see the edit button, but the user can't see the edit button on other user's profile page.
In your html file:
<h2>Profile of {{ object.username }}</h2>
{% if object.username == user.username %}
Edit
{% endif %}
Then your urls.py file should contain:
from django.urls import path
from .views import ProfileUpdateView
urlpatterns = [
...
path('<int:pk>/profile/update', ProfileUpdateView.as_view(), name = 'profile_update'),
...
]
considering you have appropriate ProfileUpdateView and appropriate model
Django newbie here. Following the documentation, I am trying the following to get a link to the admin site from the homepage of the public site I'm building:
{% load admin_urls %}
<p>Go to the admin.</p>
I am getting the error:
NoReverseMatch at /
u'opts|admin_urlname' is not a registered namespace
I am including the URLs properly:
url(r'^admin/', include(admin.site.urls)),
My template loaders are in the right order.
I've tried a few different variations on this, and they all throw namespace errors.
Any ideas? Thanks!
After 30 minutes with Daniel Roseman / Django docs in one screen and my code in the other, I come up with this simple solution:
In your views.py, add the opts context with the _meta of the model (that includes the required app_label and model_name):
class YourModelDetailView(DetailView):
def get_context_data(self, **kwargs):
context = super(YourModelDetailView, self).get_context_data(**kwargs)
context["opts"] = YourModel._meta
return context
In your templates:
{% url opts|admin_urlname:'change' object.pk %}
Where change can be any action in the reverse admin urls documentation page.
While the above answers were helpful about the code I was calling, there is a much easier way. I'm using this instead:
{% url 'admin:index' %}
This works for custom admin views as well, like:
{% url 'admin:myapp_mymodel_<keyword>' object.id %}
Where keyword is from the named parameters listed here (i.e. add, change, delete).
You are almost certainly using the released 1.4 version, rather than the development version. As the documentation for that version shows, you need to use {% load url from future %} before you can use that syntax.
In Django what's the best way to implement templates with extra functionality for users with 'admin' permissions.
I'm not sure if I should create a set of completely different views specific for admins or integrate it into my existing views and templates like 'if user is an admin' everywhere.
Is there a standard way to do this in Django?
This will show the stuff only if you are active and staff not admin:
{% if request.user.is_active and request.user.is_staff %}
{% include "foo/bar.html" %}
{% endif %}
If you wanna show only and ONLY for admin you have to do that:
{% if request.user.is_superuser %}
ADD your admin stuff there.
{% endif %}
Differences about these fields here.
If you have the the user available in template context you can do:
{% if user.is_active and user.is_staff %}
Only the admin will see this code. For example include some admin template here:
{% include "foo/bar.html" %}
{% endif %}
User will be available in your template f you use RequestContext and your TEMPLATE_CONTEXT_PROCESSORS setting contains django.contrib.auth.context_processors.auth, which is default. See authentication data in templates as reference.
I'm an advocate of keeping as much logic out of the view layer (speaking generally about the MVC Design Pattern). So why not use decorators to direct your user to different views based upon their privilege? In your urls.py, define a pattern for admins:
url(r'^admin/$', 'user.views.admin_index'),
#do so for your other admin views, maybe more elegantly than this quick example
Then define a decorator to kick the user out if they're not an admin
def redirect_if_not_admin(fn):
def wrapper(request):
if request.user.is_staff():
return fn(request)
#or user.is_superuser(), etc
else:
return HttpResponseRedirect('/Permission_Denied/')
return wrapper
And in your admin views
#redirect_if_not_admin
def index(request):
##do your thing
It's more code than the other two answers, which are not wrong. It's just a personal preference to keep clutter down in the views.
I have project in Django 1.3. In order to show username in all pages I use such tags in base.html
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}.
loggout</p>
{% else %}
loggin
{% endif %}
But if I dont return context_instance=RequestContext(request) from view value of user in template is empty. The 'django.contrib.auth.context_processors.auth' is included to TEMPLATE_CONTEXT_PROCESSORS.
Is it possible automaticaly include user to all templates?
since django 1.3. use shortcuts.render function and dont warry about requestcontext including to your views
You've given the answer yourself. As long as you use a RequestContext, it will be included in all templates.
If you really find that too much work, you could use the (new in 1.3) TemplateResponse class.
Or simply create a context processor. See
http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors
Put this in context_processor.py
def root_categories(request):
return {
'user': request.user,
}
in settings.py add the context processor.
now in your template try: {{ user }}
In my template, I have the following:
<ul class="tabbed" id="network-tabs">
{% if user.is_authenticated %}
<li>My Account</li>
<li>Log Out</li>
{% else %}
<li>Log in</li>
<li>Register</li>
{% endif %}
</ul>
It seems to work fine, unless the page been created has a #login_required decorator, in which case the page works fine but the navigation appears as if the user is not logged in, even when they are.
You should check your view function to see where the user variable is coming from. Unless you're specifically passing user into the context from the view, that's your problem.
You do have access to request.user, though, and that will always return true in a template rendered from a view that has the #login_required decorator.
The reason I can tell you for certain that there's nothing wrong with the decorator, though, is that in the code for User and AnonymousUser (located in django.contrib.auth.models) the is_authenticated method strictly returns true for User and false for AnonymousUser. The decorator does not and cannot change that. And what that means is that your template isn't actually getting a User object where you're checking user.
To follow on from Gabriel's answer, is the user variable coming from the auth context processor? If it is, and you are using the render_to_response shortcut, you need to use a RequestContext instance.
from django.template import RequestContext
...
#login_required
def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))