ValueError at /polls/add/ Представление polls.views.addQuestion не вернуло объект HttpResponse. Вместо этого оно вернуло None
Я пытаюсь передать данные из html шаблона в представление django addQuestion в моем приложении polls.Я хочу сделать добавление вопроса вместе с их шаблоном опций голосования и Я использую django==3.2 Вот мой html код
<form action="{% url 'polls:add' %}" method="post">
{% csrf_token %}
<label for="your_queston">Question: </label>
<input id="question" type="text">
<br>
<label for="choices">Choice 1</label>
<input id="choice1" type="text"><br>
<label for="choices">Choice 2</label>
<input id="choice2" type="text">
<br>
<label for="choices">Choice 3</label>
<input id="choice3" type="text">
<br>
<input type="submit" value="add">
</form>
и вот моя функция addQuestion в view.py
def addQuestion(request):
if(request.POST):
try:
if(request.POST['question']):
qtext = request.POST.get('question')
q = Question(question_text=qtext, pub_date=timezone.now())
q.save()
if(request.POST['choice1']):
q.choice_set.create(
choice_text=request.POST.get('choice1'), votes=0)
if(request.POST['choice2']):
q.choice_set.create(
choice_text=request.POST.get('choice2'), votes=0)
if(request.POST['choice3']):
q.choice_set.create(
choice_text=request.POST.get('choice3'), votes=0)
q.save()
return HttpResponseRedirect(reverse('polls:index'))
except:
pass
else:
return render(request, 'polls/addQuestion.html')
В вашем коде есть try-except. Как упоминалось в комментариях, всегда уточняйте, какой тип исключения вы хотите поймать. Но в вашем коде, если происходит исключение, функция возвращает ничего, также известное как None. Лучшим вариантом было бы:
def view(request):
if request.method == 'POST':
error = False
try:
pass # Do magic here
except YourExpectedException:
# Log the exception
error = True
if error:
return render(request, 'polls/errorPage.html'
return HttpResponseRedirect(reverse('polls:index'))
else:
return render(request, 'polls/addQuestion.html')