Django - many for many fields as a drop-down list

I have many, many relationship models that actually appear as a multi-position list of forms. In one particular place, I want to show it as a single select dropdown - any idea how to do this?

+3
source share
1 answer

See the documentation for overriding default field or widget types .

If you have a model Bookwith relation ManyToManyto Author, for example:

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)

then you can do something like this:

from django.forms import ModelForm, Select

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        widgets = {
            'name': Select(),
        }

NB. This code has not been verified, but hopefully it will be enough so that you can be on your way.

+2
source

Source: https://habr.com/ru/post/1760045/


All Articles