Last active
May 9, 2019 23:13
-
-
Save glassresistor/af11c23c58081fabc5d4647b3ccb29ba 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
def get_form_from_model_name(full_model_name): | |
app_label, model_name = full_model_name.split(".") | |
form_model = apps.get_model(app_label, model_name) | |
fields = form_model._meta.fields | |
name_fields = [] | |
for field in fields: | |
if field.related_model and (issubclass( | |
field.related_model, | |
bi_models.NamedBulkable) or issubclass( | |
field.related_model, | |
bi_models.NamedBulkableImmutable)): | |
name_fields.append(field) | |
exclude_fields = ["imported_from", "created_at", "updated_at"] | |
class CustomModelForm(forms.ModelForm): | |
def __init__(self, *args, **kwargs): | |
super(CustomModelForm, self).__init__(*args, **kwargs) | |
for name_field in name_fields: | |
self.fields['%s_name' % name_field.name] = forms.CharField( | |
required=not name_field.blank) | |
self.fields[name_field.name].required = False | |
def make_clean(self): | |
name_column = '%s_name' % name_field.name | |
data = self.cleaned_data[name_column] | |
objs = name_field.related_model.objects.filter( | |
name=data) | |
if len(objs) == 0: | |
raise forms.ValidationError( | |
"named fk does not exist!") | |
obj = objs[0] | |
data[name_field.name] = obj | |
return data | |
setattr(self, "clean_%s" % name_field.name, MethodType(make_clean, self)) | |
class Meta: | |
model = form_model | |
exclude = exclude_fields | |
return CustomModelForm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment