django basics

Author: yifei / Created: April 29, 2018, 9:19 p.m. / Modified: April 29, 2018, 10 p.m. / Edit






use a settings dir, and put all the settings in the dir use --settings option or the DJANGO_SETTINGS_MODULE variable keep everyone's dev settings in the settings dir in version control secrets should be in env the django-admin diffsettings command


start a project

% django startproject <project_name>

start an app

to use django models, you have to create django apps, a bundle of Django code, including models and views, that live together in a single Python package and represent a full Django application.

./ startapp <app_name>

register in the INSTALLED_APPS

NOTE: django project name and app name can NOT be the same, weird...

start development server

./ runserver [bind_address:port]

adding views

  1. add a function in /
  2. import it in the
  3. add one line in the urlpatterns list url(regex, func, name)

from django.http import HttpResponse

def hello(request):
    return HttpResponse("hello world")

if you want parameters, capture them in the url regex and pass them as parameters along with request to handler functions


from django.template import Template
t = Template(temp_str)
c = Context(context_dict)

you can omit the parentheses for method call, however basically, the template engine is like jinja2

the forloop variable

forloop.counter 1 based value forloop.counter0 0 based value forloop.first bool to indicate whether is first forloop.last


from django.shortcuts import render render(request, template_file, context_dict)

block/include are all the same with jinja2 template

HttpRequest & HttpResponse

request.path full path request.get_host hostname + port reuqest.is_secure True or False request.META headers in ALL_CAPS request.GET dict like object request.POST

有任何问题可以发邮件到 kongyifei (at) 讨论