开发者

Django - Different forms for model

Depending on my models state, I want to show a different form to the user. I'm trying to figure out how I'd store a reference to the correct form so I can load it in my view.

An normal view would look like:

from myapp.forms import SomeForm

def view():
form = SomeForm()

However, since I don't know which form my model needs, how would I dynamically import the form class?

I tried this:

from django.forms import ModelForm
modelforms = ModelForm.__subclasses__()

def get_modelform(model):
    return filter开发者_开发问答(lambda x:x.Meta.model == model, modelforms)[0]

But it only works if the form has been imported into the project. Since my form lives in it's own forms.py file, this doesn't work :(


In your forms.py file, write a function that returns the correct form according to your criteria. Then import that into your view and call it there.


Write a function that returns needed form class according to the condition.


You have to use modelform fabric, it could help you to make forms for your models

FormClass = modelform_factory(ModelClass)

https://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L370

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜