3

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).

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.