简体   繁体   English

Django管理员操作来添加大量的tomtomany字段?

[英]Django admin action to add bulk manytomany fields?

I'm trying to add multiple items to a ManyToManyField on Django via actions. 我正在尝试通过操作将多个项目添加到Django上的ManyToManyField中。 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. 我想将所选项目重定向到/add_authors页面,在/add_authors面上我想要一个具有Djagno admin ManyToManyField选择器的模板。 How can I redirect to /add_authors with the queryset context? 如何使用queryset上下文重定向到/add_authors

How can I make it work? 我该如何运作?

Thanks. 谢谢。

Something like this will get you pk of all selected Books 这样的事情会让您获得所有选定Books pk

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: 您可以通过以下方式在add_authors视图中检索图书pk列表:

# 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: 查看formfield_for_manytomany ,了解如何在formfield_for_manytomany中自动填充M2M字段:

Docs: https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany 文件: https//docs.djangoproject.com/zh-CN/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM