验证安装
import django
print(django.get_vesion())
python3 -m django --version
创建项目
django-admin startproject mysite
运行
python3 manage.py runserver
创建应用
python3 manage.py startapp polls
添加应用
setting.py中添加
INSTALLED_APPS = [
'polls.apps.PoolsConfig',
.....
]
模型
import datetime
from django.db import models
from django.utils import timezone
#问题表模型
class Question(models.Model):
def __str__(self):
return self.question_text
def was_publish_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
question_text = models.CharField(max_length=200) #问题内容
pub_date = models.DateTimeField('date published') #提问日期
#选择表模型
class Choice(models.Model):
def __str__(self):
return self.choice_text
question = models.ForeignKey(Question, on_delete=models.CASCADE) #问题
choice_text = models.CharField(max_length=200) #选择内容
votes = models.IntegerField(default=0) #数量
生成数据表
python3 manage.py makemigrations
python3 manage.py migrate
交互式API
python3 manage.py shell
from polls.models import Question, Choice
Question.objects.all()
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
q.question_text
q.pub_date
q.question_text = "What's up?"
q.save()
Question.objects.all()
Question.objects.filter(id=1)
Question.objects.filter(question_text__startswith='What')
from django.utils import timezone
current_year = timezone.now().year
Question.objects.filter(pub_date__year=current_year)
Question.objects.get(id=2)
Question.objects.get(pk=1)
q = Question.objects.get(pk=1)
q.was_published_recently()
q = Question.objects.get(pk=1)
q.choice_set_all()
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set_create(choice_text='Just hacking again', votes=0)
c.question
q.choice_set.all()
q.choice_set.count()
Choice.objects.filter(question__pub_date__year=current_year)
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete()
创建管理员
python3 manage.py createsuperuser
向管理页面加入应用(admin.py)
admin.site.register(Question)
admin.site.register(Choice)
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')
]
polls/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
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):
print('choice=%s'%request.POST['choice'])
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,)))
polls/templates/polls/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
{% if latest_question_list %}
{% for question in latest_question_list %}
<ul>
<li>
<a href="{% url 'polls:detail' question.id %}">
{{question.question_text}}
</a>
</li>
</ul>
{% endfor %}
{% else %}
<p>No polls are avaiable</p>
{% endif %}
</body>
</html>
polls/templates/polls/detail.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>详情页</title>
</head>
<body>
{{question.question_text}}
{% 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>
</body>
</html>
polls/template/polls/results.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>results</title>
</head>
<body>
<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>
</body>
</html>