我有以下型号:
models.py
class RegistroPago(models.Model):
fechaPago = models.DateField(default=timezone.now)
contrato = models.ForeignKey(Contrato, on_delete=models.CASCADE)
formapago = models.ForeignKey(FormaPago, on_delete=models.CASCADE)
nota = models.CharField(max_length=255, blank=True)
archivo = models.FileField(upload_to='images/', blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.pk)
class RegistroPagoDato(models.Model):
registropago = models.ForeignKey(RegistroPago,
related_name='items',on_delete=models.CASCADE)
# aqui el secreto fue este related_name = 'items'
categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE)
concepto = models.CharField(max_length=150, verbose_name="Concepto")
importe = models.DecimalField(max_digits=12, decimal_places=2,
default=0)
def __str__(self):
# return self.cliente
return str(self.pk)
views.py
class CrearRegistroPago(CreateView):
model = RegistroPago
template_name = 'registropago.html'
form_class = RegistroPagoForm
success_url = reverse_lazy('listado_pagos')
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
detalle_orden_registro_pago_formset = DetalleRegistroPagoFormSet()
return self.render_to_response(self.get_context_data(form=form,
detalle_registro_pago_form_set=detalle_orden_registro_pago_formset))
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
detalle_registro_pago_form_set = DetalleRegistroPagoFormSet(
request.POST)
if form.is_valid() and detalle_registro_pago_form_set.is_valid():
return self.form_valid(form, detalle_registro_pago_form_set)
else:
return self.form_invalid(form, detalle_registro_pago_form_set)
def form_valid(self, form, detalle_registro_pago_form_set):
form.instance.user = self.request.user
self.object = form.save()
detalle_registro_pago_form_set.instance = self.object
detalle_registro_pago_form_set.save()
return HttpResponseRedirect(self.success_url)
def form_invalid(self, form, detalle_registro_pago_form_set):
return self.render_to_response(self.get_context_data(form=form,
detalle_registro_pago_form_set=detalle_registro_pago_form_set))
def get_form_kwargs(self):
kwargs = super(CrearRegistroPago, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs
和forms.py
class RegistroPagoForm(forms.ModelForm):
class Meta:
model = RegistroPago
labels = {
"contrato": "Contrato / Nombre del Inquilino:",
"fechaPago": "Fecha de Pago:",
"formapago": "Forma de Pago:",
"nota": "Agregar Nota:",
}
fields = ['fechaPago', 'contrato', 'formapago', 'nota', 'archivo',]
def __init__(self, user, *args, **kwargs):
super(RegistroPagoForm, self).__init__(*args, **kwargs)
self.fields['contrato'].queryset =
Contrato.objects.all().filter(user=user, status=1)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
class RegistroPagoDatoForm(forms.ModelForm):
class Meta:
model = RegistroPagoDato
fields = ['categoria', 'concepto', 'importe',]
def __init__(self, *args, **kwargs):
super(RegistroPagoDatoForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
DetalleRegistroPagoFormSet = inlineformset_factory(RegistroPago,
RegistroPagoDato, form=RegistroPagoDatoForm, extra=4)
formset = DetalleRegistroPagoFormSet(initial=[{'categoria': 6, 'concepto':
'probando, 123 probando', 'importe': 999.99}, {'concepto': 'probando, 123
probando'}, {'importe': 999.99},])
for form in formset:
print(form.as_table())
当我想捕获新的付款时,使用inlineformset_factory创建的RegistrationPagoDatoForm表单字段显示为预先填充了以下内容中定义的初始值,我无法工作:
formset = DetalleRegistroPagoFormSet(initial=[{'categoria': 6, 'concepto':
'probando, 123 probando', 'importe': 999.99}, {'concepto': 'probando,
123 probando'}, {'importe': 999.99},])
有趣的是,当您看到由print(form.as_table())的DetailRegistroPagoFormSet生成的html时,初始值会正确生成!
<tr><th><label for="id_items-0-categoria">Categoria:</label></th><td><select
name="items-0-categoria" class="form-control" id="id_items-0-categoria">
<option value="">---------</option>
<option value="1">Renta</option>
<option value="2">Agua</option>
<option value="3">Electricidad</option>
<option value="4">Gas</option>
<option value="5">Intereses</option>
<option value="6" selected>Depósito</option>
<option value="7">Mantenimiento</option>
</select></td></tr>
<tr><th><label for="id_items-0-concepto">Concepto:</label></th><td><input
type="text" name="items-0-concepto" value="probando, 123 probando"
maxlength="150" class="form-control" id="id_items-0-concepto"></td></tr>
<tr><th><label for="id_items-0-importe">Importe:</label></th><td><input
type="number" name="items-0-importe" value="999.99" step="0.01" class="form-
control" id="id_items-0-importe"></td></tr>
<tr><th><label for="id_items-0-DELETE">Eliminar:</label></th><td><input
type="checkbox" name="items-0-DELETE" id="id_items-0-DELETE"><input
type="hidden" name="items-0-id" id="id_items-0-id"><input type="hidden"
name="items-0-registropago" id="id_items-0-registropago"></td></tr>
<tr><th><label for="id_items-1-categoria">Categoria:</label></th><td><select
name="items-1-categoria" class="form-control" id="id_items-1-categoria">
<option value="" selected>---------</option>
<option value="1">Renta</option>
<option value="2">Agua</option>
<option value="3">Electricidad</option>
<option value="4">Gas</option>
<option value="5">Intereses</option>
<option value="6">Depósito</option>
<option value="7">Mantenimiento</option>
</select></td></tr>
<tr><th><label for="id_items-1-concepto">Concepto:</label></th><td><input
type="text" name="items-1-concepto" value="probando, 123 probando"
maxlength="150" class="form-control" id="id_items-1-concepto"></td></tr>
<tr><th><label for="id_items-1-importe">Importe:</label></th><td><input
type="number" name="items-1-importe" value="0" step="0.01" class="form-
control" id="id_items-1-importe"></td></tr>
<tr><th><label for="id_items-1-DELETE">Eliminar:</label></th><td><input
type="checkbox" name="items-1-DELETE" id="id_items-1-DELETE"><input
type="hidden" name="items-1-id" id="id_items-1-id"><input type="hidden"
name="items-1-registropago" id="id_items-1-registropago"></td></tr>
<tr><th><label for="id_items-2-categoria">Categoria:</label></th><td><select
name="items-2-categoria" class="form-control" id="id_items-2-categoria">
<option value="" selected>---------</option>
<option value="1">Renta</option>
<option value="2">Agua</option>
<option value="3">Electricidad</option>
<option value="4">Gas</option>
<option value="5">Intereses</option>
<option value="6">Depósito</option>
<option value="7">Mantenimiento</option>
</select></td></tr>
<tr><th><label for="id_items-2-concepto">Concepto:</label></th><td><input
type="text" name="items-2-concepto" maxlength="150" class="form-control"
id="id_items-2-concepto"></td></tr>
<tr><th><label for="id_items-2-importe">Importe:</label></th><td><input
type="number" name="items-2-importe" value="999.99" step="0.01" class="form-
control" id="id_items-2-importe"></td></tr>
<tr><th><label for="id_items-2-DELETE">Eliminar:</label></th><td><input
type="checkbox" name="items-2-DELETE" id="id_items-2-DELETE"><input
type="hidden" name="items-2-id" id="id_items-2-id"><input type="hidden"
name="items-2-registropago" id="id_items-2-registropago"></td></tr>
但是在浏览器中不会出现初始值:
我想要实现的是,当我获得新的付款时,该表格如下所示:
谢谢!