昨天我把投票页面终于写完,怎么说呢,觉得这本书对我的帮助也不是很大,然后去看了下django的文档,发现竟然是同一个项目。。。。。。
但还是要善始善终吧,贴一下中文版的文档https://docs.djangoproject.com/zh-hans/2.1/
这次应该到了表单,我们的投票系统中成功的把问卷问题传上去了,但是没有选项,我们先去admin里添加模型,在admin里加上admin.site.register(Choice),在import模型的地方不要忘了加上Choice
之后重新启动服务器,去后台管理会发现可以添加投票选项了,这里我遇到了一个问题,之前在创建模型的时候,也就是在model文件下,构造的时候多写了一个choice,导致这边出错,如果之前是按着我的代码打下来,到这出了个Choice中没有choice的错的话,就去models里的构造器里删掉就好了,正确的应该是这样的
class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default = 0) def __str__(self): return self.choice_text
因网络原因,本篇基本上不用图片了,
然后去修改detail文件,创建了表单用于提交数据
<h1>{{ question.question_text }}</h1> {% 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="提交" /> </form>
然后再views下更改vote和results
from django.http import HttpResponseRedirect,HttpResponse from django.urls import reverse from .models import Question,Choice def vote(request,question_id): print("hello") question = get_object_or_404(Question,pk=question_id) try: selected_choice = question.choice_set.get(pk = request.POST['choice']) except(KeyError,Choice.DoseNotExist): return render(request,'polls/detail.html',{ 'question':question, 'error_message':"还没有选择任何选项", }) else: 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, 'polls/results.html' , {'question': question})
这是对投票进行处理,然后再polls下创建results.html,加入以下代码
<h1>{{question.question_text}}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{choice.choice_text}}--计票{{choice.votes}}{{choice.votes|pluralize}}次</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">重新投票</a>
提示:在自己手写这些代码的时候注意%和{}的间距,会报错的哦
然后,完成上述步骤后,就能去投票了