user1785295
user1785295

Reputation: 53

Django - filter form field queryset based on another field

I have three models: Book, Languages and Options. There are predefined sets of books (Master and Margarita, The Name of the Rose etc.) and languages (English, German, French and so on). Each Book instance has a predefined subset of Languages in which is available (ManyToMany relationship). Options model contains Book field (as a ForeignKey) and Languages field (ManyToMany). I want to build a form that allows user to select any book and (after selection) dynamically filter languages queryset to show only subset related to this book. Is that possible with Django?

Relevant models:

class Book (models.Model):
    title = models.CharField (max_length = 128)
    languages = models.ManyToManyField (Language, related_name = 'available_languages')

class Language (models.Model):
    name = models.CharField (max_length=64)
    abbreviation = models.CharField (max_length=4)

class Options (models.Model):
    book = models.ForeignKey (Book, help_text = 'Text', null = True, blank = True)
    languages = models.ManyToManyField (Language, related_name = 'languages', help_text = 'Languages')

Upvotes: 0

Views: 2613

Answers (2)

Rodrigo López
Rodrigo López

Reputation: 227

You can make it via AJAX. When the user selects a book you call the url of your view in Django.

The view will make a form with id of the book the user selected, then it will return only the html for the form you want. Then, in the ajax success you put the html form where you want it.

Upvotes: 0

Mounir
Mounir

Reputation: 11726

You can do this with many ways, one of the easiest one is using django-smart-selects app, which integrate very well specially if you're using django admin. All you have to do is to install the app and update your model:

from smart_selects.db_fields import ChainedManyToManyField


class Options (models.Model):
    book = models.ForeignKey(Book, help_text='Text', null=True, blank=True)
    languages = ChainedManyToManyField(Language, related_name='languages', help_text='Languages'
                                       chained_field="book",
                                       chained_model_field="languages")

Upvotes: 1

Related Questions