Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django, how do I know the currently logged-in user?

Tags:

django

login

In Django, how do I know the currently logged-in user?

like image 248
JasonYun Avatar asked Sep 25 '09 13:09

JasonYun


People also ask

How do you know if a user is logged in in Django?

Check the Logged in User in Views in Django We can use request. user. is_authenticated to check if the user is logged in or not. If the user is logged in, it will return True .

How can I see active users in Django?

# the password verified for the user if user. is_active: print("User is valid, active and authenticated") else: print("The password is valid, but the account has been disabled!") else: # the authentication system was unable to verify the username and password print("The username and password were incorrect.")

How do you check a user is superuser or not?

Superuser privileges are given by being UID (userid) 0. grep for the user from the /etc/password file. The first numeric field after the user is the UID and the second is the GID (groupid). If the user is not UID 0, they do not have root privileges.


1 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

like image 64
vikingosegundo Avatar answered Oct 23 '22 16:10

vikingosegundo