In Django, how can I find out that you are currently logged in?

In Django, how do I recognize a registered user at the moment?

+71
django login
Sep 25 '09 at 13:35
source share
3 answers

Where do you need to know the user?

In the view, the user is indicated in the request as request.user .

For user handling in templates see here

If you want to save the creator or editor of the model 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 don’t know where anymore

+97
Sep 25 '09 at 13:55
source share

The @vikingosegundo extension of the answer, if you want to get the username inside the models, I found a way that involves declaring MiddleWare. Create a file called get_username.py inside your application 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 MIDDLEWARE_CLASSES :

 MIDDLEWARE_CLASSES = ( ... 'yourapp.get_username.RequestMiddleware', ) 

Now, in your save() method, you can get the current username as follows:

 from get_username import get_username ... def save(self, *args, **kwargs): req = get_username() print "Your username is: %s" % (req.user) 
+5
Mar 31 '16 at 9:53
source share

Django 1.9.6 project by default has user in default templates

So you can directly write things like this:

 {% if user.is_authenticated %} {{ user.username }} {% else %} Not logged in. {% endif %} 

This functionality is provided by the django.contrib.auth.context_processors.auth context django.contrib.auth.context_processors.auth in settings.py .

Asked question about the template: How to access the user profile in the Django template?

+3
May 9 '16 at 8:12
source share



All Articles