大家好!我是一个新手。使用 django 文档示例,我如何处理 #theviews.py 中的所有问题
模板:
<html>
<body>
{% for question in latest_question_list %}
<h1>{{ question.question_text }}</h1>
{% if error_message %}
<p><strong>{{ error_message }}</strong>
</p>
{% endif %}
<form id="qform" action="{% url 'polls:vote' question.id %}" method="post">{% csrf_token %} {% for choice in question.choice_set.all %}
<input type="radio" name="{{ question.id }}" id=”choice{{ forloop.counter }} " value="{{ choice.id }}” />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
<br/>{% endfor %}
</form>
{% endfor %}
<input form="qform" type="submit" value="Vote" />
</body>
</html>
views.py(这不起作用!)
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST[question.id])
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 render(request,'polls/results.html', {'question':question,
'selected_choice': selected_choice, 'error_message': error_message})
模型.py
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(‘date published’)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
forms.py
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = [
'question_text',
'choices',
]
choices = forms.ModelMultipleChoiceField(queryset=Question.choice_set, widget=forms.RadioSelect)
请告诉我我缺少什么;我非常需要帮助。谢谢大家!
最佳答案
您对每个问题都使用了单独的表单,但浏览器只接受一种表单发送给服务器,您必须使用 django Formsets对于此类问题。
更新:
另外,请注意,在每个表单上只放置一个输入很重要,您可以通过一些更改来做到这一点,并且无需Django Formsets:
我认为你的 models.py 与下面类似:
from django.db import models
class Question(models.Model):
body = models.CharField(max_length=200)
answer = models.CharField(max_length=200)
class Quiz(models.Model):
questions = models.ManyToManyField(Question)
您可以在 forms.py 中创建一个表单类来处理此问题:
from django import forms
from models import Quiz, Question
class QuizForm(forms.ModelForm):
class Meta:
model = Quiz
fields = '__all__'
questions = forms.ModelMultipleChoiceField(queryset=Question.objects.all(), widget=forms.CheckboxSelectMultiple)
您的views.py文件:
from django.shortcuts import render
from forms import QuizForm
def show(request):
return render(request, 'qtemplate.html', {'form': QuizForm()})
在模板上:
<form method="post">
{{ form }}
</form>
关于python - 一次性处理 django View 中的所有模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626047/