Software » Django




remainder for setting up a django website

install first files:

django-admin startproject

the views:

  • add a file views.py and define functions
from django.http import HttpResponse

def my_page(request):
   return HttpResponse("a first page")
  • add a link between an url and the function:
file: urls.py

urlpatterns = patterns((r'^page/$',views.my_page),
)
  • arguments are defined in the url and transmit to function using braces:
urlpatterns = patterns((r'^page/(.*)/$',views.my_page),
)

running debug server

./manage.py runserver

the template:

  • add template files in a directory (/foo/)
example file: page.html
<html>
<body>
<h1>{{titre}}</h1>
{{message}}
</body>
</html>

see for details

  • add that directory to the variable TEMPLATE_DIRS in settings.py
  • in the view, use the template as follow:
from django.shortcuts import render_to_response

def my_page(request,arg):
   return render_to_response("page.html",{"titre":"My Page","message":arg})

Models: load objects from a database

  • edit settings.py and set db parameters
  • install app files ./manage.py startapp dbname
  • edit dbname/models.py
from django.db import models

class Person(models.Model):
   name=models.CharField()
   size=models.IntegerField()
   with=models.ForeignKey(Person)
   know=models.ManyToManyField(Person)
  • check model file: ./manage.py validate
  • create db: ./manage.py syncdb (see the sql: ./manage.py sqlall dbname
  • add entries into the db using python (./manage.py shell )
from myapp.dbname.models import Person

p = Person(name="toto",size=10)
p.save()

./manage.py commands

  • runserver: run the debug server
  • shell: open a python interpreter in the django environment
  • sqlall: check the validity of the model description
  • syncdb: create/update database according to the model classes