繁体   English   中英

模型自函数中的Django request.user

[英]Django request.user in model self function

我想在我的模型 self 函数中获取当前登录的用户。 我试过这个。

class My_model(models.Model):
    user = models.OneToOneField(User)
    image = models.ImageField(upload_to='uploads/',default='uploads/no-img.jpg')
    #other fields
    def show_photo(self,request):
        show_photo = False
        if Photo_request.objects.filter(who=request.user,whose=self.user).exists():
            my_request = Photo_request.objects.get(who=request.user,whose=self.user)
            request_accepted = my_request.accepted            
            if request_accepted:
                show_photo = True                  
        return show_photo
    show_photo = property(show_photo)

在我的模板中

{% for profile in profiles %}  
    {% if profile.show_photo %}  
        <img src="{{MEDIA_URL}}{{ profile.image }}" alt="image" />
    {% endif %}
{% endfor %}

但是这个功能不起作用。 我试过没有请求参数和自定义 id,那是有效的。 我的代码有问题吗?

编写自定义标签:

my_app/templatetags/my_app_tags.py

from django.template import Library

register = Library()

@register.assignment_tag(takes_context=True)
def show_photo(context):
    request = context['request']
    profile = context['profile']
    return profile.show_photo(request) # Instead of passing request I suggest to pass request.user here

通过加载 template_tags 在模板中使用它:

{% load my_app_tags %}

{% for profile in profiles %}  
    {% show_photo as show %}
    {% if show %}  
        <img src="{{MEDIA_URL}}{{ profile.image }}" alt="image" />
    {% endif %}
{% endfor %}

我在threading包中使用了current_thread函数。

  1. utils/request_utiles.py文件中添加一个新的中间件,如下所示:

    utils/request_utiles.py

     from threading import current_thread from django.utils.deprecation import MiddlewareMixin _requests = {} def get_current_request(): t = current_thread() if t not in _requests: return None return _requests[t] class RequestMiddleware(MiddlewareMixin): def process_request(self, request): _requests[current_thread()] = request
  2. settings.py文件中添加中间件

    设置.py

     MIDDLEWARE = [ ... 'utils.request_utils.RequestMiddleware', ]
  3. 在任何模型中使用get_current_request()函数。

    在您的代码中,您可以使用如下:

     from utils.request_utils import get_current_request class My_model(models.Model): user = models.OneToOneField(User) image = models.ImageField(upload_to='uploads/',default='uploads/no-img.jpg') ... def show_photo(self): request = get_current_request() # you can get current request in here. show_photo = False if Photo_request.objects.filter(who=request.user,whose=self.user).exists(): my_request = Photo_request.objects.get(who=request.user, whose=self.user) request_accepted = my_request.accepted if request_accepted: show_photo = True return show_photo show_photo = property(show_photo)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM