本文主要总结一下Django2.1的使用入门。

1、查看Django版本:

import django
print(django.get_version())

或者

python3 -m django --version

2、创建项目(Project)

首先要确保/usr/local/bin/django-admin是Python3版本的

django-admin startproject mysite

目录结构:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

PS.创建完成之后,manage.py文件默认使用的是#!/usr/bin/env python,如果使用Python3,需要修改为#!/usr/bin/env python3

3、直接开启Django服务器

python3 manage.py runserver [port]

PS.这样开启的服务器是没有做任何配置的Django服务器,没有设置port的时候默认port为8000,启动服务后访问http://127.0.0.1:8000即可看到Django服务器

4、创建应用(App)

使用如下命令创建App:

python3 manage.py startapp polls

polls目录结构如下:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

5、编写第一个视图文件

修改文件polls/views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

6、修改App中的URL设置

修改文件polls/urls.py,不存在该文件可自行创建

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

7、在Project中引用App的URL配置:

修改文件mysite/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

8、设置数据库

修改文件mysite/settings.py 默认数据库连接方式如下:

DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3',
         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
     }
}

修改为以下内容:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',         
        'NAME': 'dbname',
        'USER': 'dbuser',
        'PASSWORD': 'dbpwd',
        'HOST': 'dbhost',
        'PORT': 'dbport',
    }
}

常见SQL引擎有:

'django.db.backends.sqlite3'
'django.db.backends.postgresql'
'django.db.backends.mysql'
'django.db.backends.oracle'

9、生成Django默认数据表

python3 manage.py migrate

10、创建自定义模型

修改文件:polls/models.py

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

11、激活自定义模型

修改文件mysite/settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

12、将自定义模型中的修改实现到数据表

I、生成一次模型迁移

python3 manage.py makemigrations polls

II、生成SQL

python3 manage.py sqlmigrate polls 0001

III、更新数据表

python3 manage.py migrate

13、为自定义模型添加自定义方法

修改文件polls/models.py

I、添加__str__()方法

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

II、添加其它自定义方法

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

14、创建管理员账户

python3 manage.py createsuperuser

15、在管理页面添加model管理入口

修改文件polls/admin.py

from django.contrib import admin

from .models import Question

admin.site.register(Question)

16、添加新的视图

I、修改文件polls/views.py

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

II、修改文件polls/urls.py

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

III、重新修改polls/views.py

from django.http import HttpResponse

from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

# Leave the rest of the views (detail, results, vote) unchanged

IV、创建视图模板文件polls/templates/polls/index.html

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

VI、更新polls/views.py的index方法

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

VII、使用快捷函数render()替代HttpResponse()

修改文件polls/views.py

from django.shortcuts import render

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

VIII、处理404错误

修改文件polls/views.py

from django.http import Http404
from django.shortcuts import render

from .models import Question
# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

IX、添加detail模板polls/templates/polls/detail.html

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

X、使用快捷函数get_object_or_404()替代try...catch...以及Http404

修改文件polls/views.py

from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

17、去除模板中的硬编码

I、修改文件polls/index.html中的硬编码

原内容:

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

修改后内容:

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

18、为URL名称添加命名空间

I、修改文件polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

II、修改模板文件polls/index.html

原文件:

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

修改后:

<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

19、添加表单

I、修改文件polls/templates/polls/detail.html

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

II、修改polls/views.py的vote方法

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question
# ...
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

III、修改polls/views.py的result方法

from django.shortcuts import get_object_or_404, render


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

IV、修改polls/templates/polls/results.html

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

20、使用通用视图改良URLConf

I、修改文件polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

II、修改文件polls/views.py

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    ... # same as above, no changes needed.

21、进行自动化测试

I、编写测试文件polls/tests.py

import datetime

from django.test import TestCase
from django.utils import timezone

from .models import Question


class QuestionModelTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        """
        was_published_recently() returns False for questions whose pub_date
        is in the future.
        """
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

II、执行测试

python3 manage.py test polls

22、使用自定义static文件

I、添加样式文件polls/static/polls/style.css

body {
    background: white url("images/background.gif") no-repeat;
}
li a {
    color: green;
}

II、模板文件polls/templates/polls/index.html引入静态文件

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">

本文就记录到这里,后续还有要补充的再加上。