Hi Dick,

Consider declaring model field by:
https://docs.djangoproject.com/en/3.0/ref/models/fields/#field-choices-named-groups

and template settings




On Thu, Jan 30, 2020, 02:13 Bernhard Dick <bernh...@bdick.de> wrote:

> 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
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/d68305ec-b5cf-4ffe-b4a8-71bed3e690ec%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/d68305ec-b5cf-4ffe-b4a8-71bed3e690ec%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAP5HUWpG2VO7zh9M2O4wTFY32FJ1JFvOakHFLZ%2B7cpNuikqa%3Dg%40mail.gmail.com.

Reply via email to