Hi,
I'm having trouble with the template-side when I'm converting my code to make use of the in version 3 introduced IntegerChoices-Class and I'd like to get some tips on doing it right.
My version 2 Code looks like this:
class StateModel(models.Model):
STATE_DRAFT = 0
STATE_PUBLISHED = 1
STATE_CHOICES = [
(STATE_DRAFT, 'draft'),
(STATE_PUBLISHED, 'published'),
]
state = models.PositiveIntegerField(choices=STATE_CHOICES, default=STATE_DRAFT)
In the template for a ListView I want to show an edit button next to all instances that are not yet published or where the current user has administrative permissions. Currently that can by done via
{% if instance.state == instance.STATE_DRAFT or perms.appname.manage_entries %} edit {% endif %}.
Now with the use of the IntegerChoices my model looks cleaner:
class StateModel(models.Model):
class State(models.IntegerChoices):
DRAFT = 0, 'draft'
PUBLISHED = 1, 'published'
state = models.PositiveIntegerField(choices=State, default=State.DRAFT)
But then I'm not able to access the constant values for the states from my templates. Is there a preffered way to circumvent this? One idea would to simply add some methods like:
def isDraft(self):
return self.state == State.DRAFT
but that seems a bit boilerplate to me. I think the ideal solution would be to have something like a method named isAllowedToEdit in the model, which runs all my checks (and could be used elsewhere in the python-side of the project). But here I have the problem that I can't pass the permission information when calling from the template.
Regards
Bernhard