Updateview with dynamic form_class

你离开我真会死。 提交于 2021-02-07 20:40:51

问题


I would like to dynamically change the form_class of an UpdateView CBV in Django 1.6.

I've tried to do this using the get_context_data(), but that didn't help since the form is already initialized. So it will need to happen during __init__, I guess. Here's what I've tried on __init__:

class UpdatePersonView(generic.UpdateView):

    model = Person
    form_class = ""

    def __init__(self, *args, **kwargs):
        super(UpdatePersonView, self).__init__(*args, **kwargs)
        person = Person.objects.get(id=self.get_object().id)
        if not person.somefield:
            self.form_class = OneFormClass
        elif person.somefield:
            self.form_class = SomeOtherFormClass

I'm stuck with a 'UpdatePersonView' object has no attribute 'kwargs' error message when executing person = Person.objects.get(id=self.get_object().id).

When manually specifying the id (e.g. id=9), then the setup works.

How can I get the args/kwargs inside the init method that I'm overriding? Particularly I would need access to the pk.


回答1:


You should simply override get_form_class.

(Also I'm not sure why you're querying for person: that object is the same is self.get_object() already, so there's no point getting the ID of that then querying again.)

def get_form_class(self):
    if self.object.somefield:
        return OneFormClass
    else:
        return SomeOtherFormClass


来源:https://stackoverflow.com/questions/22965341/updateview-with-dynamic-form-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!