2

I'm trying to add multiple items to a ManyToManyField on Django via actions. The models:

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    website = models.URLField()


class Author(models.Model):
    name = models.CharField(max_length=30)
    twitter = models.CharField(max_length=20)


class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

Admin panel

def add_authors(modeladmin, request, queryset):
    return HttpResponseRedirect('/add_authors')

@admin.register(Book)
class BookRegister(admin.ModelAdmin):
    actions = [add_authors]

I want to redirect the selected items to /add_authors page where I want to have a template that have the Djagno admin ManyToManyField selector. How can I redirect to /add_authors with the queryset context?

How can I make it work?

Thanks.

1 Answers1

0

Something like this will get you pk of all selected Books

import urllib

def add_authors(modeladmin, request, queryset):
    params = {
        'books': queryset.values_list('id', flat=True)
    }
    redirect_url = '/add_authors/?%s' % urllib.urlencode(params, doseq=True)
    return HttpResponseRedirect(redirect_url)

And you can retrieve the books pk list at the add_authors view by:

# http://.../?books=1&books=2&...
books = request.GET.getlist('books')

Have a look at formfield_for_manytomany for how to auto-populate M2M field in modeladmin:

Docs: https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany

mishbah
  • 5,487
  • 5
  • 25
  • 35