字段前键django中的“ invalid_choice”

时间:2018-11-07 00:32:37

标签: django python-3.x django-forms django-queryset

我使用查询集初始化的前键字段存在问题,但显示了表单,但在发送数据时出现错误'在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'

0 个答案:

没有答案