2

I was wondering if it's possible to add a css class to the Django admin form?

For example:

@admin.register(SomeFunction)
class SomeFunctionAdmin(SortableAdmin):
    fieldsets = (
        (None, {
            'fields': ('item1', 'item2', 'item3'),
        }),
    )

    def get_form(self, request, obj=None, **kwargs):
        form = super(SomeFunctionAdmin, self).get_form(request, obj, **kwargs)
        return form

    class Media:
        js = (
            'custom.js',
        )

Now I want to add a css class to SomeFunctionAdmin, let's say I want to add .custom-form-admin class. And in my custom.js file I have some functions which search for this custom css class.

How do I add the custom css class programatically to SomeFunctionAdmin?

I imagne the code would look something like this:

@admin.register(SomeFunction)
class SomeFunctionAdmin(SortableAdmin):
    fieldsets = (
        (None, {
            'fields': ('item1', 'item2', 'item3'),
        }),
    )

    def get_form(self, request, obj=None, **kwargs):
        form = super(SomeFunctionAdmin, self).get_form(request, obj, **kwargs)
        form.set_css += 'custom-form-admin'
        return form

    class Media:
        js = (
            'custom.js',
        )

1 Answer 1

1

You can override render_change_form() and modify the content:

from django.http import HttpResponse


@admin.register(SomeFunction)
class SomeFunctionAdmin(SortableAdmin):
    fieldsets = (
        (None, {
            'fields': ('item1', 'item2', 'item3'),
        }),
    )

    def render_change_form(self, *args, **kwargs):
        content = super(SomeFunctionAdmin, self).render_change_form(*args, **kwargs).render().content
        return HttpResponse(content.replace('<form', '<form class="custom-form-admin"'))

    class Media:
        js = (
            'custom.js',
        )
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. I keep getting this error Exception Value: super(type, obj): obj must be an instance or subtype of type
Fixed the above, now it seems like I need to return the following: Exception Value: expected bytes, bytearray or buffer compatible object on the return HttpResponse(content.replace('<form', '<form class="custom-form-admin"'))
return HttpResponse(content.replace(b'<form', b'<form class="custom-form-admin"')) if you are using Python 3
Thank you. Although I am not so fond of replacing the form, it works. I hoped there would be some method to add custom css class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.