TransWikia.com

how to exclude choices field values in django models?

Stack Overflow Asked by afi on December 18, 2020

form Depending from the user group of the logged in user, some story_status values should be remove if logged in user is not belong from certain group.i have a producer group, if logged in user is not belong form producer group then i want to remove the choices field value footage ready from the story_status. my code is not excluding the values

models.py

class Article(models.Model):
    STORY_STATUS = {
        ('story not done', 'story not done'),
        ('story finish', 'story finish'),
        ('Copy Editor Done', 'Copy Editor Done'),
        ('footage ready', 'footage ready')
    }

    title = models.CharField(max_length=255, help_text="Short title")
    story_status = models.CharField(choices=STORY_STATUS)

output.html

class ArticleForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(ArticleForm, self).__init__(*args, **kwargs)
        if not self.user.groups.filter(name__iexact='producer').exists():
            self.queryset = Article.objects.exclude(story_status='footage ready')

    class Meta:
        model = Article
        fields = [
            'title',
            'story_status'
        ]

One Answer

Try to overwrite choices using init method like

STORY_STATUS = [
    ('story not done', 'story not done'),
    ('story finish', 'story finish'),
    ('Copy Editor Done', 'Copy Editor Done'),
    ('footage ready', 'footage ready')
]

story_status_config = {
    'producer': ['footage ready'],
    'other_group': ['story finish']
}

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user', None)
    super(ArticleForm, self).__init__(*args, **kwargs)
    for group,exclude_vals in story_status_config:
        if not self.user.groups.filter(name__iexact=group).exists():
            self.fields['story_status'].choices = [x for x in STORY_STATUS if x[0] not in exclude_vals]

Correct answer by Pruthvi Barot on December 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP