6

I am trying to use comments application in my project.

I tried to use code ({% render_comment_form for event %}), shown in the documentation here: Django comments

And the question is how to make the form redirect to the same page, after the submission.


Also the big question is: Currently if we have any error found in the for, then we're redirected to preview template. Is that possible to avoid this behaviour and display errors over the same form (on the same page)?

Oleg Tarasenko
  • 9,324
  • 18
  • 73
  • 102

5 Answers5

5

I will show you how I resolved it in my blog, so you could do something similar. My comments are for Entry model in entries application.

First add new method for your Entry (like) object.

def get_absolute_url(self):
    return "/%i/%i/%i/entry/%i/%s/" % (self.date.year, self.date.month, self.date.day, self.id, self.slug)

It generates url for entry objects. URL example: /2009/12/12/entry/1/lorem-ipsum/

To urls.py add 1 line:

(r'^comments/posted/$', 'smenteks_blog.entries.views.comment_posted'),

So now you should have at least 2 lines for comments in your urls.py file.

(r'^comments/posted/$', 'smenteks_blog.entries.views.comment_posted'),
(r'^comments/', include('django.contrib.comments.urls')),

For entries (like) application in views.py file add function:

from django.contrib.comments import Comment #A
...
def comment_posted(request):
    if request.GET['c']:
        comment_id = request.GET['c'] #B
        comment = Comment.objects.get( pk=comment_id )
        entry = Entry.objects.get(id=comment.object_pk) #C
        if entry:
            return HttpResponseRedirect( entry.get_absolute_url() ) #D
    return HttpResponseRedirect( "/" )    
  • A) Import on top of file to have access for comment object,
  • B) Get comment_id form REQUEST,
  • C) Fetch entry object,
  • D) Use get_absolute_url method to make proper redirect.

Now:

  • Post button in comment form on entry site redirects user on the same (entry) site.
  • Post button on preview site redirects user on the proper (entry) site.
  • Preview button in comment form on entry site and on preview site redirects user on preview site
  • Thankyou page is not more in use (That page was quite annoying in my opinion).

Next thing good to do is to override preview.html template:

  • Go to django framework dir, under linux it could by /usr/share/pyshared/.
  • Get original preview.html template from DJANGO_DIR/contrib/comments/templates/comments/preview.html
  • Copy it to templates direcotry in your project PROJECT_DIR/templates/comments/entries_preview.html
  • From now on, it shoud override default template, You can change extends in this way: {% extends "your_pagelayout.html" %} to have your layout and all css files working.
smentek
  • 2,820
  • 1
  • 28
  • 32
2

Take a look at "Django-1.4/django/contrib/comments/templates/comments/" folder and you will see in the "form.html" file, there is the line

{% if next %}<div><input type="hidden" name="next" value="{{ next }}" /></div>{% endif %}

Therefore, in the Article-Detail view, you can include the "next" attribute in the context data, and then the comment framework will do the rest

class ArticleDetailView(DetailView):
    model = Article
    context_object_name = 'article'

    def get_context_data(self, **kwargs):
        context = super(ArticleDetailView, self).get_context_data(**kwargs)

        context['next'] = reverse('blogs.views.article_detail_view', 
            kwargs={'pk':self.kwargs['pk'], 'slug': self.kwargs['slug']})
        return context
Thai Tran
  • 9,815
  • 7
  • 43
  • 64
1

Simplify Django’s Free Comments Redirection

Tom
  • 22,301
  • 5
  • 63
  • 96
  • Good tip... Actually there is one more ugly redirect... To preview form (especially when there are some errors). Can I display errors over the same form (without opening new page) – Oleg Tarasenko Jan 23 '10 at 13:26
  • I always have the same issues with comments. It's a bit more work, but I usually wind up doing the whole thing via Ajax. I hijack the form's submit() action and do a post to the comment submit view. That way you can handle the errors without leaving the page, redirect to where ever you want or stay on the page and just put the new comment into the list dynamically. There's an app on bitbucket to help with this. Blog post about it at http://brandonkonkle.com/blog/2009/oct/24/dry-ajax-comments/. Here's another example: http://www.nomadjourney.com/2009/01/using-django-templates-with-jquery-ajax/ – Tom Jan 23 '10 at 14:04
  • Is it me or is this an inflexible solution? This solution only allows you to use django comments only in one case for your whole application. Let's say you create a photo gallery, in esence, you won't be able to use commenting on each photo unless you treat each photo as a blog post. – killerbarney Jan 31 '11 at 19:57
  • Why though? You could just extend the view to accept a content type either via the URL or POST. See https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/ – Tom Mar 14 '12 at 22:59
  • What part doesn't work? The answer's 3 years old and the link is 5 years old, so it's likely the comments app has changed a fair bit. Plus CSRF protection was added in 1.2, so it may be the form submissions are being blocked by the lack of a CSRF token. – Tom Jan 21 '13 at 16:40
1

Update: Now have the option to redirect as part of the comment form: see https://django-contrib-comments.readthedocs.io/en/latest/quickstart.html#redirecting-after-the-comment-post

Tom
  • 22,301
  • 5
  • 63
  • 96
PhoebeB
  • 8,434
  • 8
  • 57
  • 76
0

This is a really simple redirect to implement. It redirects you back to the page where the comment was made.

When a comment is posted, the url comments/posted/ calls the view comment_posted which then redirects back to the referer page.

Be sure to replace [app_name] with your application name.

views.py

from urlparse import urlsplit

def comment_posted( request ):
    referer = request.META.get('HTTP_REFERER', None)
    if referer is None:
        pass
    try:
        redirect_to = urlsplit(referer, 'http', False)[2]
    except IndexError:
       pass
    return HttpResponseRedirect(redirect_to)

urls.py

( r'^comments/posted/$', '[app_name].views.comment_posted' ),
Corey
  • 166
  • 3
  • 14