Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-admin - how to modify ModelAdmin to create multiple objects at once?

let's assume that I have very basic model

class Message(models.Model):
      msg = models.CharField(max_length=30)

this model is registered with admin module:

class MessageAdmin(admin.ModelAdmin):
    pass
admin.site.register(Message, MessageAdmin)

Currently when I go into the admin interface, after clicking "Add message" I have only one form where I can enter the msg.

I would like to have multiple forms (formset perhaps) on the "Add page" so I can create multiple messages at once. It's really annoying having to click "Save and add another" every single time.

Ideally I would like to achieve something like InlineModelAdmin but it turns out that you can use it only for the models that are related to the object which is edited.

What would you recommend to use to resolve this problem?

like image 931
skrobul Avatar asked Jun 07 '10 22:06

skrobul


People also ask

How do I make multiple objects in Django?

To create multiple records based on a Django model you can use the built-in bulk_create() method. The advantage of the bulk_create() method is that it creates all entries in a single query, so it's very efficient if you have a list of a dozen or a hundred entries you wish to create.

How to edit multiple models from one Django admin?

To be able to edit multiple objects from one Django admin, you need to use inlines. You can see the form to add and edit Villain inside the Category admin. If the Inline model has alot of fields, use StackedInline else use TabularInline .

Is Django's admin interface customizable if yes then how?

To implement it in your project, make a new app in your Django project named products. Install this application, type product in the INSTALLED_APPS list in settings.py file. We will now make models in the products app. The model will be used throughout the tutorial to customize the Django Admin.


1 Answers

This may not be exactly what you are looking for, but if you want to create multiple objects at the same time you could to somehthing like this:

#In /forms.py
MessageAdminForm(forms.ModelForm):
    msg = CharField(max_length=30)
    count = IntegerField()

#In /admin.py
from app.admin import MessageAdminForm
MessageAdmin(admin.ModelAdmin):
    form = MessageAdminForm
    fieldsets = (
        (None, {
            'fields' : ('msg','count')    
         }),)
    def save_model(self, request, obj, form, change):
        obj.msg = form.cleaned_data['msg']
        obj.save()
        for messages in range(form.cleaned_data['count']):
            message = Message(msg=form.cleaned_data['msg'])
            message.save()

Basicly what you are doing is creating a custom form for your admin template, which ask the user how many times the object shall be created. The logic is than interpreted in the save_model method.

like image 129
hermansc Avatar answered Sep 21 '22 23:09

hermansc