Summary: Writing your first Django app
October 14, 2008
After started reading Writing your first Django app for the second time, I decided that I should really take a note. It should be very helpful for reminding a lot of details covered in this tutorial
It is intended to be used by myself. So it’ll be quite hard to read.
Create project
- go to .../django/bin
- django-admin.py startproject mysite
- You will get 4 files
mysite/ __init__.py manage.py settings.py urls.py
Starting Server & Setting
- manage.py runserver
- DATABASE_ENGINE = ‘sqlite3′
- DATABASE_NAME = ‘C:/xxx/yyy.db’ (Note: use frontslashes)
- DATABASE_USER = ” (not used for SQLite).
- DATABASE_PASSWORD = ” (not used for SQLite).
- DATABASE_HOST = ” (not used for SQLite).
- INSTALLED_APPS << add your applications
manage.py commands
- manage.py syncdb
- manage.py startapp [appname] (don’t forget to update INSTALLED_APP
- manage.py shell
- manage.py validate — Checks for any errors in the construction of your models.
- manage.py sqlcustom [appname]– Outputs any custom SQL statements (such as table modifications or constraints) that are defined for the application.
- manage.py sqlclear [appname] — Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any).
- manage.py sqlindexes< — Outputs the CREATE INDEX statements for this app.
- manage.py sqlall [appname]– A combination of all the SQL from the sql, sqlcustom, and sqlindexes commands.
Model and interactions
-
__str__ class Poll(models.Model): # ... def __unicode__(self): return self.question
-
Poll.objects.all()
-
Poll.objects.filter(id=1)
-
Poll.objects.filter(question__startswith='What')
-
Poll.objects.get(pub_date__year=2007)
-
Poll.objects.get(id=2)
-
p = Poll.objects.get(pk=1)
-
p.was_published_today()
-
p.choice_set.create(choice='Not much', votes=0)
-
c = p.choice_set.create(choice='Just hacking again', votes=0
-
p.choice_set.all()
-
p.choice_set.count()
-
Choice.objects.filter(poll__pub_date__year=2007)
-
c = p.choice_set.filter(choice__startswith='Just hacking')
-
c.delete()
Activating and Customizing admin application
- Add "django.contrib.admin" to your INSTALLED_APPS setting.
- manage.py syncdb
- edit urls.py by adding two lines below + uncomment the last line
from django.contrib import admin admin.autodiscover()
- create admin.py in your application, put these lines
from mysite.polls.models import Poll from django.contrib import admin admin.site.register(Poll)
- customize the form by changing admin.py
class PollAdmin(admin.ModelAdmin): fields = ['pub_date', 'question'] admin.site.register(Poll, PollAdmin)
- to split fieldsets
class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date']}), ] admin.site.register(Poll, PollAdmin)
- Add choice in Poll page (can use TabularInline instead of StackedInline)
class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class PollAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline]
- Show details in list page
class PollAdmin(admin.ModelAdmin): # ... list_display = ('question', 'pub_date', 'was_published_today')
Add these lines in model
def was_published_today(self): return self.pub_date.date() == datetime.date.today() was_published_today.short_description = 'Published today?'
-
Searching search_fields = ['question']
- Drill down by date
date_hierarchy = 'pub_date
- Customizing template directory in settings.py file
TEMPLATE_DIRS = ( "/home/my_username/mytemplates", # Change this to your own directory. )
Creating “Views” and URLs
- Change urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^polls/$', 'mysite.polls.views.index'), (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'), (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'), (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'), )
- Add called functions such as
def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id)
- To use template
from django.template import Context, loader from mysite.polls.models import Poll from django.http import HttpResponse def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] t = loader.get_template('polls/index.html') c = Context({ 'latest_poll_list': latest_poll_list, }) return HttpResponse(t.render(c)) or use shortcut def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
- For 404 pages
from django.shortcuts import render_to_response, get_object_or_404 # ... def detail(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) return render_to_response('polls/detail.html', {'poll': p})
- Same for 500 (Error)
- This is how template look like
{% if latest_poll_list %} <ul> {% for poll in latest_poll_list %} <li>{{ poll.question }}</li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
———–