Thursday, April 3, 2008

DJango comments.....

OK...

Well of late I have starting on Django to develop a website .
Everything went well till we came to a point where in we got to use the comments module and tell you its such a pain in the ass to find a good tutorial which will explain how to use Django comments.

After struggling for a bit I could learn how to use it though.
As a developer I would like to learn by seeing some realtime examples and unfortunately there are not many good sites explaining the usage of Comments module of Django.
So I decided to write one on my blog for the benefit of those who want to learn Django Comments.

In this blog I will be explaining how to use the Free comments module of Django.
Ofcourse some or most if it is from the official djangosite www.djangoProject.com

I will be explaining the use of ratings in the coming blogs.I assume you have got the basic knowledge on Djando to build the app, run the server and syncdb.

Ok lets start building the movies app with comments.

In this exapmple we will be developing a movie application where in we will be displaying all the theatres the movie is played . and when the user clicks on the individual movie link the movie detail page is displayed where the user is allowed to post comment

the application is named movies.
The following are my models.py, views.py and forms.py

models.py

from django.db import models

# Create your models here.
class Movie(models.Model):
name = models.CharField(maxlength=60)

def __str__(self):
return self.name

class Theatre(models.Model):
movie_id = models.ForeignKey(Movie)
name = models.CharField(maxlength=60)
timings = models.CharField(maxlength=60)

def __str__(self):
return self.name


____________________________________________
views.py

# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from forms import MovieForm
from movies.models import Movie
from movies.models import Theatre
from django.contrib.comments.views.comments import post_free_comment
import datetime

def movie(request):
current_date = datetime.datetime.now()
return render_to_response('index.html', locals())

def movieinfo(request):
#current_date = datetime.datetime.now()
if request.method == 'POST':
mname = request.POST['mname']
m,created = Movie.objects.get_or_create(name = mname)
t,create = Theatre.objects.get_or_create(movie_id = m,name = request.POST['tname'],timings = request.POST['timings'])
return HttpResponseRedirect('http://127.0.0.1:8000/moviedetail')
else:
form = MovieForm()
return render_to_response('movieinfo.html', locals())

def moviedetail(request):
movie_list = Movie.objects.all()
mov_dict={}
tlist = []
for mov in movie_list:
theatre_list = Theatre.objects.filter(movie_id = mov)
mov_dict[mov.name] = theatre_list
movname_list = mov_dict.keys()
return render_to_response('moviedetail.html', locals())

def movienext(request):
moviename = request.GET['movie']
m = Movie.objects.get(name=moviename)
return render_to_response('movienext.html', locals())

def my_post_free_comment(request):
if request.has_key('url') and not request.has_key('preview'):
response = post_free_comment(request)

# Check there's a url to redirect to, and that post_free_comment worked
if len(request['url'].strip()) > 0 and isinstance(response, HttpResponseRedirect):
return HttpResponseRedirect(request['url'])

# Fall back on the default post_free_comment response
return response

return post_free_comment(request)
______________________________________________

forms.py

from django import newforms as forms
from models import Movie
from models import Theatre
from django.newforms import form_for_model

TOPIC_CHOICES = (
('general', 'General enquiry'),
('bug', 'Bug report'),
('suggestion', 'Suggestion'),
)

class MovieForm(forms.Form):
mname = forms.CharField()
tname = forms.CharField()
timings = forms.CharField()
________________________________________________
in the urls.py file

add the entries

from movies.views import my_post_free_comment
from django.contrib.comments.models import FreeComment

and in the pages section of urls.py add

(r'^comments/postfree/', my_post_free_comment),
(r'^comments/', include('django.contrib.comments.urls.comments')),

Note:The urlsfor the normal pages are not added.It is required to add the pages by the users as per their requirement.
_______________________________________________________________
in the settings.py file add the entry under the installed apps module.

'movies',
'django.contrib.comments',

This will add the comments app and the movies app to your project.

______________________________________________________________

The last item is the templates module

In order to run the comments application

you need to have the following html files in the comments directory of your templates file.

freepreview.html
posted.html

These files are available from the official djangotutorial located at
http://code.djangoproject.com/wiki/UsingFreeComment.
_____________________________________________________________________

to set up the app to run the movies application you also need the following files under your template directory

index.html
moviedetail.html
movieinfo.html
movienext.html


I am not able to display the above html pages in the blog .. but one needs to embed the following code in the page where comments neds to be displayed

{% load comments %}
get the code from example of comments from the first Example of Django official tutorial at http://code.djangoproject.com/wiki/UsingFreeComment and paste it here
--------------------------------------
once you have the above things setup , you are ready to run and test the application..

first run
"python manage.py syncdb" to set up db
then run the server using the

"python manage.py runserver"
once the server is up without errors , in the browser enter the address

127.0.0.1:8000/movie/

form there you can proceed.If you have any doubts please post them as comments and I will try to answer them asap.

Also, please dunt foget to read the basics from the official django site http://code.djangoproject.com/wiki/UsingFreeComment.

PS: if required I will send my entire application when requested in comments.

Happy reading,
-Sri.