Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Redirect to current article after comment post

Tags:

django

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)?

like image 545
Oleg Tarasenko Avatar asked Jan 23 '10 13:01

Oleg Tarasenko


1 Answers

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.
like image 96
smentek Avatar answered Sep 28 '22 09:09

smentek