Django: Creating an Inline Formset Similar to the Admin Interface

Viewed 8463

I'm a Django newbie, and I have a question about reusing the inline formset of the admin interface in the production code. Consider the following model:

class Attribute(models.Model):
    name       = models.CharField(max_length=50)

class Person(models.Model):
    lastName   = models.CharField(max_length=50)
    firstName  = models.CharField(max_length=50)
    email      = models.CharField(max_length=50)
    attributes = models.ManyToManyField(Attribute, through='AttributeValue')

class AttributeValue(models.Model):
    person     = models.ForeignKey(Person, on_delete=models.CASCADE)
    attribute  = models.ForeignKey(Attribute, on_delete=models.PROTECT)
    isConsumer = models.BooleanField()
    value      = models.CharField(max_length=50)

The admin interface for this comes out beautifully. I used the following admin.py:

class AttributeValueInline(admin.TabularInline):
    model = AttributeValue
    extra = 3

class PersonAdmin(admin.ModelAdmin):
    list_display = ('lastName', 'firstName','email')
    fieldsets = [
       ('Name',        {'fields': ['firstName', 'lastName']}),
       ('Contact Info',{'fields': ['email','phoneNumber']})
    ]
    inlines = [AttributeValueInline]

admin.site.register(Person, PersonAdmin)
admin.site.register(Attribute)

This is almost exactly what I want. It looks like this: enter image description here

When I tried to implement the same in the non-admin website, I had to write quite a bit of code to do the inline formsets, form processing, in addition to the actual business logic. In addition to this, I faced the problem mentioned here.

I can't expose the admin interface to the end-user because we need to have a customized web design, and page flow. But, can I reuse parts of the admin interface code instead of re-implementing the same functionality?

Any other suggestions to reduce the code would be most welcome.

1 Answers
Related