Salim Fadhley
Salim Fadhley

Reputation: 8195

Make many to many fields editable in both object's admin forms

I have a Django model with a many-to-many field relating it to another Django model object.

class B(models.Model):
    name = models.CharField(max_length=100)

class A(models.Model):
    name = models.CharField(max_length=100)
    models.ManyToManyField(B)

If I look on A's admin form I will see the name field and a many-to-many widget listing all the B's.

If I look at B's admin form I will see just the name widget.

Is there a way to allow both model's admin form to have a many-to-many widget. I'd like to add A's when I'm looking at B, and I'd like to add B's when I'm looking at A.

Can this be done?

Upvotes: 0

Views: 197

Answers (1)

Basavaraju US
Basavaraju US

Reputation: 134

You can do that by using MultipleChoiceField. Django model's ManyToManyField is represented as a MultipleChoiceField.

Check references.

  1. https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_many/
  2. https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types
  3. https://docs.djangoproject.com/en/dev/ref/forms/widgets/#setting-arguments-for-widgets

Note: While adding B in A's form, you should create B instance first and then you have to add A to B. else you will get error as B instance needs to have a primary key value before a many-to-many relationship can be used.

Upvotes: 1

Related Questions