简体   繁体   English

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

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

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

Where do you need to know the user? 你在哪里需要了解用户?

In views the user is provided in the request as request.user . 视图中 ,用户在请求中作为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 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 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 我在互联网上找到了这个,但我不知道在哪里

Extending @vikingosegundo's answer, if you want to get the username inside Models, I found a way that involves declaring a MiddleWare. 扩展@ vikingosegundo的答案,如果你想获得Models中的用户名,我找到了一种涉及声明MiddleWare的方法。 Create a file called get_username.py inside your app, with this content: 在您的应用内创建一个名为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

Edit your settings.py and add it to the MIDDLEWARE_CLASSES : 编辑您的settings.py并将其添加到MIDDLEWARE_CLASSES

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

Now, in your save() method, you can get the current username like this: 现在,在save()方法中,您可以获得如下的当前用户名:

from get_username import get_username

...

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

Django 1.9.6 default project has user in the default templates Django 1.9.6默认项目在默认模板中有user

So you can write things like this directly: 所以你可以直接写这样的东西:

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

This functionality is provided by the django.contrib.auth.context_processors.auth context processor in settings.py . 此功能由settings.pydjango.contrib.auth.context_processors.auth上下文处理器提供。

Dedicated template question: How to access the user profile in a Django template? 专用模板问题: 如何在Django模板中访问用户配置文件?

You just need to request current user:您只需要请求当前用户:

 def foo():
         current_user = request.user
         return print(current_user)
 foo()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Django将一个页面显示给已登录的用户,将另一个页面显示给未登录的用户? - How do I show one page to logged-in user and another to a not-logged in user with Django? 如何在 Django 中获取登录用户的用户名? - How can I get the username of the logged-in user in Django? Django:如何在基于 class 的视图中获取登录用户的用户名? - Django: How do I get the username of the logged-in user in my class based view? Django自定义管理器 - 如何仅返回登录用户创建的对象? - Django custom managers - how do I return only objects created by the logged-in user? Django:过滤当前登录用户的 ListView(多多多场) - Django: Filter ListView on currently logged-in user (manytomanyfield) 如何过滤当前登录用户的 Django 表单下拉列表(基于类的视图) - How to filter Django Form dropdown for currently logged-in user (Class Based Views) 我如何查看Django中已登录用户以外的用户信息? - How can I see user information other than the logged-in user in Django? 在 Django 模板中显示当前登录用户喜欢的所有用户配置文件(在 ManytoMany 字段下) - Display all User profiles, in Django template, liked by the currently logged-in User (under ManytoMany field) 如何在Django views.py中获取登录用户的用户名 - How can I get the username of the logged-in user in Django views.py Django - 按当前登录用户的车辆过滤帖子表单选项 - Django - Filtering Post Form option by currently logged-in User's Vehicle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM