Make fixing ModelForms easier
esitarski opened this issue · comments
It's not DRY to have to explicitly handle ForeignKeys and ManyToMany in ModelForms with SafeModelChoiceField and SafeModelManyToManyField:
class PostMethodForm(ModelForm):
class Meta:
model = Comment
field_classes = {
'post': SafeModelChoiceField,
}
This is especially painful when you have lots of embedded ForeignKeys and ManyToMany fields. A somewhat DRYer solution is below:
class PostMethodForm(ModelForm):
class Meta:
model = Comment
field_classes = update_safe_field_classes( model )
The function that does this is below. It allows for merging with an existing field_classes dict. It seems that an even more automatic solution is possible.
Can anyone see a problem with this approach?
from django_scopes.forms import SafeModelChoiceField, SafeModelMultipleChoiceField
from django.db.models.fields.related import ManyToManyField, ForeignKey, OneToOneField
def update_safe_field_classes( model_class, existing_field_classes = None ):
fields = {}
for f in model_class._meta.get_fields():
if isinstance( f, ForeignKey ):
fields[f.name] = SafeModelChoiceField
elif isinstance( f, ManyToManyField ):
fields[f.name] = SafeModelMultipleChoiceField
elif isinstance( f, OneToOneField ):
fields[f.name] = SafeModelChoiceField
if existing_field_classes:
fields.update( existing_field_classes )
return fields
On first sight, I don't see an immediate problem here, could be a very useful utility
Seems like something that would be useful as a decorator, because we already know that we want to use it on field_classes
.