2

I know this should be straight-forward, but for some reasons I'm not getting the results I want.

This instruction: {{user.profile.role.all}} in my Django template outputs this:

<QuerySet [<Role: Creator>, <Role: Performer>, <Role: Venue>]>

I'd like to check if a role is within this queryset; so, for instance, if I want to check if a role 'venue' is present, according to what the documentation tells me, I should do:

{% if "Venue" in user.profile.role.all %}

Right? The above-mentioned if, though, returns false. Why is that?

HBMCS
  • 686
  • 5
  • 25

1 Answers1

1

The reason this does not work is because a string is something different than a Role with as name the same string.

You can pass a set of role names to the template, for example with:

context['role'] = Role.objects.filter(
    profile__user=self.request.user
).values_list('type', flat=True)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Yes, that does it! Thanks. – HBMCS Jun 01 '20 at 19:08
  • Wait, but why does `{% if "Venue" or "Promoter" in roleList %}` return true then, if either one or the other are in the list? Can't I check for more than one string at a time? – HBMCS Jun 01 '20 at 19:16
  • @HBMCS: that is because the *truthiness* of `'Venue'` is true since it is a non-empty string, you write `if ('Venue') or ('Promotor' in roleList %}` after all, you should write it as `{% if 'Venue' in roleList or 'Promotor' in roleList %}`. – Willem Van Onsem Jun 01 '20 at 19:18
  • This works: (i.e. returns false) `{% if "Venue" in roleList or "Promoter" in roleList %}` although it doesn't seem very DRY to me. – HBMCS Jun 01 '20 at 19:18
  • Ah, OK, so if I'm checking for ten roles I need to repeat in roleList each time. OK, I'll do that. – HBMCS Jun 01 '20 at 19:19
  • @HBMCS: Django has a permissions framework that is probaby better: https://stackoverflow.com/questions/9469590/check-permission-inside-a-template-in-django it makes use of `Groups`, so perhaps you can use the permissions framework over writing your own. – Willem Van Onsem Jun 01 '20 at 19:20
  • This is checking the properties of Profiles for displaying it to anonymous users, otherwise it'd have been too easy :) . Like, 'do not display the instruments played tab in the profile page of a composer' sort of thing. – HBMCS Jun 01 '20 at 19:40
  • ...or maybe you mean that 'Groups' should be my 'Roles'? – HBMCS Jun 01 '20 at 19:41
  • 1
    @HBMCS: well groups are not the permissions, but a group can have zero, one or more permissions. So yes, you can for example use groups over defining a `Role` model I think. Django's admin pages also normally have pages to edit the permissions. Furthemore there are decorators for permission checks. – Willem Van Onsem Jun 01 '20 at 19:43