views.py:
@login_required
def put(request, id):
question = get_object_or_404(Question, id=id)
poll_form = PollForm(request.POST, instance=question)
print(poll_form)
choice_forms = [ChoiceForm(request.POST, prefix=str(
choice.id), instance=choice) for choice in question.choice_set.all()]
if poll_form.is_valid() and all([cf.is_valid() for cf in choice_forms]):
new_poll = poll_form.save(commit=False)
new_poll.created_by = request.user
new_poll.save()
for cf in choice_forms:
new_choice = cf.save(commit=False)
new_choice.question = new_poll
new_choice.save()
return redirect('poll:index')
context = {'poll_form': poll_form, 'choice_forms': choice_forms}
return render(request, 'polls/edit_poll.html', context)
edit_poll.html:
{{poll_form.as_table}}
{% for form in choice_forms %}
{{form.as_table}}
{% endfor %}
models.py:
class Question(models.Model):
title = models.TextField(null=True, blank=True)
created_by = models.ForeignKey(User, null=True, blank=True,
related_name="created", on_delete=models.CASCADE)
forms.py:
class PollForm(forms.ModelForm):
title = forms.CharField(max_length=333, label='Question')
class Meta:
model = Question
fields = ['title']
class ChoiceForm(forms.ModelForm):
text = forms.CharField(max_length=255, label='Choice')
class Meta:
model = Choice
exclude = ('question',)
当我检查元素时:
<td><ul class="errorlist"><li>This field is required.</li></ul><input
type="text" name="title" maxlength="333" required="" id="id_title"></td>
字段是 empty
(但它应该由现有的 id
问题和选择填充)但我看到 errorlist
类我不知道。
请帮帮我。
但是当我填写edit
表格并尝试update
事情时它工作