用Django建立能在网页上投票的问卷调查
程序员文章站
2022-05-05 18:24:59
...
新建一个Mysite_v00的Django工程,startapp polls,配置好ur和setting
在polls的models创建两个类Question和Choice,可以添加问题、选择和发布时间
注意这个关联的外码q_c,很重要。
通过admin导入models的类
在polls下的views.py添加index,results1,vote1和detail1函数访问models
接下来在polls下创建tempaltes/polls文件夹添加index.html、detail.html、和results.html
接下来设置polls文件夹下的urls.py
然后运行我的问卷调查
点击查看选项和投票
点击再次投票可添加投票
投票之后可以实时刷新(星期三的票数从4变成5)
ok很简单!
分享关键代码环节
from .models import Question
from .models import Choice
from django.http import HttpResponseRedirect
from django.shortcuts import reverse
from django.shortcuts import render
def results1(request, question_id):
question = Question.objects.get(pk=question_id)
return render(request, 'polls/results.html', {'question': question})
def vote1(request, question_id):
question = Question.objects.get(pk=question_id)
try:
selected_choice = question.q_c.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results1', args=(question.id,)))
def detail1(request,question_id):
question = Question.objects.get(pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
detail.html
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote1' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.q_c.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>
index.html
<center><h1><font color="#FF0000">调用html查看问题与投票</font></h1></center>
<figure>
{% if questions %}
<ol>
{% for q in questions %}
<li>
<a href="{% url 'polls:results1' q.id %}">{{ q.question_text }}</a>
</li>
{% endfor %}
</ol>
{% else %}
No polls.
{% endif %}
</figure>
results.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.q_c.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail1' question.id %}">再次投票?</a>
喜欢就点赞吧!
上一篇: 问卷调查Html5开发总结