How to add additional choices to forms which is taken from a model in django

Question:

As in the topic is it possible to add choices to the forms that take from the model.

forms.py

class BookGenreForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ('genre',)

models.py

class Book(Product):
    GENRE_CHOICES = (
        ('Fantasy', 'Fantasy'),
        ('Sci-Fi', 'Sci-Fi'),
        ('Romance', 'Romance'),
        ('Historical Novel', 'Historical Novel'),
        ('Horror', 'Horror'),
        ('Criminal', 'Criminal'),
        ('Biography', 'Biography'),
    )
    author = models.CharField(max_length=100)
    isbn = models.CharField(max_length=100)
    genre = models.CharField(max_length=100, choices=GENRE_CHOICES)

I care about adding add-ons for selection, such as alphabetically, by popularity. I can handle the creation of a view. At the same time, I would not like to just add these options in the choices model unless it is possible that later in the panel the user does not have the option to add as a genre of popularity, etc.

I have an idea to make individual forms.Forms for everyone and re-create elections in them but I don’t think it would be a pretty way to do it

Asked By: Tylzan

||

Answers:

You can create a custom form field that adds additional choices to the existing ones, like so:

class GenreChoiceField(forms.ChoiceField):
    def __init__(self, choices=(), *args, **kwargs):
        super().__init__(choices=choices, *args, **kwargs)
        self.choices += [('popularity', 'By popularity'), ('alphabetical', 'Alphabetically')]

class BookGenreForm(forms.ModelForm):
    genre = GenreChoiceField(choices=Book.GENRE_CHOICES)
    class Meta:
        model = Book
        fields = ('genre',)

In the above example, GenreChoiceField is defined that inherits from ModelChoiceField which adds two extra choices to the existing Book.GENRE_CHOICES. The BookGenreForm then uses this custom field instead of the default CharField for the genre field.

For more information, refer Creating Custom Fields from docs.

Answered By: Sunderam Dubey