问题
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