Created
March 4, 2011 00:51
-
-
Save SmileyChris/853944 to your computer and use it in GitHub Desktop.
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.utils.datastructures import SortedDict | |
from django.db.models.fields import AutoField | |
class EasyFieldsets(object): | |
""" | |
A mixin for use with ``ModelAdmin`` and related inline classes allowing | |
fieldsets to be used without having to manually define all fields | |
(undefined ones are placed at the end of the ``None`` fieldset). | |
""" | |
def __init__(self, *args, **kwargs): | |
super(EasyFieldsets, self).__init__(*args, **kwargs) | |
fieldsets = SortedDict(self.fieldsets) | |
# Get the currently named fields from the fieldsets. | |
named_fields = [] | |
for fieldset in fieldsets.values(): | |
for field in fieldset['fields']: | |
if isinstance(field, basestring): | |
named_fields.append(field) | |
else: | |
# Fields can be grouped. | |
named_fields.extend(field) | |
# Add any missing fields into the main fieldset. | |
fields = self.model._meta.fields + self.model._meta.many_to_many | |
missing_fields = [f.name for f in fields | |
if f.editable and not isinstance(f, AutoField) | |
and f.name not in named_fields] | |
if missing_fields: | |
if None not in fieldsets: | |
fieldsets[None] = {} | |
# Push the missing base fieldset to the top of the fieldset | |
# order. | |
fieldsets.keyOrder.remove(None) | |
fieldsets.keyOrder.insert(0, None) | |
fields = tuple(missing_fields) | |
base_fieldset = fieldsets.get(None) | |
base_fieldset['fields'] = (tuple(base_fieldset.get('fields', [])) | |
+ tuple(missing_fields)) | |
self.fieldsets = fieldsets.items() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment