【发布时间】:2016-06-14 10:20:43
【问题描述】:
我有一个profile 模型与User 模型具有一对一的关系,因此我可以访问模板罐中的两个模型到user 变量,如下所示:
template.html
{% if user.profile.phone == 1234567890 %}
Show something
{% endif %}
效果很好,条件给出了True 并显示了一些东西,但我也有Property 和User_Property 的模型,User_Property 模型具有Foreignkey 来自User 和Property 的ID .
models.py
class Property(models.Model):
name = models.CharField(max_length=50, unique=True)
class User_Property(models.Model):
us = models.ForeignKey(User, related_name='up_us')
prop = models.ForeignKey(Property, related_name='up_prop')
所以如果我尝试像这样访问User_Property 模型:
{% if user.user_property.prop == 1 %}
Show something
{% endif %}
我无法访问它,即使它是 True,我也没有尝试过 False。这是因为与Profile 模型的关系是用OneToOneField 建立的,而与User_Property 的关系是用ForeignKey 字段建立的,我需要将context 传递给User_Property 模型?
如果我在模板中使用JOIN SQL 语句,是否可以访问Property 模型?像这样:
{% if user.user_property.property.name == 'the name of the property' %}
Show something
{% endif %}
抱歉,帖子太长了,但我尝试添加所有需要的信息。
编辑:好的,如果有人需要类似的东西,这就是我为解决问题所做的。
创建一个context_processor.py 以返回一个User_Property 的实例并将其添加到我的settings.py 中,这样即使我没有在视图中将它作为上下文传递,我也可以在我的所有模板中访问该实例.
context_processors.py
from App_name.models import User_Property
from django.contrib.auth.models import User
def access_prop(request):
user = request.user.id #add the .id to no have problems with the AnonymousUser in my logg-in page
user_property = User_Property.objects.filter(us=user).values_list('prop', flat=True) #this stores the list of all the properties for the logg-in user
return {
'user_property': user_property,
}
settings.py
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += ('App_name.context_processors.access_prop',)
然后在模板中检查用户是否具有特定属性
template.html
{% if 'property name' in user_property %}
Show something
{% else %}
This is not for you
{% endif %}
要检查name 而不是id 的具体情况,只需在我的模型User_Property 的prop 字段中添加to_field='name',如下所示:prop = models.ForeignKey(Property, related_name='up_prop', to_field='name')。
【问题讨论】:
-
很难跟上。您是否有
OneToOneField关系?你将什么作为user传递给上下文? -
OneToOneField关系在User和Profile模型之间,user是来自当前登录用户docs.djangoproject.com/en/1.8/topics/auth/default/#users 的User模型的一个实例跨度> -
还有一条建议,最好不要将您的班级命名为
Property,它是保留名称(小写)。 -
@vishes_shell 别担心,这只是我在这个例子中使用的名字,而不是我在课堂上使用的真实名字。
标签: python html django django-models django-templates