Eyal
Eyal

Reputation: 1709

Django Static Inlines

I have a model Student with lots of fields and a model Document with a ForeignKey to Student. I'm using an inline to edit Students' associated Documents.

models.py:

class Document(models.Model):

    def media_path(instance, filename):
        return '{0}/{1}'.format(instance.Student.Id, filename)

    File = models.FileField(
        _('File'),
        upload_to=media_path,)

    Title = models.CharField(
        _('File Name'),
        max_length=32,
        blank=True,)

    Student = models.ForeignKey(
        Student,
        null=True,
        on_delete=models.SET_NULL)

    class Meta:
        verbose_name = _('Document')
        verbose_name_plural = _('Documents')

admin.py:

class DocumentInline(admin.TabularInline):
    model = Document
    extra = 0


class StudentAdmin(UserAdmin):
    ...
    inlines = [
        DocumentInline,
    ]

    class Meta:
        model = Student


admin.site.register(Student, StudentAdmin)

What I want is to add 3 inline Document lines with specific Title each time a Student is created, so for example:

I just created a Student and I already have 3 lines in the Document inlines section and each one with a pre-defined Title (and the File obviously is empty):

How can I do such thing?

Thanks in advance.

Upvotes: 1

Views: 132

Answers (1)

tdsymonds
tdsymonds

Reputation: 1709

You could add a receiver to intercept the post save signal:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Student)
def create_default_docs(sender, instance, created, **kwargs):
    if created:
        for title in ['title1','title2','title3']:
            d = Document(title=title, student=instance)
            d.save()

This code gets executed after the student model has been saved. If the model has just been created, it will then create the three documents with the default titles specified.

One thing to note, you'd need to allow your file field to allow nulls, as at the moment it's a required field.

Upvotes: 2

Related Questions