简体   繁体   English

如何在admin.py中访问当前用户

[英]How to access current user in admin.py

In my admin.py file I am trying to display a time as the logged in users timezone. 在我的admin.py文件中,我试图将时间显示为登录用户的时区。 If I have something like below how can I pass in the request also to access the request.user.userprofile so I can dynamically set the timezone? 如果我有类似下面的内容,我如何也可以传入请求以访问request.user.userprofile,以便可以动态设置时区?

class CapAdmin(admin.ModelAdmin):
...
list_display = ('time_clicked', 'source_name', 'link')
....

    def time_clicked(self, instance):
        local_tz = pytz.timezone('America/Chicago') # I want the user timezone here
        local_dt = instance.click_time.replace(tzinfo=pytz.utc).astimezone(local_tz)
        return mark_safe("{0}").format(local_tz.normalize(local_dt).strftime('%b %d, %Y, %I:%M %p'))

You don't have access to the user there. 您无权访问那里的用户。 But you don't need it; 但是你不需要它; you should be activating the timezone in middleware, as described in the docs . 您应该按照docs说明激活中间件中的时区。 Something like: 就像是:

class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.user.is_authenticated and request.user.timezone
            tzname = request.user.timezone
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()

Add this to your middleware settings. 将此添加到您的中间件设置。 Now in your admin class you can do: 现在,在您的管理类中,您可以执行以下操作:

from django.utils.timezone import localtime

def time_clicked(self, instance):
    return localtime(instance.time_clicked)

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

相关问题 从admin.py中的配置文件访问用户数据 - Access to user data from profile in admin.py 如何访问由 admin.py 中的 OnetoOneField 引用的另一个 model 扩展的“用户”model 的属性 - How to access attributes of the 'User' model extended by another model referenced by a OnetoOneField in admin.py 检查Django admin.py中的当前消息 - Examine current messages in Django admin.py Django-登录的用户未填充在admin.py中 - Django - Logged in User Not Populating in admin.py 修改admin.py,使其仅提供模型的当前登录用户.ForeignKey(User) - Modify admin.py so that it's only offering the current logged-in user for the models.ForeignKey(User) Django Admin:如何访问 admin.py 中的请求对象,以获取 list_display 方法? - Django Admin: How to access the request object in admin.py, for list_display methods? Django:从admin.py访问用户信息以获取没有请求对象的方法? - Django: access to user info from admin.py for methods with no request object? 如何检查用户是否在默认的 django 组中? 在管理面板 (admin.py) - how to check if a user is in a default django group? in the admin panel (admin.py) 自定义admin.py - Customize admin.py 如何在dajango的自定义用户模型中修复admin.py中不可调用的属性错误? - how to fix not a callable attribute error in admin.py in custom user model in dajango?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM