django - 'invalid_choice' 在字段外键 django
问题描述
我使用查询集初始化的外键字段有问题,显示表单,但在发送数据时,to_python 中的错误引发 ValidationError (self.error_messages [' invalid_choice '], code =' invalid_choice ') '出现' 。我知道有一种方法可以使“to_python”方法无效,但我仍然无法让它工作。我将不胜感激任何帮助。
我的观点:
class PlanesCreate(generic.CreateView):
model= Plan_Estudios
template_name= 'ControlEscolar/Administracion/planes/planes_form.html'
form_class= PlanForm
success_url = reverse_lazy('ControlEscolar:planes_filtro')
def get_form_kwargs(self):
kwargs = super(PlanesCreate, self).get_form_kwargs()
kwargs.update({'programa': self.request.session['programa']})
return kwargs
我的表格:
class PlanForm(forms.ModelForm):
class Meta:
model = Plan_Estudios
fields = "__all__"
widgets = {
'nombreplan': forms.TextInput(attrs={'class':'form-control'}),
'programa': forms.Select(attrs={'class':'form-control'}),
}
def __init__(self, *args, **kwargs):
p=kwargs.pop('programa', None)
super(PlanForm, self).__init__(*args, **kwargs)
query=Programa_Academico.objects.filter(pk=p)
self.fields['programa'].queryset=query #Inicialize field with query
我的模型:
class Plan_Estudios(models.Model):
nombreplan= models.CharField(max_length=30)
programa= models.ForeignKey(Programa_Academico, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.nombreplan
class Programa_Academico(models.Model):
nombreP= models.CharField(max_length=50)
siglas= models.CharField(max_length=10)
def __str__(self):
return self.siglas
错误:
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in is_valid
185. return self.is_bound and not self.errors
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in errors
180. self.full_clean()
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in full_clean
381. self._clean_fields()
File "C:\Users\Envs\py1\lib\site-packages\django\forms\forms.py" in _clean_fields
399. value = field.clean(value)
File "C:\Users\Envs\py1\lib\site-packages\django\forms\fields.py" in clean
147. value = self.to_python(value)
File "C:\Users\Envs\py1\lib\site-packages\django\forms\models.py" in to_python
1252.
raise ValidationError(self.error_messages['invalid_choice'],
code='invalid_choice')
Exception Type: KeyError at /ControlEscolar/planes/crear
Exception Value: 'invalid_choice'
解决方案
推荐阅读
- python - TypeError:无法实例化打字。可选
- python - 从标签内部获取信息 - BeautifulSoup4 (Python 3)
- r - 在 Shiny 中将 save_kable 导出为 pdf
- corda - Corda - Service origin 和 ourIdentity 是不同的身份
- javascript - 从电子邮件客户端在默认浏览器中打开链接
- node.js - MongoDB中的分组和计数操作
- sql - 如何将表名作为参数传递给 sql 表值函数?
- python - django-cms 文档:django.urls.exceptions.NoReverseMatch: 'polls' 不是注册的命名空间
- jpa - 日期范围的 JPA 规范问题
- gmail - 有没有办法在没有收到每日电子邮件时发送 Gmail 消息或创建通知?