Django过滤器下拉列表基于另一个下拉列表

时间:2019-06-06 00:29:18

标签: django

我正在尝试根据按下的程序来过滤子程序下拉列表。当前,我正在使用一对多关系将许多子程序保存在程序节点下。我以为这可以处理事情,但是无论选择哪个程序,它都只是返回所有子程序。

views.py

class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = fields = ['asset_name', 'road_name', 'suburb', 'lifecycle', 'program', 'subprogram', 'internal_budget', 'external_budget', 'budget_year', 'finance_description', 'project_description', 'reference_description', 'attachment']

def form_valid(self, form):
    form.instance.author = self.request.user
    return super().form_valid(form)

models.py

class Program (models.Model):
program_name = models.CharField(max_length=50, unique=True)  

def __str__(self):
    return self.program_name  

def get_absolute_url(self):
    return reverse('program-create')  


 class SubProgram (models.Model):
# program = models.OneToOneField(Program, on_delete=models.CASCADE, primary_key=True)
program = models.ForeignKey(Program, on_delete=models.CASCADE)
subprogram_name = models.CharField(max_length=50, unique=True)

def __str__(self):
    return self.subprogram_name  

def get_absolute_url(self):
    return reverse('subprogram-create')  

class Post (models.Model):
asset_name = models.CharField(max_length=150)
road_name = models.CharField(max_length=150)
suburb = models.CharField(max_length=150)
lifecycle = models.CharField(max_length=20, choices=CYCLE_CHOICES)
program = models.ForeignKey(Program, on_delete=models.CASCADE)
subprogram = models.CharField(max_length=20, choices=SUBPROGRAM_CHOICES)
internal_budget = models.IntegerField(blank=True)
external_budget = models.IntegerField(blank=True)
budget_year = models.CharField(max_length=20, choices=BUDGET_YEAR_CHOICES)
budget = models.IntegerField(blank=True)
finance_description = models.TextField()
project_description = models.TextField()
reference_description = models.CharField(max_length=150)
attachment = models.FileField(blank=True)
date_posted = models.DateTimeField(default=timezone.now())
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return self.asset_name

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk': self.pk})

def save(self, *args, **kwargs):
    if not self.budget:
        self.budget = self.internal_budget + self.external_budget
    return super(Post, self).save(*args, **kwargs)   

1 个答案:

答案 0 :(得分:0)

您可以这样做

  

urls.py

path('load/sub-program/',views.load_subprogram,name='load_subprogram')
  

views.py

def load_subprogram(request):
    program = Program.objects.get(id=request.GET.get('program_id'))
    return render(request, 'sub_program_dropdown_list.html', {'program': program})
  

sub_program_dropdown_list.html

   <select>
        <option value="">Select Sub Program</option>
        <option value="{{program.id}}">{{program.subprogram_name}}</option>
 </select>
  

add_subprogram.html

programs = Program.objects.all() #do this in views.py while rendering this add_subprogram.html
<select name="program" id="select" data-program-url="{% url 'load_subprogram' %}">

 <option value="">Select Program</option>
 {% for program in programs %}
<option value="{{program.id}}">{{program.program_name}}</option>
{% endfor %}
  </select>
<select name="subprogram_name" id="select1">

 <option value="">Select SubProgram</option>

</select>
  

ajax

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
                     <script>
    $("#select").change(function () {
      var url = $("#select").attr("data-program-url");  // get the url of the load_program view
      var program_id = $(this).val();  // get the selected program id 
      $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request
        data: {
          'program_id': program_id       // add the program id to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `load_subprogram` view function
          $("#select1").html(data);  // replace the contents of the subprogram select with the data that came from the server
        }
      });

    });
  </script>