So this is what I have:
#models.py
class Story(models.Model):
title = models.CharField(max_length=150)
story = models.TextField()
page = models.ForeignKey(Page, on_delete=models.CASCADE)
#views.py
class StoryUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Story
fields = ['title', 'content']
def form_valid(self, form):
story = self.get_object()
if self.request.user in User.objects.filter(groups__name=story.page.name):
return super().form_valid(form)
else:
pass
def test_func(self):
story = self.get_object()
if self.request.user in User.objects.filter(groups__name=story.page.name):
return True
return False
#urls.py
path('edit_story/<int:pk>', StoryUpdateView.as_view(), name='update-story')
here I want to give access to this update view to a group of users. So my query should be like this: if the current user is in User.objects.filter(groups__name=story.page.name)
group, then he should have access to update a story.
Now I believe that my form_valid() and test_func() method is wrong. But I can't find a way to make it right. What should be the right logic for doing this?
Also, to get the story, what should I do? Do I do story = self.get_object()
as done here which possibly is not working or do I need to use the method get_object_or_404()
and how to do that?
Any help will be much appreciated