Django admin change only classes in a fieldset

By , 09/08/2011 00:11

I’ve been playing around with Django lately and while I love the framework (and especially the admin interface) it does have some minor points. It might be because of my lack of understanding of the framework and/or Python but some stuff is hard to find. One problem I was faced with was that I wanted to use the .wide class that is provided by the admin to use in case the labels are to big and get overlapped by the form fields.

One way to tackle this problem would be to override the templates or define a CSS file to apply this CSS class (or it’s properties) to the fields. I however prefer to change as little as possible to the templates of the admin interface so that updates of the Django framework in the future require lesser effort.

The recommended way to apply the .wide class seems to be using the classes tuple in the fieldsets option of the ModelAdmin class. This requires however that you fill in the fields tuple also. Since I’ll probably forget manually updating this class everytime I update the model (and I’m lazy) I looked for a solution to fill in the fields tuple automatically.

This is what I came up with:

  1. from django.contrib import admin
  2. from django.forms.models import fields_for_model
  3.  
  4. from My.models import MyModel
  5.  
  6. class MyModelAdmin(admin.ModelAdmin):
  7.     fieldsets = (
  8.         (None, {
  9.             ‘fields’: fields_for_model(MyModel),
  10.             ‘classes’: (‘wide’,),
  11.         }),
  12.     )
  13.  
  14. admin.site.register(MyModel, MyModelAdmin)

Possible things to add if you are using different fieldsets would be some methods to automatically place remaining fieldsets in the None tuple, introduce a base class so that you can have defaults for all your admin classes, … One package that seems to be working in that direction is django-form-utils with the BetterForm class.

Flattr this!

Leave a Reply

*

Panorama Theme by Themocracy