Source address: http://python.usyiyi.cn/documents/django_182/intro/tutorial02.html
Address 2: https://django-intro-zh.readthedocs.io/zh_CN/latest/whats_next/
1,django-admin startproject mysite
2,python manage.py startapp polls
3. Write models.py file in app
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 management. py makemigrations to create migration files for these changes
5. Python management. py migrate, update these changes to the database.
6,python manage.py createsuperuser
7. Modify polls/admin.py to allow poll applications to be editable in management sites
from django.contrib import admin
from .models import Question
admin.site.register(Question)
8. Create a model management object (class), and then pass the object (class name) as the second parameter to admin.site.register() to customize the management form.
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. Divide the form into field sets. The first element of each tuple in field sets is the title of the field set.
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']}),
('Time information',{'fields':['pub_date']}),
]
admin.site.register(Question,QuestionAdmin)
10. You can add a set of Choice s directly while creating Question objects
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']}),
('Time information',{'fields':['pub_date']}),
]
inlines = [ChoiceInline]
admin.site.register(Question,QuestionAdmin)
# admin.site.register(Choice)
This tells Django: Choice objects to be edited in the Question management interface. Provide enough space for three choices by default
11. By default, Django displays the contents returned by str() for each object. But sometimes it would be helpful if we could display individual fields. We use the list_display option to do this.
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']}),
('Time information',{'fields':['pub_date']}),
]
inlines = [ChoiceInline]
list_display = ('question_text','pub_date','was_published_recently')
admin.site.register(Question,QuestionAdmin)
# admin.site.register(Choice)
12. Adding filters and search functions
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']}),
('Time information',{'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. Custom Management Interface Template
14. Modify the view function, modify urlconf, and include urls.py in app
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<question_id>[0-9]+)/$', views.detail,name='detail'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.results,name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote,name='vote'),
]
15. Load the polls/index.html template file and pass it a 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. Shortcut function 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. Throw 404 errors
# 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. Shortcut function: 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. Remove hard-coded URLs from templates and define URLs by name parameter in the urls() function of polls.urls. You can use the {% url%} tag instead.
20. Add a namespace for the URL name
# 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)),
]
//Now edit the polls/index.html file from:
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
//Amend to read:
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
20. Write view functions to simplify and delete old index, detail, and results views, and replace them with Django's general view (Part 4)
21. Write forms for testing