[django实践]投票app
code: https://github.com/lannyMa/toupiao
polls app介绍
这个例子来源于django官网,恰好2.x版本有中文版. https://docs.djangoproject.com/zh-hans/2.0/intro/tutorial01/
功能介绍
-
首页
-
投票
-
投票结果页
从首页点选项,进入投票(detail)页, 选择-vote(result),跳转到投票页重新投票
代码里值得学习的
1.取出关联表中的数据
detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
2: url的redirect和reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from app01.models import Question, Choice
from django.urls import reverse
path('specifics/<int:question_id>/', views.detail, name='detail'),
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
return HttpResponseRedirect(reverse('app02:results', args=(question.id,)))
取出所有和取出某一个
https://docs.djangoproject.com/zh-hans/2.0/intro/tutorial04/
关于时间
class Question(models.Model):
question_text = models.CharField(max_length=50)
pub_date = models.DateTimeField(timezone.now())
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
return self.question_text
class Choice(models.Model):
question_text = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=50)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
关于get_object_or_404
https://docs.djangoproject.com/zh-hans/2.0/intro/tutorial03/
detail
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})
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})