[Answered ]-How to add additional choices to forms which is taken from a model in django

1👍

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.

Leave a comment