Home > Enterprise >  How to create custom button in Django admin, which create many object?
How to create custom button in Django admin, which create many object?

Time:02-01

I have a model Student:

from django.db import models
from django.contrib import admin


class Student(models.Model):
    name = models.CharField(max_length=30, default='')
    lastname = models.CharField(max_length=30, default='')
    grade= models.CharField(max_length=8, default='')

class StudentAdmin(admin.ModelAdmin):
    list_display= ('name','lastname','grade')

from django.contrib import admin
from .models import *

admin.site.register(Student, StudentAdmin)

Imagine, that I have an additional model Person ( with name and surname fields). My situation is just an example. I want to create a button in the Django admin (it's very important to implement this in Django admin page), that creates many Student objects at once (name and lastname we take from Person, with empty grade field, which we can fill in the future).

CodePudding user response:

You can use Admin Actions to do this:

First you define a create_student function that performs the insert activity. This will be linked to a Person Admin, since the action is performed from Persons. For example:

@admin.action(description='Create students from selected persons')
def create_student(modeladmin, request, queryset):
    for person in queryset:
        s = Student(name = person.name, lastname=person.lastname)
        s.save()

so you can add the action to a PersonAdmin

class PersonAdmin(admin.ModelAdmin):
    actions = [create_student]

admin.site.register(Person, PersonAdmin)
  •  Tags:  
  • Related