【问题标题】:Django user injection in model properties模型属性中的 Django 用户注入
【发布时间】:2012-07-20 13:27:45
【问题描述】:

我在 Django 中有这个模型:

News
Comments
Reactions

关系是:

a News has various Comments
a Comment has various Reactions

问题在于用户(在请求/会话中):用户可能订阅了反应或评论;他可能已登录或未登录。 (这是一个foo的例子,没有多大意义)

我不能在模板中做:

{% for reaction in this_news.comments.reactions %}
 {{ reaction.name }}
 {% if reaction.user_subscribed %} #reaction.user_subscribed(request.user)...
 You have subscribed this reaction!
 {% endif %}
{% endfor %}

问题是:

  • 我不能用参数调用模板中的方法(见上面的注释)
  • 模型无权访问请求

现在我在News 模型中调用init_user 方法,传递请求。然后我在CommentReaction 模型中使用相同的方法,我必须设置user_subscribed 属性循环每个模型的子节点。

难道没有更聪明的方法吗?

编辑:感谢 Ignacio 关于使用自定义标签的提示,我正在尝试使用通用模式来传递用户(避免使用闭包,因为我不知道如何使用它们自动取款机):

def inject_user(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, method_injected, user = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires exactly three arguments" % token.contents.split()[0])
    return InjectUserNode(method_injected, user)

class InjectUserNode(template.Node):
    def __init__(self, method_injected, user):
        self.method_injected = template.Variable(method_injected)
        self.user = template.Variable(user)

    def render(self, context):
        try:
            method_injected = self.method_injected.resolve(context)
            user = self.user.resolve(context)
            return method_injected(user)
        except template.VariableDoesNotExist:
            return ''

当我使用它{% inject_user object.method_that_receives_a_user request.user %} 时,我在method_injected(user) 中遇到了这个错误'str' object is not callable;我该如何解决?

【问题讨论】:

    标签: django request models django-custom-tags


    【解决方案1】:

    我用一种不太优雅的方式解决了它,但它对我有用。

    我在我的 User 定义的类中创建了一种单例,并在我需要的每个视图中设置了一个属性。

    属性是User.current

    然后,在模型内部,我需要让当前用户查看User.current

    【讨论】:

      【解决方案2】:

      custom template tags 获取用户并设置上下文变量以指示标准的存在或不存在。

      【讨论】:

      • 它不仅仅涉及 user_subscribed 属性,还有很多由用户驱动的行为..有没有通用的方法来做到这一点?使用自定义标签,我可以在模板中采用模型方法并将其传递给用户?
      • 你能解释一下或告诉我怎么做吗?您最后一句话的文档不清楚(生成标签的闭包)
      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2017-07-21
      • 2012-12-15
      • 2023-03-22
      • 2014-03-30
      相关资源
      最近更新 更多