我正在尝试向用户帐户添加偏好设置。每个偏好都是真/假值,它需要保持这种状态。
由于每个帐户可能有多个偏好设置,因此我想知道如何在我的模板中循环显示这些偏好设置,并在整个应用程序中轻松提供这些偏好设置。
实施例。我想显示用户名和他们喜欢的所有颜色。
models.py
class UserColors(models.Model):
white = models.BooleanField(_("White"))
black = models.BooleanField(_("Black"))
class Account(models.Model):
user = models.OneToOneField(User, unique=True, verbose_name='user', related_name='account')
colors = models.ForeignKey('UserColors', null=True)
views.py
class UserView(DetailView):
context_object_name = 'account'
template_name = 'detail.html'
def get_object(self, queryset=None):
return self.request.user
template.html
user: {% account.user.username %} <br>
colors:
# the following would be ideal instead of doing multiple ifs in search for true/false values
{% for color in account.colors %}
color.name
{% endif %}
输出
user: userName
colors: white, black
答案 0 :(得分:1)
<强>更新强>
在我的原始答案中,我尝试重构数据并将值保持为布尔值。看起来我们需要更接近原始结构。
您可以遍历UserColors
模型上的字段。在View代码中更容易,因为你需要getattr:
def get_context_data(self, request, *args, **kwargs):
data = super(UserView, self).get_context_data(request, *args, **kwargs)
acct = data['account'] # Guessing this is here based on your posted template code
colors = {}
for field in acct.colors._meta.fields:
colors[field.name] = getattr(acct.colors, field.name, False)
data['usercolors'] = colors
return data
然后在模板中:
{% for k,v in usercolors.items() %}
{% if v %}
{{ k }}
{% endif %}
{% endfor %}
原始回答:
你可以像这样构建它:
class UserColor(models.Model):
colors = {
"WHITE": "WHT",
"BLACK": "BLK",
}
color_choices = (
(colors['WHITE'], "White"),
(colors['BLACK'], "Black"),
)
name = models.CharField(_("Color Name"), max_length=3, choices=color_choices)
value = models.BooleanField(_("Whether they like it"))
user = models.ForeignKey(User)
然后在每个用户为您要指定的每种颜色指定一个:
user = User.objects.get(name="me")
white = UserColor.objects.create(
color=UserColor.colors['WHITE'], value=False, user=user)
black = UserColor.objects.create(
color=UserColor.colors['BLACK'], value=True, user=user)
像这样使用:
{% for color in user.color_set.all() %}
{{ color.name }}: {{ color.value }}
{% endfor %}