1

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

fpaekoaij
  • 193
  • 1
  • 2
  • 15
  • 1
    Have you seen this SO [post](https://stackoverflow.com/questions/4789021/in-django-how-do-i-check-if-a-user-is-in-a-certain-group) showing how to check if a user bbelongs to a certain group? – Chris Jan 19 '20 at 10:14
  • Yes, but as you can see I need to somehow access the story for getting the group_name and so that did not fulfill my query and also this is in the method form_valid. – fpaekoaij Jan 19 '20 at 10:26
  • 1
    I am not sure were your problem is. I tested your code and it gives me a 403 response (Forbidden) when a user does not belong to the group and a 404 response if the model does not exist. Isn't this your expected behaviour? – Chris Jan 19 '20 at 11:07
  • 1
    Except for the fact that in the view you posted your are defining a field which does not exist in your model (content). But I guess this is just a typo in your post – Chris Jan 19 '20 at 11:09

0 Answers0