Search code examples
pythondjangodjango-admin-actions

Django Admin Actions: Add "Students" to "Academic Class"


Django 1.7, Python 3.0, Postgresql

Thanks for taking time to read this, I expect I am missing something obvious here.

For simplicity, let's say that my models are:

  • Student
  • AcademicClass

I am wanting to use Admin Actions to:

1st: Select Students
2nd: Create new yet-to-have-details-filled-in AcademicClass with the previously attached Students attached

Adding actions = [make_new_academic_class] and linking to that page has been fairly straight-forward, but I am completely confused as to how to attach the queryset on to that new AcademicClass.

    students = ManyToManyField('mgmt.Student', related_name='classes')

I believe I have everything correct, except this part:

def make_new_academic_class(modeladmin, request, queryset):
for stdnt in queryset:
    print(stdnt.id)  #obviously want to save this somehow
                     #then want to insert it in the AcademicClass-Student relationship
return redirect("/school/class/add")

UPDATE

Was told that the best way to do this would be to "pre-populate the form" using the Django API. Working on that.


Solution

  • Ok, so I figured this out:

    def make_class(modeladmin, request, queryset):
        new_class = Class()
        new_class.save()
        for student in queryset:
            new_class.students.add(student.id)
        return redirect(reverse('admin:mgmt_class_change', args=(new_class.id,)))
    

    I took a couple approaches on this, and this is the one that worked. Hopefully helpful to someone (or myself) in the future.