Get user information in django templates

An alternate method for current Django versions: {% if user.is_authenticated %} <p>Welcome, {{ user.get_username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} 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 … Read more

Change Django ModelChoiceField to show users’ full names rather than usernames

You can setup a custom ModelChoiceField that will return whatever label you’d like. Place something like this within a fields.py or wherever applicable. class UserModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() Then when creating your form, simply use that field UserModelChoiceField(queryset=User.objects.filter(is_staff=False), required = False) More info can be found here

Django’s self.client.login(…) does not work in unit tests

The code that doesn’t work: from django.contrib.auth.models import User from django.test import Client user = User.objects.create(username=”testuser”, password=’12345′) c = Client() logged_in = c.login(username=”testuser”, password=’12345′) Why doesn’t it work? In the snippet above, when the User is created the actual password hash is set to be 12345. When the client calls the login method, the value … Read more

Check permission inside a template in Django

If you are looking to check for permissions in templates, the following code would suffice: {% if perms.app_label.can_do_something %} <form here> {% endif %} Where model refers to the model that the user need permissions to see the form for. Refer to https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions for more examples. The currently logged-in user’s permissions are stored in the … Read more

How to deploy an HTTPS-only site, with Django/nginx?

For the 2nd part of John C’s answer, and Django 1.4+… Instead of extending HttpResponseRedirect, you can change the request.scheme to https. Because Django is behind Nginx’s reverse proxy, it doesn’t know the original request was secure. In your Django settings, set the SECURE_PROXY_SSL_HEADER setting: SECURE_PROXY_SSL_HEADER = (‘HTTP_X_FORWARDED_PROTO’, ‘https’) Then, you need Nginx to set … Read more

How can I detect multiple logins into a Django web application from different locations?

Not sure if this is still needed but thought I would share my solution: 1) Install django-tracking (thankyou for that tip Van Gale Google Maps + GeoIP is amazing!) 2) Add this middleware: from django.contrib.sessions.models import Session from tracking.models import Visitor from datetime import datetime class UserRestrictMiddleware(object): “”” Prevents more than one user logging in … Read more