簡體   English   中英

如何在 Django 模型中排除選擇字段值?

[英]how to exclude choices field values in django models?

表單取決於登錄用戶的用戶組,如果登錄用戶不屬於某個組,則應刪除一些 story_status 值。我有一個制作人組,如果登錄用戶不屬於表單制作人組,那么我想刪除從story_status footage ready選擇字段值footage ready 我的代碼不排除這些值

模型.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)

輸出.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'
        ]

嘗試使用 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