Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How do I dynamically filter a dropdown box?

Tags:

python

django

Say for example I have a three models. Content, Chapter and Page. Within the Content form there will be two dropdown boxes. One for chapters and the other for pages. If I was to select a chapter from the dropdown box, how do I then filter the page dropdown box only to show the pages within that chapter.

models.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)

views.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)

forms.py

class ContentForm(forms.ModelForm):

    class Meta:
        model = Content
like image 816
Chris Meek Avatar asked Aug 06 '26 18:08

Chris Meek


1 Answers

I suggest you two option:

  1. using django-autocomplete-light
  2. using jquery like this
like image 159
Hasan Ramezani Avatar answered Aug 08 '26 11:08

Hasan Ramezani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!