jquery – 使用带有django形式的ajax时,得到错误“选择一个有效的选择.这不是可用的选择之一.“

前端之家收集整理的这篇文章主要介绍了jquery – 使用带有django形式的ajax时,得到错误“选择一个有效的选择.这不是可用的选择之一.“前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 django的新手.我正在使用简单的ajax在课程选择的基础上动态更新选择字段学期.但在提交表单时我收到错误选择一个有效的选择.选择的选项不是可用选项之一.代码如下:

forms.py:

  1. from django import forms
  2. from Feedback_form.models import course,section_info
  3.  
  4. class loginForm(forms.Form):
  5. iquery1 = course.objects.values_list('course_name',flat = True)
  6. iquery1_choices = [('','----------')] + [(id,id) for id in iquery1]
  7. sem_choices = [('','----------')]
  8.  
  9. course_name = forms.ChoiceField(iquery1_choices,required=True,widget=forms.Select())
  10. semester = forms.ChoiceField(sem_choices,required= True,widget=forms.Select())

views.py:

  1. def get_batch(request,c_id):
  2. current_course = Feedback_form.models.course.objects.get(course_name=c_id)
  3. batches = Feedback_form.models.batch.objects.all().filter(course_id=current_course)
  4. no_of_sem = Feedback_form.models.course.objects.values_list('number_of_sem',flat=True).filter(course_id = current_course)
  5. no_of_sem = int(no_of_sem[0])
  6. batch_dict = {}
  7. for batch in batches:
  8. batch_dict[batch.batch_id] = batch.batch_id
  9. sem = {}
  10. sem[no_of_sem] = no_of_sem
  11. data = [batch_dict,no_of_sem]
  12. return HttpResponse(json.dumps(data))

loginForm.html:

  1. <form action="" method="post">
  2. <table>
  3. {{ form.as_table }}
  4. </table>
  5. {% csrf_token%}
  6. <input type="submit" value="Submit">
  7. </form>
  8.  
  9. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  10. <script>
  11.  
  12. $(document).ready(function(){
  13. $('#id_course_name').change(function() {
  14. request_url = 'login/get_batch/' + c_id + '/';
  15. $.ajax({
  16. url: request_url,success: function(data){
  17. data = $.parseJSON(data);
  18. $('#id_semester').html('<option selected="' + "selected" + '">' + '' +'</option>');
  19. for(var i = 1; i<=data[1]; i++) //data[1] contains no of sem
  20. $('#id_semester').append('<option value="' + i + '">' + i +'</option>');
  21. },errors: function(e) {
  22. alert(e);
  23. }
  24. })
  25.  
  26. })

请帮帮我.

解决方法

问题是choiceField要求选择的选项在其选择集中.在上面的代码中,学期的选择是通过jquery动态更新的,但这不是学期选择集的一部分,即sem_choices.因此问题就出现了.要解决此问题,请在sem_choices中包含所选值.通过使用request.POST方法.

在views.py中:

  1. form = loginForm(request.POST)
  2. sem = request.POST.get('semester')
  3. form.fields['semester'].choices = [(sem,sem)]

猜你在找的jQuery相关文章