目前,因为我想访问user所有模板中的信息,所以我总是context_instance = RequestContext( request )在我的所有视图中使用.我也喜欢RequestContext因为它会自动处理csrf.
现在我通常只是将我的所有字典值放在里面RequestContext这样渲染
request_context = RequestContext( request, {
'order' : order,
'order_comments' : order_comments,
'comment_form' : comment_form,
} )
return render_to_response( 'doors/orders/detail.html', context_instance = request_context )
Run Code Online (Sandbox Code Playgroud)
这有什么不同呢?
context = {
'order' : order,
'order_comments' : order_comments,
'comment_form' : comment_form,
}
return render_to_response( 'doors/orders/detail.html', context, context_instance = RequestContext( request ) )
Run Code Online (Sandbox Code Playgroud)
如果程序方面没有真正的差异,那么这是最佳实践还是首选方法?
例如,我有一行这样的代码
if checked:
checked_string = "check"
else:
checked_string = "uncheck"
print "You can {} that step!".format(checked_string)
Run Code Online (Sandbox Code Playgroud)
这有什么捷径吗?我只是好奇而已.
在您可视地选择一个文本块并键入后:,Vim会'<,'>为您写入.
但我很好奇'<,'>它的真正含义以及它是否可以编辑.

我想can_view在我的Django应用程序中为每个模型添加一个Meta权限.
我想把它添加到每个班级 models.py
class Meta:
permissions = [ ( "can_view", "Can view {something}".format( something = self.verbose_name ) ]
Run Code Online (Sandbox Code Playgroud)
我甚至不确定self.verbose_name在这种情况下是否会像这样工作....
这可能吗?
奖金问题:一旦我在模型中添加了权限,Meta那么我可以has_perm正确地调用它吗?喜欢
if request.user.has_perm( 'polls.can_view' ) :
# Show a list of polls.
else :
# Say "Insufficient permissions" or something.
Run Code Online (Sandbox Code Playgroud) 假设我有
x = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
Run Code Online (Sandbox Code Playgroud)
我怎么去
x = ((1, 2), (4, 5), (7, 8))
Run Code Online (Sandbox Code Playgroud)
?
我想出的唯一方法是使用列表推导然后转换回元组:
x = tuple([n[1:len(n)] for n in x])
Run Code Online (Sandbox Code Playgroud)
但我觉得这是一种丑陋的做法......
在每个页面(base.html)中,我想检查request.user我的班级是否有管理员角色UserTypes并显示管理员链接.目前我这样做:
{% if user.profile.user_types.all %}
{% for user_type in user.profile.user_types.all %}
{% if user_type.name == "ad" %}
<li>
<a href="{% url admin:index %}" class="round button dark ic-settings image-left">Admin</a>
</li>
{% endif %}
{% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
user.profile只是从Django User到我的UserProfile.
但这似乎有点冗长和笨重.有更简单的方法吗?也许我应该编写自己的自定义上下文处理器并传递一个类似的变量is_admin,但我从来没有写过自定义上下文处理器...
标题可能令人困惑,但我不知道如何解释它.这是一个例子.
做这样的事情会更好吗?
class UserType( models.Model ) :
def user_count( self ) :
return self.userprofile_set.count()
Run Code Online (Sandbox Code Playgroud)
或者像这样?
class UserType( models.Model ) :
def user_count( self ) :
# Does "user_types = self" work? I'm not sure.
return UserProfile.filter( user_types = self.pk ).count()
Run Code Online (Sandbox Code Playgroud)
哪里
class UserProfile( models.Model ) :
user_types = models.ManyToManyField( UserType )
Run Code Online (Sandbox Code Playgroud)
UserType.user_count()只返回UserProfile具有特定人物的人数UserType.
对不起,如果这是一个愚蠢,微不足道的问题,但我很好奇.也许一些Django专家可以深入研究实际的SQL性能或东西:-).