【发布时间】: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 方法,传递请求。然后我在Comment 和Reaction 模型中使用相同的方法,我必须设置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