FormView CBV change ModelForm per request

自闭症网瘾萝莉.ら 提交于 2020-01-07 01:59:44

问题


I am trying to build a Wizard for populating data in to DataBase. I try the session.Wizard with out success plus I don't think this is what ti need. correct me if I am wrong.

so basically my database have some tables which needs to be fill, because of the joints need to be done, I wanted to make a nice wizard which takes you along the way.

so I have a base template which would have steps, sometimes there would be no need in creating a new data if exists all ready. so I have made a display of each table on template so user can check if the table contain what he needs for next step or he needs to create it.

I made a cbv FormView and I am trying to get the step from GET and load the needed ModelForm

model.py

Class A(models.Model):
    user = CharField()
class B(models.Model):
    pupy = CahrField()

form.py

AForm(forms.ModelForm):
    class Meta:
        model=A
        fields = ['user']

BForm(forms.ModelForm):
    class Meta:
        model=B
        fields = ['pupy']

views.py

class Wizard(FormView)
    template_name = 'test.html'
    def get(self, request, *args, **kwargs):
        self.step = self.request.GET.get('step')
        self.form_class = FORM[self.step] # FORM = dict {'step': ModelForm}
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.save()

I can't type here everything I have tried so far, basically I do get my form in to the html by clinking the links but I am having a truble saving them, I have manage to save the first form if I I do

def __init__
    self.step = 'first_step'

just as a test


回答1:


found an answer from another post that is working by combining 2 people answer Switch case for form_class and template_name

@Denny Crane

class Foo(FormView):
    def dispatch(self, request, *args, **kwargs):
        self.var = request.session['sessionvar']['var']
        if self.var == some_value:
            form_class = form1
            template_name = template1
        elif self.var == another_value:
            form_class = form2
            template_name = template2
        [...]
        return super(Foo, self).dispatch(request, *args, **kwargs)

@Serafeim

need to override get_form_class() as well

def get_form_class(self):
    self.form_class = FORM[self.step]
    return self.form_class


来源:https://stackoverflow.com/questions/40192863/formview-cbv-change-modelform-per-request

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