Created
April 23, 2019 11:23
-
-
Save ekinertac/2af00d18f5346e769a9ceb5dddd2bb37 to your computer and use it in GitHub Desktop.
CssClassMixin for Django-Admin form elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PostAdmin(CssClassMixin, admin.ModelAdmin): | |
form_css_clasess = { | |
'title': 'col-sm-8', | |
'slug': 'col-sm-12' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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