我有以下表格:
forms.py
class TipoDePagoForm(forms.Form):
tipo_de_pago = forms.ChoiceField(widget=forms.RadioSelect, choices=FORMAS_PAGO, required=True)
folio = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Folio',
'aria-describedby': 'basic-addon2'
}), required= False)
medio_venta = forms.ModelChoiceField(queryset= MediosVenta.objects.all())
HTML中的ModelChoiceField是这样表示的:
<form method="POST" class="card-body">
{% csrf_token %}
<h3>Opciones de Pago</h3>
<div class="d-block my-3">
{% for value, name in tipodepagoform.fields.tipo_de_pago.choices %}
<div class="custom-control custom-radio">
<input id="{{ name }}" name="tipo_de_pago" value="{{ value }}" type="radio" class="custom-control-input" required>
<label class="custom-control-label" for="{{ name }}">{{ name }}</label>
</div>
{% endfor %}
</div>
<div class="d-block my-3">
<label for="folio">{{ tipodepagoform.folio }}</label>
</div>
<div class="d-block my-3">
<select name="{{ tipodepagoform.medio_venta.nombre }}" id="{{ tipodepagoform.medio_venta.id_for_label }}">
{% for value, name in tipodepagoform.fields.medio_venta.choices %}
<option value="{{ value }}" {% if tipodepagoform.medio_venta.value == value %} selected {% endif %}>{{ name }}</option>
{% endfor %}
</select>
</div>
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit" >Pagar</button>
</form>
在视图(视图的一部分)中执行POST时:
def post(self, *args, **kwargs):
today = date.today()
tipodepagoform = TipoDePagoForm(self.request.POST or None)
if tipodepagoform.is_valid():
tipo_de_pago = tipodepagoform.cleaned_data.get('tipo_de_pago')
folio = tipodepagoform.cleaned_data.get('folio')
medio_venta = tipodepagoform.cleaned_data.get('medio_venta')
print(medio_venta)
form_is无效,并显示以下错误:
<ul class="errorlist"><li>medio_venta<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
打印我看到的选择“无”值的表单:
<tr><th><label for="id_medio_venta">Medio venta:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select name="medio_venta" required id="id_medio_venta">
<option value="" selected>---------</option>
<option value="1">Gimnasio</option>
<option value="2">Marketplace</option>
<option value="3">Membresías</option>
</select></td></tr>
我不知道为什么即使我选择了任何带有值的选项,它实际上也没有选择。
打印后:
<QueryDict: {'XXXXXXXXXX], 'tipo_de_pago': ['Efectivo'], 'folio': ['']}>
帖子没有获得模型选择字段
1条答案
按热度按时间pbgvytdp1#
我想你这里有一个错误:
尝试在以下位置更改它: