Oluwaseun Peter
Oluwaseun Peter

Reputation: 33

How To Redirect To Same Page After Post a Comment Using Django

as stated in my thread heading, i been on this issue for quite few days. Im trying to redirect to same page i was after making comment of a page irrespective of the paginated comments. Tried altering the get_success_url method but its not working.

class ReadThread(MultipleObjectMixin, CreateView):
    query_pk_and_slug = True
    form_class = PostForm
    paginate_by = 3
    template_name = 'read_thread.html'
    context_object_name = 'posts'

    def get(self, request, *args, **kwargs):
        self.thread = self.get_object()
        self.object_list = self.get_queryset()
        return super().get(request, *args, **kwargs)

    def get_object(self):
        thread = super().get_object(
            Thread.objects.filter(category__slug__iexact=self.kwargs['category_slug'])
        )
        return thread

    def post(self, request, *args, **kwargs):
        self.thread = self.get_object()
        return super().post(request, *args, **kwargs)

    def get_queryset(self):
        return self.thread.posts.all()

    def get_context_data(self, **kwargs):
        context = super(ReadThread, self).get_context_data(**kwargs)
        context['thread'] = self.thread
        return context

    def form_valid(self, form):
        form.instance.thread = self.thread
        form.instance.user = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        return redirect(self.request.build_absolute_uri(self.thread))

Upvotes: 1

Views: 215

Answers (1)

Charnel
Charnel

Reputation: 4432

Are you are looking for redirect to the HTTP_REFERRER

redirect(request.META.get('HTTP_REFERER'))

that you can add as a response of successful POST request?

Upvotes: 1

Related Questions