While using ajax with django form, getting error “Select a valid choice. That is not one of the available choices.”

前端 未结 2 789
[愿得一人]
[愿得一人] 2020-12-16 17:38

I am newbie in django. I am using simple ajax to dynamically update the choice field semester on the basis of course selection. But while s

相关标签:
2条回答
  • 2020-12-16 18:12

    The problem is that ChoiceField requires the selected option to be in its choice set.

    In the above code, the choices for semester are dynamically updating via jquery. However, these choices are not the part of semester's choice set i.e. sem_choices. Hence the problem.

    To solve this problem, include the selected value in sem_choices by using the request.POST method.

    In views.py:

    form = loginForm(request.POST)
    sem = request.POST.get('semester')
    form.fields['semester'].choices = [(sem, sem)]
    
    0 讨论(0)
  • 2020-12-16 18:18

    Another solution is to over-ride the valid_value() method of the ChoiceField. If you are not worried about the possible values the form could return, then it's as simple as this:

    class AjaxChoiceField(forms.ChoiceField):
        def valid_value(self, value):
            return True
    

    Or you could add more validation if needed.

    0 讨论(0)
提交回复
热议问题