Search code examples
pythondjangoformsviewmodel

Django Forms Show Extra Categories For Users Part Of Group


I'd like to show these categories below additionally with users who have the blogger category.

The current issue is..

  1. For a blogger user it's only showing blogger categories when it should be showing all
  2. For a normal user it's showing blogger categories when it should only be showing the original 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"),
            )

Solution

  • you can try the following 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"),
        )