liepumartins
liepumartins

Reputation: 494

Add multiple records at once in django admin panel

I have following setup.

from django.db import models
from django.contrib.auth.models import User

class Event(models.Model):
    name = models.CharField(max_length=64)
    date = models.DateField()

ATTENDANCE_CHOICES = (
    ('A','Attending'),
    ('N','Absent'),
    ('L','Taken ill'),
)

class Attendance(models.Model):
    student = models.ForeignKey(User)
    event = models.ForeignKey(Event)
    status = models.CharField(max_length=1, choices=ATTENDANCE_CHOICES)

In a nutshell: Students(User) attend or doesn't attend classes(Event), this is registered by Attendance. Problem is adding those attendance records one at a time.

What I am looking for is a way to provide form for each class(each Event object) with list of all students and attendance status radio buttons or drop downs next to them.

Something like this:

https://i.sstatic.net/J2G4d.png

I have looked at many discussions about multiple/bulk record insertion via django admin and am beginning to wonder is this even possible with django admin or do I have to create such form from scratch? Either way, what would be the best (most django-ish) approach?

Upvotes: 4

Views: 7944

Answers (1)

"Is this even possible?" It's possible right out of the box.

Look into the django Admin app, Inlines, ModelForms, and the RadioSelect widget.

class MyForm(forms.ModelForm):
    class Meta:
        model = Attendance

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs
        self.fields['status'].widget = forms.RadioSelect(choices=self.fields['status'].choices)

class AttendanceInline(admin.TabularInline):
    model = Attendance
    form = MyForm

class EventAdmin(admin.ModelAdmin):
     inlines = [AttendanceInline]

     def save_model(self, request, obj, form, change):
        obj.save()
        for user in User.objects.all():
            obj.attendance_set.create(user=user, status='')
             # you should consider a null field or a possible choice for "Undecided"

admin.site.register(Event, EventAdmin)

Upvotes: 5

Related Questions