0

So I have a ManyToMany field in my model and Django admin renders it as a multiselect field. It works fine and I have no issues — except that I can't Edit it after creating a record. I tried Del key, mouse right-click, nothing worked. Looks like I have to delete the record and create it again?

enter image description here

This is the field I want to edit. I want to remove one or two of the above items. I'm on Windows.

Omid Shojaee
  • 333
  • 1
  • 4
  • 20

1 Answers1

0

Well it looks like there's a simpler solution:

(Courtesy of Webdev Hints)

Here's my models:

class Technology(models.Model):
    title = models.CharField(max_length=10)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Technologies'


class Project(models.Model):
    title = models.CharField(max_length=100)
    description = HTMLField()
    technology = models.ManyToManyField(Technology, related_name='projects')
    image = models.ImageField(upload_to='projects/')

    def __str__(self):
        return self.title

And the solution is to add the following to the admin.py:

@admin.register(Technology)
class TechnologyAdmin(admin.ModelAdmin):
    pass


class TechnologyInline(admin.TabularInline):
    model = Project.technology.through


@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
    inlines = (TechnologyInline,)
    exclude = ('technology',)

Now the ManyToMany filed is editable.

Omid Shojaee
  • 333
  • 1
  • 4
  • 20