Django Forms показывает дополнительные категории для пользователей, входящих в группу

Я хотел бы показать эти категории ниже дополнительно пользователям, у которых есть категория blogger.

Текущий вопрос...

  1. Для пользователя блоггера он показывает только категории блоггера, хотя должен показывать все
  2. Для обычного пользователя он показывает категории блоггера, когда должен показывать только оригинальные 3

forms.py

class PostCreateForm(ModelForm):
    
    class Meta:
        model = Post
        fields = [
            "title",
            "category",
            "associated_portfolios",
            "body",

        ]
        exclude = ('allow_comments',)
        

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        blogger = User.objects.filter(groups__name='blogger').exists()
        print("Current User:", user)
        print("Blogger User:",  blogger)

        super(PostCreateForm, self).__init__(*args, **kwargs)
        self.fields['category'].choices = (
                ("Watchlist", "Watchlist"),
                ("Lesson/Review", "Lesson/Review"),
                ("General", "General"),
                )
        if User.objects.filter(groups__name='blogger').exists():
            self.fields['category'].choices = (
                ("Analysis", "Analysis"),
                ("Milestone", "Milestone"),
                ("Features", "Features"),
                ("Tutorials", "Tutorials"),
                ("Careers", "Careers"),
                ("Community", "Community"),
            )

проверить, что пользователь находится в группе и показать категории для блоггера

def __init__(self, *args, **kwargs):
    user = kwargs.pop('user', None)

    super(PostCreateForm, self).__init__(*args, **kwargs)

    if user and user.groups.filter(name = 'blogger').exists():
        # show all categories if user is in blogger group
        self.fields['category'].choices = (
            ("Analysis", "Analysis"),
            ("Milestone", "Milestone"),
            ("Features", "Features"),
            ("Tutorials", "Tutorials"),
            ("Careers", "Careers"),
            ("Community", "Community"),
        )
    else:
        # show basic categories if user is not in blogger group.

        self.fields['category'].choices = (
            ("Watchlist", "Watchlist"),
            ("Lesson/Review", "Lesson/Review"),
            ("General", "General"),
        )

Если вы хотите проверить, состоит ли пользователь в группе blogger и на основании этого показать ему различные категории, вы должны сделать это следующим образом:

class PostCreateForm(ModelForm):
    
    class Meta:
        model = Post
        fields = [
            "title",
            "category",
            "associated_portfolios",
            "body",

        ]
        exclude = ('allow_comments',)
        

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        # blogger = User.objects.filter(groups__name='blogger').exists()
        # print("Current User:", user)
        # print("Blogger User:",  blogger)

        super(PostCreateForm, self).__init__(*args, **kwargs)
        
        if User.objects.filter(groups__name='blogger', id=user.id).exists():
            self.fields['category'].choices = (
                ("Analysis", "Analysis"),
                ("Milestone", "Milestone"),
                ("Features", "Features"),
                ("Tutorials", "Tutorials"),
                ("Careers", "Careers"),
                ("Community", "Community"),
            )
        else:
            self.fields['category'].choices = (
                ("Watchlist", "Watchlist"),
                ("Lesson/Review", "Lesson/Review"),
                ("General", "General"),
                )

Нужно проверить, есть ли у пользователя, переданного форме в kwargs, группа blogger. Даже лучше, чем:

User.objects.filter(groups__name='blogger', id=user.id).exists()

используется

user.groups.filter(name='blogger').exists()

непосредственно на экземпляре User

вы можете попробовать следующее def init(self, *args, **kwargs): user = kwargs.pop('user', None)

super(PostCreateForm, self).__init__(*args, **kwargs)

if user and user.groups.filter(name = 'blogger').exists():
    # show all categories if user is in blogger group
    self.fields['category'].choices = (
        ("Analysis", "Analysis"),
        ("Milestone", "Milestone"),
        ("Features", "Features"),
        ("Tutorials", "Tutorials"),
        ("Careers", "Careers"),
        ("Community", "Community"),

        ("Watchlist", "Watchlist"),
        ("Lesson/Review", "Lesson/Review"),
        ("General", "General"),
    )
else:
    # show basic categories if user is not in blogger group.

    self.fields['category'].choices = (
        ("Watchlist", "Watchlist"),
        ("Lesson/Review", "Lesson/Review"),
        ("General", "General"),
    )
Вернуться на верх