Skip to main content
 首页 » 编程设计

python之Django:如何动态过滤下拉框

2025年05月04日7pengyingh

例如,我有三个模型。 内容、章节和页面。在 Content 表单中将有两个下拉框。一个用于章节,另一个用于页面。如果我要从下拉框中选择一个 chapter,我该如何过滤 page 下拉框只显示 pages 章节。

模型.py

class Page(Models.Model): 
    # Some details about the page 
 
class Chapter(models.Model): 
    # Some detail about the chapter 
 
class Content(models.Model): 
    chapter = models.ForeignKey(Chapter) 
    page = models.ForeignKey(Chapter) 

View .py

def create_contents(request): 
    if request.POST: 
        form = ContentForm(request.POST, request.FILES) 
        if form.is_valid(): 
            form.save() 
 
            return HttpResponseRedirect('/books/all/') 
    else: 
        form = ContenttForm() 
 
    args = {} 
    args.update(csrf(request)) 
 
    args['form'] = form 
 
    return render_to_response('content/content.html', args) 

表单.py

class ContentForm(forms.ModelForm): 
 
    class Meta: 
        model = Content 

请您参考如下方法:

我建议你两个选择:

  1. 使用django-autocomplete-light
  2. 像this一样使用jquery