简体   繁体   English

如何在 Django 模型中排除选择字段值?

[英]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 .表单取决于登录用户的用户组,如果登录用户不属于某个组,则应删除一些 story_status 值。我有一个制作人组,如果登录用户不属于表单制作人组,那么我想删除从story_status footage ready选择字段值footage ready my code is not excluding the values我的代码不排除这些值

models.py模型.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输出.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'
        ]

Try to overwrite choices using init method like尝试使用 init 方法覆盖选择,例如

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM