Login required when submitting a form inside a DetailView

Is there a way to add login_required when submitting a form inside a DetailView?

I know LoginRequiredMixin, but I want anonymous user to view the details of the post, but require them to login when adding a comment. Is there a way to do that? Thanks!

views.py

class PostView(DetailView, FormMixin):
    model = Post
    form_class= CommentForm

    def get_success_url(self):
        return reverse_lazy('post-detail', kwargs={'pk': self.object.pk})

    def get_post_data(self, *args, **kwargs):
        post_menu = Post.object.all()
        context = super(PostDetailView, self).get_context_data
        context["form"] = CommentForm()
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        comment_form = self.get_form()
        if comment_form.is_valid():
            return self.form_valid(comment_form)
        else:
            return self.form_invalid(comment_form)

    def form_valid(self, comment_form):
        comment_form.instance.post = self.object
        comment_form.instance.user = self.request.user
        comment_form.save()
        return super().form_valid(comment_form)


Read more here: https://stackoverflow.com/questions/65724473/login-required-when-submitting-a-form-inside-a-detailview

Content Attribution

This content was originally published by Senpai at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: