1👍
✅
Update:
In my original answer, I tried restructuring the data and keeping the values as boolean. It looks like we need to stay closer to the original structure.
You can loop through the fields on your UserColors
model. It’s easier in the View code, as you need 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
Then in the template:
{% for k,v in usercolors.items() %}
{% if v %}
{{ k }}
{% endif %}
{% endfor %}
Original answer:
You could structure it like this:
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)
Then point one at each user for each color that you want to specify:
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)
Use it like this:
{% for color in user.color_set.all() %}
{{ color.name }}: {{ color.value }}
{% endfor %}
Source:stackexchange.com