Django入门笔记(一)_建站基本流程 逻辑总览 基本环境 虚拟配置 命令行 创建模型 URLconf 视图编写 模板编写 全局settings 测试 超级用户
逻辑总览
基本环境
pip3 install virtualenv
虚拟配置
virtualenv - p python3 BASE_DIR/ . . / venv
venv/ Scripts/ activate
find / - name virtualenv
source venv/ bin / activate
deactivate
命令行
pip install django
python - m django - - version
django- admin startproject mysite
django- admin startapp polls
python manage. py runserver
http: // 127.0 .0 .1 : 8000 /
创建模型
模型脚本 vi BASE_DIR/polls/
+ models.py
from django. db import modelsclass Question ( models. Model) : question_text = models. CharField( max_length= 200 , ) pub_date = models. DateTimeField( 'date published' ) def __str__ ( self) : return self. question_textclass Choice ( models. Model) : question = models. ForeignKey( Question, on_delete= models. CASCADE, related_name= 'choice' ) choice_text = models. CharField( max_length= 200 ) votes = models. IntegerField( default= 0 ) def __str__ ( self) : return self. choice_text
python manage. py makemigrations
python manage. py makemigrations polls
python manage. py migrate
URLconf
from django. contrib import admin
from django. urls import path
from django. conf. urls import url, includeurlpatterns = [ url( r'polls/' , include( 'polls.urls' ) ) , url( r'admin/' , admin. site. urls) ,
]
vi BASE_DIR/polls/
+ urls.py
from django. conf. urls import urlfrom . import viewsapp_name = 'polls'
urlpatterns = [ url( r'^$' , views. polls, name= 'polls' ) , url( r'^question_list/$' , views. question_list, name= 'question_list' ) , url( r'^question_list/detail/(?P<question_id>\d+)/$' , views. detail, name= 'detail' ) , url( r'^vote/(\d+)/$' , views. vote, name= 'vote' ) , url( r'^results/(\d+)/$' , views. results, name= 'results' ) ,
]
视图编写
vi BASE_DIR/polls/
+ views.py
from django. shortcuts import render, get_object_or_404
from django. http import HttpResponse, HttpResponseRedirect
from django. template import loader
from django. urls import reversefrom . models import Question, Choicedef polls ( request) : context = "the polls index" return render( request, 'polls.html' , { 'context' : context} ) def question_list ( request) : questions = Question. objects. all ( ) return render( request, 'question_list.html' , { 'questions' : questions} ) def detail ( request, question_id) : question = get_object_or_404( Question, pk= question_id) return render( request, 'detail.html' , { 'question' : question} ) def vote ( request, question_id) : question = get_object_or_404( Question, pk= question_id) try : selected_choice = question. choice. get( pk= request. POST[ 'choice' ] ) except ( KeyError, Choice. DoesNotExist) : return render( request, 'detail.html' , { 'question' : question, 'error_message' : "You didn't select a choice." , } ) selected_choice. votes += 1 selected_choice. save( ) return HttpResponseRedirect( reverse( 'polls:results' , args= ( question. id , ) ) ) def results ( request, question_id) : question = get_object_or_404( Question, pk= question_id) return render( request, 'results.html' , { 'question' : question} )
模板编写
cp bootstrap. min . css BASE_DIR/ polls/ static/
cd BASE_DIR/polls/templates/
polls.html
{% load static %}
< link rel = " stylesheet" href = " {% static ' css/bootstrap.min.css' %}" >
< div class = " container" > < ol class = " breadcrumb my-4" > < li class = " breadcrumb-item active" > polls</ li> < li class = " breadcrumb-item" > < a href = " {% url ' polls:question_list' %}" > question_list</ a> </ li> </ ol> < h1 class = " breadcrumb my-4" > {{ context }}</ h1> < a href = " {% url ' polls:question_list' %}" > show all question</ a>
</ div>
{% load static %}
< link rel = " stylesheet" href = " {% static ' css/bootstrap.min.css' %}" >
< div class = " container" > < ol class = " breadcrumb my-4" > < li class = " breadcrumb-item" > < a href = " {% url ' polls:polls' %}" > polls</ a> </ li> < li class = " breadcrumb-item active" > question_list</ li> </ ol> < h1 class = " breadcrumb my-4" > question_list</ h1> {% if not questions %}< p> < strong> empty question</ strong> </ p> {% else %}< table class = " table" > < thead class = " thead-dark" > < tr> < th> question_text</ th> < th> pub_date</ th> </ tr> </ thead> < tbody> {% for question in questions %}< tr> < td> < a href = " {% url ' polls:detail' question.id %}" > {{ question.question_text }}</ a> < small class = " text-muted d-block" > {{ forloop.counter }}</ small> </ td> < td class = " align=middle" > {{ question.pub_date }}</ td> </ tr> {% endfor %}</ tbody> </ table> {% endif %}
</ div>
{% load static %}
< link rel = " stylesheet" href = " {% static ' css/bootstrap.min.css' %}" >
< div class = " container" > < ol class = " breadcrumb my-4" > < li class = " breadcrumb-item" > < a href = " {% url ' polls:polls' %}" > polls</ a> </ li> < li class = " breadcrumb-item" > < a href = " {% url ' polls:question_list' %}" > question_list</ a> </ li> < li class = " breadcrumb-item active" > detail</ li> </ ol> < h1 class = " breadcrumb my-4" > {{ question.question_text }}</ h1> {% if error_message %}< p> < strong> {{ error_message }}</ strong> </ p> {% endif %}{% if not question.choice.all %}< p> < strong> empyt choice </ strong> </ p> {% else %}< form action = " {% url ' polls:vote' question.id %}" method = " post" > {% csrf_token %}{% for choice in question.choice.all %}< input type = " radio" id = " choice_{{ forloop.counter }}" name = " choice" value = " {{ choice.id }}" /> < label for = " choice_{{ forloop.counter }}" > {{ choice.choice_text }}</ label> < br /> {% endfor %}< input type = " submit" value = " Vote" /> </ form> {% endif %}
</ div>
{% load static %}
< link rel = " stylesheet" href = " {% static ' css/bootstrap.min.css' %}" >
< div class = " container" > < ol class = " breadcrumb my-4" > < li class = " breadcrumb-item" > < a href = " {% url ' polls:polls' %}" > polls</ a> </ li> < li class = " breadcrumb-item" > < a href = " {% url ' polls:question_list' %}" > question_list</ a> </ li> < li class = " breadcrumb-item active" > result</ li> </ ol> < h1 class = " breadcrumb my-4" > {{ question.question_text }}</ h1> < table class = " table" > < thead class = " thead-dark" > < tr> < th> choice</ th> < th> count</ th> </ tr> </ thead> < tbody> {% for choice in question.choice.all %}< tr> < td> {{ choice.choice_text }}</ td> < td> {{ choice.votes }} vote{{ choice.votes|pluralize }}</ td> </ tr> {% endfor %}</ tbody> </ table> < a href = " {% url ' polls:detail' question.id %}" > Vote again?</ a>
</ div>
全局settings
vi BASE_DIR/mysite/
+ settings.py
INSTALLED_APPS = [ 'polls' ,
]
TEMPLATES = [ { 'DIRS' : [ os. path. join( BASE_DIR, 'templates' ) ] , 'APP_DIRS' : True , } ,
]
STATIC_URL = '/static/' STATICFILES_DIRS = [ os. path. join( BASE_DIR, 'static' ) ,
]
测试
vi BASE_DIR/polls/
+ tests.py
from django. test import TestCase
from django. urls import reverse, resolvefrom . views import polls, question_list, detail, vote , results
from . models import Question
from django. utils import timezoneclass PollsTests ( TestCase) : def test_polls_view_status_code ( self) : url = reverse( 'polls:polls' ) response = self. client. get( url) self. assertIs( response. status_code, 200 ) self. assertContains( response, 'polls' ) def test_polls_url_resolve_polls_view ( self) : view = resolve( '/polls/' ) self. assertEqual( view. func, polls) class Question_listTests ( TestCase) : def test_question_list_status_code ( self) : Question. objects. create( question_text= "test_question_list_status_code" , pub_date= timezone. now( ) ) url = reverse( 'polls:question_list' ) response = self. client. get( url) self. assertIs( response. status_code, 200 ) def test_question_list_status_code_empty ( self) : url = reverse( 'polls:question_list' ) response = self. client. get( url) self. assertIs( response. status_code, 200 ) self. assertContains( response, 'empty' ) self. assertQuerysetEqual( response. context[ 'questions' ] , [ ] ) def test_question_list_url_resolve_polls_view ( self) : view = resolve( '/polls/question_list/' ) self. assertEquals( view. func, question_list) class DetailTests ( TestCase) : def setUp ( self) : q1= Question. objects. create( question_text= "DetailTests" , pub_date= timezone. now( ) ) q1. choice. create( choice_text= 'someone' ) q2= Question. objects. create( question_text= "DetailTests_empty" , pub_date= timezone. now( ) ) def test_detail_view_status_code ( self) : url = reverse( 'polls:detail' , args= ( 1 , ) ) response = self. client. get( url) self. assertIs( response. status_code, 200 ) def test_detail_view_status_code_empty ( self) : url = reverse( 'polls:detail' , args= ( 2 , ) ) response = self. client. get( url) self. assertContains( response, 'empty' ) def test_detail_url_resolve_polls_view ( self) : view = resolve( '/polls/question_list/detail/1/' ) self. assertEqual( view. func, detail) class VoteTests ( TestCase) : def test_vote_url_resolve_polls_view ( self) : view = resolve( '/polls/vote/1/' ) self. assertEqual( view. func, vote) class ResultsTests ( TestCase) : def setUp ( self) : Question. objects. create( question_text= "ResultsTests" , pub_date= timezone. now( ) ) def test_result_view_status_code ( self) : url = reverse( 'polls:results' , args= ( 1 , ) ) response = self. client. get( url) self. assertIs( response. status_code, 200 ) def test_result_url_resolve_polls_view ( self) : view = resolve( '/polls/results/1/' ) self. assertEqual( view. func, results)
python manage. py test
超级用户
python manage. py createsuperuser
cp django/ contirb/ admin/ templates/ base_site. html BASE_DIR/ templates/ admin/
< h1 id = "site-name" > < a href= "{% url 'admin:index' %}" > Polls Administration< / a> < / h1>
vi BASE_DIR/polls/
+ admin.py
from django. contrib import adminfrom . models import Question, Choiceclass ChoiceInline ( admin. TabularInline) : model = Choiceextra = 3 class QuestionAdmin ( admin. ModelAdmin) : fieldsets = [ ( 'Question' , { 'fields' : [ 'question_text' ] } ) , ( 'Date information' , { 'fields' : [ 'pub_date' ] , 'classes' : [ 'collapse' ] } ) , ] inlines = [ ChoiceInline] list_display = ( 'question_text' , 'pub_date' ) list_filter = [ 'pub_date' ] search_fields = [ 'question_text' ] class ChoiceAdmin ( admin. ModelAdmin) : fields= [ 'question' , 'choice_text' , 'votes' ] list_display = ( 'choice_text' , 'question' , 'votes' ) admin. site. register( Question, QuestionAdmin)
admin. site. register( Choice, ChoiceAdmin)