您现在的位置:首页 >> 前端 >> 内容

Django学习流程精简记录

时间:2017/7/25 14:30:17 点击:

  核心提示:Django学习流程精简记录。1、django-admin startproject mysite2、python manage.py startapp polls3、编写app里面的models.p...

Django学习流程精简记录。
1、django-admin startproject mysite
2、python manage.py startapp polls
3、编写app里面的models.py文件

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

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

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

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

    def __str__(self):
        return self.choice_text

4、python manage.py makemigrations,为这些修改创建迁移文件
5、python manage.py migrate,将这些改变更新到数据库中。
6、python manage.py createsuperuser
7、修改polls/admin.py让poll应用在管理站点中可编辑

from django.contrib import admin

from .models import Question

admin.site.register(Question)

8、创建一个模型管理对象(class),然后把该对象(class名)作为第二个参数传入admin.site.register(),来自定义管理表单

from django.contrib import admin

# Register your models here.
from .models import Question

class QuestionAdmin(admin.ModelAdmin):
    fields = ['pub_date','question_text']

admin.site.register(Question,QuestionAdmin)

9、把表单分割成字段集,fieldsets中每个元组的第一个元素是字段集的标题

from django.contrib import admin

# Register your models here.
from .models import Question

class QuestionAdmin(admin.ModelAdmin):
    # fields = ['pub_date','question_text']
    fieldsets = [
        (None,              {'fields':['question_text']}),
        ('时间信息',{'fields':['pub_date']}),
    ]

admin.site.register(Question,QuestionAdmin)

10、创建Question对象的同时可以直接添加一组Choice

from django.contrib import admin

# Register your models here.
from .models import Question,Choice

class ChoiceInline(admin.StackedInline):
    model = Choice
    extra = 3

class QuestionAdmin(admin.ModelAdmin):
    # fields = ['pub_date','question_text']
    fieldsets = [
        (None,              {'fields':['question_text']}),
        ('时间信息',{'fields':['pub_date']}),
    ]
    inlines = [ChoiceInline]

admin.site.register(Question,QuestionAdmin)
# admin.site.register(Choice)

这告诉Django:Choice对象在Question的管理界面中编辑。默认提供足够3个Choice的空间

11、默认地,Django显示每个对象的str()返回的内容。但有时如果我们能显示个别的字段将很有帮助。 我们使用list_display 选项来实现这个功能

from django.contrib import admin

# Register your models here.
from .models import Question,Choice

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

class QuestionAdmin(admin.ModelAdmin):
    # fields = ['pub_date','question_text']
    fieldsets = [
        (None,              {'fields':['question_text']}),
        ('时间信息',{'fields':['pub_date']}),
    ]
    inlines = [ChoiceInline]
    list_display = ('question_text','pub_date','was_published_recently')

admin.site.register(Question,QuestionAdmin)
# admin.site.register(Choice)

12、添加过滤器和搜索功能

from django.contrib import admin

# Register your models here.
from .models import Question,Choice

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

class QuestionAdmin(admin.ModelAdmin):
    # fields = ['pub_date','question_text']
    fieldsets = [
        (None,              {'fields':['question_text']}),
        ('时间信息',{'fields':['pub_date']}),
    ]
    inlines = [ChoiceInline]
    list_display = ('question_text','pub_date','was_published_recently')
    list_filter = ['pub_date']
    search_fields = ['question_text']

admin.site.register(Question,QuestionAdmin)
# admin.site.register(Choice)

13、自定义管理界面模版
14、修改视图函数,修改urlconf,把app里面的urls.py包含进去
https://django-intro-zh.readthedocs.io/zh_CN/latest/part3/

# polls/urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index,name='index'),
    url(r'^(?P[0-9]+)/$', views.detail,name='detail'),
    url(r'^(?P[0-9]+)/results/$', views.results,name='results'),
    url(r'^(?P[0-9]+)/vote/$', views.vote,name='vote'),
]

15、载入 polls/index.html 模板文件,并且向它传递一个上下文环境(context)

# polls/views.py

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))

16.快捷函数render

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from .models import Question
from django.template import loader

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]

    # output = ','.join([p.question_text for p in latest_question_list])
    # template = loader.get_template('polls/index.html')
    context = {'latest_question_list':latest_question_list}

    return render(request,'polls/index.html',context)

17.抛出 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})

18.快捷函数:get_object_of_404()

# 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})

19.去除模板中的硬编码 URL,在 polls.urls 的 urls() 函数中通过 name 参数为 URL 定义了名字,你可以使用 {% url %} 标签代替它
20.为 URL 名称添加命名空间

# mysite/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
]

现在,编辑 polls/index.html 文件,从:
  • {{ question.question_text }}
  • 修改成:
  • {{ question.question_text }}

20.编写视图函数,可以精简删除旧的 index、detail和 results 视图,并用 Django 的通用视图代替(第四部分)
21.编写表单做测试

Tags:DJ JA AN NG 
作者:网络 来源:张昆的博客