Я пытался выполнить итерацию request.POST.get()
, чтобы получить некоторые входные данные из соответствующего html-файла моего представления, используя конкатенацию.
Однако независимо от того, заполнен ли ввод, он всегда говорит, что ввод возвращает откат. (Как в ответе по умолчанию, который дает программист.)
Кто-нибудь знает, как это решить? Я пытаюсь сделать так, чтобы каждый вариант добавлялся к набору вариантов для каждого вопроса.
< Сильный > create.html
{% extends "polls/base.html" %}
{% block title %}Create a Poll{% endblock title %}
{% block header %}Create:{% endblock header %}
{% load custom_tags %}
{% block content %}
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:create' %}" method="post"> {% csrf_token %}
{% for field in questionfields %}
{% if field == 'question_text' %}
<label for="{{ field }}">{{ field|capfirst|replace }}:</label>
<input type="text" name="{{ field }}" id="{{ field }}">
<br>
{% endif %}
{% endfor %}
<br>
{% for choice in choicenumber|rangeof %}
<br>
<label for="choice{{ forloop.counter }}">Choice {{ forloop.counter }}</label>
<input type="text" name="choice{{ forloop.counter }}" id="choice{{ forloop.counter }}">
<br>
{% endfor %}
<br>
<br>
<input type="submit" value="Create" name="submit">
</form>
{% endblock content %}
views.py
def create(request):
choicenumber = 3
context = {
'questionfields': Question.__dict__,
'choicenumber': choicenumber,
}
submitbutton = request.POST.get('submit', False)
if submitbutton:
new_question = Question.objects.create(question_text=request.POST.get('question_text', ''), pub_date=timezone.now())
if new_question.question_text == '':
context = {
'questionfields': Question.__dict__,
'error_message': "No poll question entered.",
'choicenumber': choicenumber,
}
del new_question
return render(request, 'polls/create.html', context)
else:
new_question.save()
for i in range(choicenumber):
choice = request.POST.get(('choice' + str(i)), '')
new_question.choice_set.add(choice)
new_question.save()
return HttpResponseRedirect(reverse('polls:results', args=(new_question.id,)))
else:
return render(request, 'polls/create.html', context)
Ошибка: TypeError в экземпляре / polls / create / 'Choice' ожидался, получено ''
Метод запроса: POST
URL-адрес запроса: http://127.0.0.1:8000/polls/create/
Версия Django: 3.0.8
Тип исключения: TypeError
Значение исключения: ожидался экземпляр 'Choice', получено ''
Ошибка была в строке 52 файла:
new_question.choice_set.add (выбор)
Я был бы очень благодарен, если бы кто-нибудь мог помочь.
РЕДАКТИРОВАТЬ::
Модели по запросу:
models.py
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.boolean = True
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.short_description = 'Published recently?'
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
1 ответ
Тогда остальная часть должна быть такой:
else:
new_question.save(commit=False)
for i in range(choicenumber):
choice = request.POST.get('choice' + str(i), '')
if choice:
choice_obj = Choice.objects.create(question=new_question,choice_text=choice)
new_question.choice_set.add(choice_obj)
new_question.save()
return HttpResponseRedirect(reverse('polls:results', args=(new_question.id,)))
Похожие вопросы
Новые вопросы
python
Python — это мультипарадигмальный многоцелевой язык программирования с динамической типизацией. Он предназначен для быстрого изучения, понимания и использования, а также обеспечивает чистый и унифицированный синтаксис. Обратите внимание, что Python 2 официально не поддерживается с 01.01.2020. Если у вас есть вопросы о версии Python, добавьте тег [python-2.7] или [python-3.x]. При использовании варианта Python (например, Jython, PyPy) или библиотеки (например, Pandas, NumPy) укажите это в тегах.