afi
afi

Reputation: 603

how to exclude choices field values in django models?

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'
        ]

Upvotes: 2

Views: 1456

Answers (1)

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

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]

Upvotes: 2

Related Questions