Skip to content

Instantly share code, notes, and snippets.

@ekinertac
Created April 23, 2019 11:23
Show Gist options
  • Save ekinertac/2af00d18f5346e769a9ceb5dddd2bb37 to your computer and use it in GitHub Desktop.
Save ekinertac/2af00d18f5346e769a9ceb5dddd2bb37 to your computer and use it in GitHub Desktop.
CssClassMixin for Django-Admin form elements
class PostAdmin(CssClassMixin, admin.ModelAdmin):
form_css_clasess = {
'title': 'col-sm-8',
'slug': 'col-sm-12'
}
from django import forms
class CssClassMixin(object):
def get_object_form(self, css_classes):
model_class = self.model
class _ObjectForm(forms.ModelForm):
class Meta:
model = model_class
fields = '__all__'
def __init__(self, *args, **kwargs):
super(_ObjectForm, self).__init__(*args, **kwargs)
for field in css_classes:
self.fields[field].widget.attrs['class'] = css_classes[field]
return _ObjectForm
def get_form(self, request, obj=None, **kwargs):
return self.get_object_form(self.form_css_clasess)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment