I'd like to show these categories below additionally with users who have the blogger category.
The current issue is..
- For a blogger user it's only showing blogger categories when it should be showing all
- 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"),
)
CodePudding user response:
check user is in the group and show categories for blogger
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"),
)
CodePudding user response:
If you want to check if user is in group blogger and base on that show him diffrent categories you should do it like that:
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"),
)
You need to check if user that is passed to form in kwargs have blogger group. Even better than:
User.objects.filter(groups__name='blogger', id=user.id).exists()
is use
user.groups.filter(name='blogger').exists()
directly on User instance