如何以Django形式显示依赖下拉列表

时间:2019-04-27 08:10:44

标签: django

这是我处理学生费用管理的一些代码。此代码可以按我的意愿工作,但我唯一想更改的是通过模板提交学生费用表格时。如果用户选择了某些课程,则添加学生费用信息选择费用下拉菜单中只显示该选定课程的basic_price和advanced_price。我尝试了很多事情,但没有成功。我如何才能做到这一点?

  

models.py

class Course(models.Model):
    title = models.CharField(max_length=250)
    basic_price = models.IntegerField(default=0)
    advanced_price = models.IntegerField(default=0)
    basic_duration = models.CharField(max_length=50)
    advanced_duration = models.CharField(max_length=50)
    shift = models.CharField(max_length=1000)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

class StudentFee(models.Model):
    student = models.ForeignKey(Student,on_delete=CASCADE)
    course = models.ForeignKey(Course,on_delete=models.DO_NOTHING)
    total_fee = models.CharField(max_length=250)
    first_installment = models.IntegerField(default=0)
    date_first_installment = models.DateField(default=datetime.date.today)
    second_installment = models.IntegerField(default=0)
    date_second_installment = models.DateField(default=datetime.date.today)
    third_installment = models.IntegerField(default=0)
    date_third_installment = models.DateField(default=datetime.date.today)
    remaining = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.total_fee
  

views.py

 def ajax_course_fees(request):
    course = Course.objects.get(id=request.GET.get('course_id'))
    #generate an html template for the specific option
    return render(request, 'students/fees_dropdown_list_options.html', {'course': course})

def addstudentfee(request):

if not request.user.is_superuser:
    messages.warning(request, 'Permission Denied.You have no permission to perform this action.')
    return redirect('students:home')
students = Student.objects.all()
courses = Course.objects.all()
if request.method == "POST":
    form = StudentFeeForm(request.POST or None)
    total_fee = form.cleaned_data['total_fee']
    first_installment = form.cleaned_data['first_installment']
    second_installment = form.cleaned_data['second_installment']
    third_installment = form.cleaned_data['third_installment']
    remaining = int(total_fee) - int(int(first_installment)+int(second_installment)+int(third_installment))
    if form.is_valid():
        student = form.save(commit=False)
        student.remaining = int(remaining)
        student.save()
        messages.success(request,'data saved for student {}'.format(student.student))
        return redirect('students:student_fee')
    else:
        # messages.error(request,'error in form')
        return HttpResponse(form.errors)

else:
    form = StudentFeeForm()
return render(request,'students/student_fee.html',{'form':form,'students':students,'courses':courses})
  

urls.py

path('ajax/load-course-fees/', views.ajax_course_fees, name='ajax_load_course_fees'),
  

forms.py

class StudentFeeForm(forms.ModelForm):
            class Meta:
                model = StudentFee
                fields = ['student','course','total_fee','first_installment','second_installment','third_installment']
  

student_fee.html

     <div class="form-group">
                        <h5>Course <span class="text-danger">*</span></h5>
                        <div class="controls">
                    <select name="course" id="personForm" data-fees-url="{% url 'students:ajax_load_course_fees' %}" required class="form-control">
                    <option value="">Select Course</option>
                        {% for course in courses %}
                            <option value="{{course.id}}">{{course.title}}</option>
                        {% endfor %}
                </select>
                        </div>
                     </div>
                     <div class="form-group">
                        <h5>Total Fee <span class="text-danger">*</span></h5>
                        <div class="controls">
                <select name="total_fee" id="select3" required class="form-control">
                    <option value="">Select Fee</option>
                </select>
                        </div>
                     </div>


 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $("#personForm").change(function () {
      var url = $("#personForm").attr("data-fees-url");  // get the url of the ajax_load_course_fees view
      var course_id = $(this).val();  // get the selected course pk from the HTML input

      $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request
        data: {
          'course_id': course_id       // add the course pk to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `ajax_course_fees` view function
          $("#select3").html(data);  // replace the contents of the fees select with the data that came from the server
        }
      });

    });
  </script>
  

fees_dropdown_list_options.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select name="total_fee">
<option value="">Select Fee</option>
<option value="{{course.basic_price}}">{{course.basic_price}}(Basic)</option>
<option value="{{course.advanced_price}}">{{course.advanced_price}}(Advanced)</option>
</select>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要创建一个新函数,该函数将返回特定于课程的费用,但从ajax调用

def ajax_course_fees(request):
    course = Course.objects.get(pk=request.GET.get('course_pk'))
    #generate an html template for the specific option
    return render(request, 'fees_dropdown_list_options.html', {'course': course})

关联模板:

fees_dropdown_list_options.html

<option value="">Select Fee</option>
<option value="{{course.basic_price}}">{{course.basic_price}}(Basic)</option>
<option value="{{course.advanced_price}}">{{course.advanced_price}}(Advanced)</option>

在urls.py中添加以下内容:

 path('ajax/load-course-fees/', views.ajax_course_fees, name='ajax_load_course_fees'),

以下是您观点的一些改进:

def addstudentfee(request):
    if not request.user.is_superuser:
        messages.info(request, 'You have to logged in first as a admin')
        return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
    students = Student.objects.all()
    courses = Course.objects.all()
    form = StudentFeeFrom(request.POST or None)

    if form.is_valid():
        total_fee = form.cleaned_data['total_fee']
        first_installment = form.cleaned_data['first_installment']
        second_installment = form.cleaned_data['second_installment']
        third_installment = form.cleaned_data['third_installment']
        remaining = int(total_fee) - int(int(first_installment)+int(second_installment)+int(third_installment))

        student = form.save(commit=False)
        student.remaining = int(remaining)
        student.save()
        messages.success(request,'data saved for student {}'.format(student.student))
        return redirect('students:student_fee')

    else:
        # messages.error(request,'error in form')
        return HttpResponse(form.errors)

    return render(request,'students/student_fee.html',{'form':form,'students':students,'courses':courses})

默认情况下,您需要在模板中删除费用,这些费用将从ajax调用中为每个课程动态加载

我提供了Jquery来进行ajax调用。

<select name="course" id="select2" data-fees-url="{% url 'ajax_load_course_fees' %}" required class="form-control">
    <option value="">Select Course</option>
        {% for course in courses %}
            <option value="{{course.id}}">{{course.title}}</option>
        {% endfor %}
</select>
<select name="total_fee" id="select3" required class="form-control">
    <option value="">Select Fee</option>
</select>


 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $("#select2").change(function () {
      var url = $("#select2").attr("data-fees-url");  // get the url of the ajax_load_course_fees view
      var course_pk = $(this).val();  // get the selected course pk from the HTML input

      $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request
        data: {
          'course_pk': course_pk       // add the course pk to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `ajax_course_fees` view function
          $("#select3").html(data);  // replace the contents of the fees select with the data that came from the server
        }
      });

    });
  </script>

为您提供信息:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html