我正在使用ModelFormSet发送多个QRCode模型对象实例,但是在提交表单'id': ['This field is required.']
时,错误出现在views.py
(formset.errors
)
最初,我确实将所有表单字段都一一包括在内,但是试图修复刚刚将整个{{ form }}
粘贴到模板中的表单,以便将所有隐藏字段都放在其中。
template.html
:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.formset/1.2.2/jquery.formset.js"></script>
<div id="app">
<div class="container">
<h3 class="">Создание заданий</h3>
<form method="post" >
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="row">
<div class="input-field col s6">
{{ form }}
</div>
</div>
{% endfor %}
<input type="submit" class="waves-effect waves-light btn">
</form>
</div>
</div>
{# <script src="{% static 'js/quest_qrs.js' %}"></script>#}
{% endblock %}
models.py
:
class QRCode(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
body = models.TextField()
nextStep = models.ForeignKey(
'self',
on_delete=models.CASCADE,
null=True,
blank=True
)
views.py
:
class QRCreateView(LoginRequired, View):
def get(self, request, pk):
data = {
'form-TOTAL_FORMS': '1',
'form-INITIAL_FORMS': '1',
'form-MAX_NUM_FORMS': '',
}
formset = QRFormSet(data)
context = {'formset': formset}
return render(request, 'qrs_create.html', context)
def post(self, request, pk):
formset = QRFormSet(request.POST)
print(formset.__dict__)
print(formset.errors)
if formset.is_valid():
starting_quest = Quest.objects.get(pk=pk)
starting_quest.startQr = formset[0]
starting_quest.save()
formset_len = len(formset)
for i in range(formset_len):
formset[i].nextStep = formset[i + 1] if i + 1 < formset_len else None
formset[i].save()
return render(request, 'index.html')
return render(request, 'qrs_create.html', {'formset': formset})
forms.py
:
QRFormSet = forms.modelformset_factory(
QRCode,
fields=('body',),
extra=1,
widgets={
'body': forms.TextInput(attrs={
'class': 'materialize-textarea',
'placeholder': 'Содержание задания',
})
},
)
下面是发送数据时formset.__dict__
和formset.errors
的打印内容
{'queryset': None,
'initial_extra': None,
'is_bound': True,
'prefix': 'form',
'auto_id': 'id_%s',
'data': <QueryDict: {'csrfmiddlewaretoken': ['1rE8onLIBWUskDEDxjdjTigIqeLaPRvjwtqdx62xsv52HvRqwtk2kn8bxTKVxhNE'],
'form-TOTAL_FORMS': ['1'],
'form-INITIAL_FORMS': ['1'],
'form-MIN_NUM_FORMS': [''],
'form-MAX_NUM_FORMS': [''],
'form-0-body': ['Task1'],
'form-0-id': ['']}>,
'files': {}, 'initial': None,
'form_kwargs': {},
'error_class': <class 'django.forms.utils.ErrorList'>,
'_errors': None,
'_non_form_errors': None}
[{'id': ['This field is required.']}