micgeronimo
micgeronimo

Reputation: 2149

Create ModelForm dynamically

I have to equal modelForms and I want to make just one general instead of them. Please see below code samples

class CreateStudent(forms.ModelForm):
    class Meta:
        model = Student
        fields = [field.name for field in model._meta.fields if not field.name == 'id']


class CreateGroup(forms.ModelForm):
    class Meta:
        model = Group
        fields = [field.name for field in model._meta.fields if not field.name == 'id']

I want to be able to do something like this:

class CreateItem(forms.ModelForm):
    class Meta:
        model = custom_model_name #here I need to pass model from request somehow
        fields = [field.name for field in model._meta.fields if not field.name == 'id']

I want to have to links like /create/Group and /create/User and I want to pass last part of url (Group or User) to form constructor and generate form basing on it.

Upvotes: 0

Views: 132

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You can't do it this way. The meta stuff is evaluated at define time, so you can't change it depending on a request at runtime.

However since you've only got a limited number of models, and you're not customising the forms themselves, why not just define the forms and then use a dictionary to use the right one?

def create(request, model_class):
    forms = {
        'user': UserForm,
        'group': GroupForm
    }


    form_class = forms[model_class]
    ...

Upvotes: 2

Related Questions