I am trying to add preferences to user accounts. Each preference is true/false value and it needs to stay this way.
Since each account might have multiple preferences I would like to know how to loop through them in my templates and have those preferences easily available throughout the app.
Ex. I want to display user’s name and all of the colors they like.
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 %}
output
user: userName
colors: white, black
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
UserColorsmodel. It’s easier in the View code, as you need getattr:Then in the template:
Original answer:
You could structure it like this:
Then point one at each user for each color that you want to specify:
Use it like this: