0

我正在尝试向用户帐户添加首选项。每个偏好都是真/假值,它需要保持这种方式。

由于每个帐户可能有多个首选项,我想知道如何在我的模板中循环它们,并在整个应用程序中轻松使用这些首选项。

前任。我想显示用户名和他们喜欢的所有颜色。

模型.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)

视图.py

class UserView(DetailView):
    context_object_name = 'account'
    template_name = 'detail.html'

    def get_object(self, queryset=None):
        return self.request.user

模板.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
4

1 回答 1

1

更新:

在我最初的答案中,我尝试重组数据并将值保持为布尔值。看起来我们需要更接近原始结构。

您可以遍历UserColors模型上的字段。查看代码更容易,因为您需要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 %}
于 2012-10-11T16:49:43.833 回答