下面是我的模特:
class Person(models.Model):
number = models.ForeignKey(Admfiles, on_delete=models.CASCADE, blank = False)
name = models.CharField(max_length = 255, blank = False)
situation= models.CharField(max_length = 20, blank = False)
在我的模板中,输入是使用js附加输入动态创建的,所以我不知道字典的长度。
<input name="person[0][name]" value="...">
<input name="person[0][situation]" value="...">
<input name="person[1][name]" value="...">
<input name="person[1][situation]" value="...">
<input name="person[n][name]" value="...">
<input name="person[n][situation]" value="...">
如果执行,我将收到正确的值:
return HttpResponse(request.POST.get('person[0][name]'))
return HttpResponse(request.POST.get('person[0][situation]'))
如何迭代将n元素保存到模型中?
如果我正确理解了您的问题,则可以如下获取整个POST数据:
data = request.POST.dict()
然后您可以遍历此字典并保存对象。
for key in data:
value = data['key']
# save the element in your database
[[在此处输入图像描述] [1]
我终于使用了表单集库。 (首先安装pip ...)
Setting.py:
INSTALLED_APPS = [
'djangoformsetjs',
]
我的表格:
from django.forms import inlineformset_factory
class CrearImputadoForm(forms.ModelForm):
class Meta:
model = Imputado
fields = '__all__'
ImputadoFormset = inlineformset_factory(
Expediente,
Imputado,
extra=1
)
我的看法:
class CrearImputado(CreateView):
model = Imputado
form_class = CrearImputadoForm
template_name = 'crear_imputado.html'
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['formset'] = ImputadoFormset(queryset=Imputado.objects.none())
context['expedientes'] = Expediente.objects.filter(id = self.kwargs['pk'])
return context
def post (self, request, * args, ** kwargs):
#return HttpResponse(request.POST.items())
expediente = Expediente.objects.get(pk=request.POST.get('numero_id'))
form = ImputadoFormset(request.POST, instance=expediente)
if form.is_valid():
#return HttpResponse(request.POST.items())
form.save()
return redirect('repositorio:crear_delito', request.POST.get('numero_id'))
else:
#return HttpResponse(request.POST.items())
return render(request, self.template_name, {'form': form, 'mensaje':'Ocurrió un error. Contáctese con el administrador.'})
模板:
<table class="table table-striped">
{{ formset.management_form }}
{% for form in formset %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'Nuevo Imputado',
deleteText: 'Borrar',
prefix: 'imputado_set'
});
</script>
And finally import jquery.formset.js.
I don't know if it's the best way, but works fine.
[1]: https://i.stack.imgur.com/CRPaZ.png