python - Create ModelForm dynamically -
i have equal modelforms , want make 1 general instead of them. please see below code samples
class createstudent(forms.modelform): class meta: model = student fields = [field.name field in model._meta.fields if not field.name == 'id'] class creategroup(forms.modelform): class meta: model = group fields = [field.name field in model._meta.fields if not field.name == 'id']
i want able this:
class createitem(forms.modelform): class meta: model = custom_model_name #here need pass model request somehow fields = [field.name field in model._meta.fields if not field.name == 'id']
i want have links /create/group
, /create/user
, want pass last part of url (group
or user
) form constructor , generate form basing on it.
you can't way. meta stuff evaluated @ define time, can't change depending on request @ runtime.
however since you've got limited number of models, , you're not customising forms themselves, why not define forms , use dictionary use right one?
def create(request, model_class): forms = { 'user': userform, 'group': groupform } form_class = forms[model_class] ...
Comments
Post a Comment