Use ModelAdmin form in any view

I've spent quite a bit of time setting it up ModelAdmin

for my models and I want it to be able to basically reuse it elsewhere on my site, i.e. not just the admin pages.

Specifically, I want to further subclass the subclass ModelAdmin

I created and override some of the methods and attributes that are not additive, and then use that second subclass to create a form from a model in one of my regular (non-admin) ones. But I'm not sure how to get the form from the subclass ModelAdmin

or how to bind it to a specific model.

So, for example, mine

looks something like this:

from django.contrib import admin

class MyAdmin(admin.ModelAdmin):
    fields = ['my_custom_field']
    readonly_fields = ['my_custom_field']

    def my_custom_field(self, instance):
        return "This is my admin page."


And it works really well. Now I want to subclass this as:

class MyNonAdmin(MyAdmin):
    def my_custom_field(self, instance):
        return "This is NOT my admin page!"


Now I want to use MyNonAdmin

in a view function to create a form bound to a specific model and use that form in the template. I just don't know how to do it.


I found a way to render the form, but it doesn't include it readonly_fields

. The form design looks like this:

def view_func(request, id):j
    res = get_object_or_404(ModelClass, pk=int(id))
    admin = MyNonAdmin(ModelClass, None)
    form = admin.get_form(request, res)

    return render(request, 'my_template.html', dict(


But as I said, it only displays the form and not another readonly_fields

one that I really care about.


source to share

All Articles