Summary: Writing your first Django app

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

  1. go to .../django/bin
  2. django-admin.py startproject mysite
  3. 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

  1. Add "django.contrib.admin" to your INSTALLED_APPS setting.
  2. manage.py syncdb
  3. edit urls.py by adding two lines below + uncomment the last line
    from django.contrib import admin
    admin.autodiscover()
  4. create admin.py in your application, put these lines
    from mysite.polls.models import Poll
    from django.contrib import admin
    
    admin.site.register(Poll)
  5. customize the form by changing admin.py
    class PollAdmin(admin.ModelAdmin):
        fields = ['pub_date', 'question']
    
    admin.site.register(Poll, PollAdmin)
  6. to split fieldsets
    class PollAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['question']}),
            ('Date information', {'fields': ['pub_date']}),
        ]
    
    admin.site.register(Poll, PollAdmin)
  7. 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]
  8. 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?'
    
  9. Searching
    search_fields = ['question']
  10. Drill down by date
    date_hierarchy = 'pub_date
  11. Customizing template directory in settings.py file
    TEMPLATE_DIRS = (
        "/home/my_username/mytemplates", # Change this to your own directory.
    )
    

Creating “Views” and URLs

  1. 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'),
    )
  2. Add called functions such as
    def detail(request, poll_id):
        return HttpResponse("You're looking at poll %s." % poll_id)
  3. 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})
    
  4. 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})
    
  5. Same for 500 (Error)
  6. 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 %}

———–

, ,

  1. #1 by chakrit on October 14, 2008 - 4:40 pm

    wah… I want to learn Python and Django too but never has the time for it..

    hope you can teach me sometimes in the future🙂

  2. #2 by ijemmy on October 15, 2008 - 11:57 am

    Fine, it’ll take only 2 hours for an overview, so you can have a background to continue studying further.

    BTW, I have never try C#, ASP, and .NET framework too😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: