In Django, how do I know the currently logged-in user?
-
1Duplicate of your previous question? http://stackoverflow.com/questions/1476596/login-code-for-django – Abizern Sep 25 '09 at 13:42
-
8@Abizem, no that is not a duplicate of this question at all. – Kirk Woll Aug 09 '12 at 17:15
3 Answers
Where do you need to know the user?
In views the user is provided in the request as request.user
.
For user-handling in templates see here
If you want to save the creator or editor of a model's instance you can do something like:
model.py
class Article(models.Model):
created_by = models.ForeignKey(User, related_name='created_by')
created_on = models.DateTimeField(auto_now_add = True)
edited_by = models.ForeignKey(User, related_name='edited_by')
edited_on = models.DateTimeField(auto_now = True)
published = models.BooleanField(default=None)
admin.py
class ArticleAdmin(admin.ModelAdmin):
fields= ('title','slug','text','category','published')
inlines = [ImagesInline]
def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
if not hasattr(instance,'created_by'):
instance.created_by = request.user
instance.edited_by = request.user
instance.save()
form.save_m2m()
return instance
def save_formset(self, request, form, formset, change):
def set_user(instance):
if not instance.created_by:
instance.created_by = request.user
instance.edited_by = request.user
instance.save()
if formset.model == Article:
instances = formset.save(commit=False)
map(set_user, instances)
formset.save_m2m()
return instances
else:
return formset.save()
I found this on the Internet, but I don't know where anymore

- 52,040
- 14
- 137
- 178
-
4Just a note, in save_formset -> set_user, it should be if not hasattr(instance,'created_by') – FurtiveFelon Jun 15 '10 at 19:56
-
-
Why would you do that? (please create a new question, my django days are long gone) – vikingosegundo Mar 18 '16 at 14:11
-
@vikingosegundo I was just wondering why you don't use Django anymore? Don't you do back-end development anymore or have you moved on to NodeJS? – Alfa Bravo Jun 19 '18 at 14:27
-
I am currently working exclusively as an iOS developer, but from time to time for prototyping purposes Django is still the weapon of choice for me. – vikingosegundo Jun 19 '18 at 15:12
-
1for some reason it didn't work for me using the inner function `set_user` and then mapping it through `instances`. It just didn't save new models into database. I had to use a `for instance in instances:` with the `set_user` body inside the loop and worked perfectly. Additionally, I think the `if formset.model == Article` should be `if formset.model == Image`. Thanks @vikingosegundo for your answer. I was hitting my head to the keyboard for days trying to solve this!! – ekauffmann Feb 21 '19 at 14:40
Extending @vikingosegundo's answer, if you want to get the username inside Models, I found a way that involves declaring a MiddleWare. Create a file called get_username.py
inside your app, with this content:
from threading import current_thread
_requests = {}
def get_username():
t = current_thread()
if t not in _requests:
return None
return _requests[t]
class RequestMiddleware(object):
def process_request(self, request):
_requests[current_thread()] = request
Edit your settings.py
and add it to the MIDDLEWARE_CLASSES
:
MIDDLEWARE_CLASSES = (
...
'yourapp.get_username.RequestMiddleware',
)
Now, in your save()
method, you can get the current username like this:
from get_username import get_username
...
def save(self, *args, **kwargs):
req = get_username()
print "Your username is: %s" % (req.user)

- 13,691
- 9
- 45
- 62
-
Dedicated thread: http://stackoverflow.com/questions/10991460/django-get-current-user-in-model-save – Ciro Santilli OurBigBook.com May 09 '16 at 08:03
-
@nKn is the really dedicated MiddleWare necessary to invoke `get_username()` in `Models` object? If so, it would be nice to have a link to a canonical docs regarding that. Are there updated native django functions in 1.9.5 to do the same? – alvas May 30 '16 at 07:25
Django 1.9.6 default project has user
in the default templates
So you can write things like this directly:
{% if user.is_authenticated %}
{{ user.username }}
{% else %}
Not logged in.
{% endif %}
This functionality is provided by thedjango.contrib.auth.context_processors.auth
context processor in settings.py
.
Dedicated template question: How to access the user profile in a Django template?

- 1
- 1

- 347,512
- 102
- 1,199
- 985