在Django中,我如何知道当前登录的用户?

时间:2009-09-25 13:35:45

标签: django login

在Django中,我如何知道当前登录的用户?

3 个答案:

答案 0 :(得分:106)

您需要在哪里了解用户?

views 中,请求中的用户名为request.user

对于模板中的用户处理,请参阅here

如果您要保存模型实例的创建者或编辑者,您可以执行以下操作:

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()

我在互联网上找到了这个,但我不知道在哪里

答案 1 :(得分:6)

扩展@ vikingosegundo的答案,如果你想获得Models中的用户名,我找到了一种涉及声明MiddleWare的方法。在您的应用内创建一个名为get_username.py的文件,其中包含以下内容:

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

修改您的settings.py并将其添加到MIDDLEWARE_CLASSES

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

现在,在您的save()方法中,您可以获得如下的当前用户名:

from get_username import get_username

...

def save(self, *args, **kwargs):
    req = get_username()
    print "Your username is: %s" % (req.user)

答案 2 :(得分:4)

Django 1.9.6默认项目在默认模板中有user

所以你可以直接写这样的东西:

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

此功能由django.contrib.auth.context_processors.auth中的settings.py上下文处理器提供。

专用模板问题:How to access the user profile in a Django template?