How to get the django Current login user?
A:
Useful link:
Edit:
Can you provide an example what you want to achieve by getting the current User? Cause it really vague...
bastianneu
2009-09-25 13:48:45
+3
A:
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
vikingosegundo
2009-09-25 13:55:51
Just a note, in save_formset -> set_user, it should be if not hasattr(instance,'created_by')
FurtiveFelon
2010-06-15 19:56:01
A:
If I understood your question, you want to get access to the current user, regardless where you are.
One way would be caching the user, or the current request, into the threadlocals.
This link can help you: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
KOkon
2010-01-22 22:46:50