Passing initial data from a database to Django Form Wizard template

1.1k views Asked by At

This is the first time I have to use the Django Wizard Form and I'm having more problems than expected (I'm a newbie). I'm trying to pass some initial data from a database to a Form Wizard template. I have been googling but I have found no answer.

I think that I must override the get_context_data method to query my database and build and return a dictionary, but I'm not really sure about that. Could someone explain me the correct process?

I put my code below to show you my idea.

def my_function(request):
    form = MyWizard.as_view([Form1, Form2, Form3])
    return form(context=RequestContext(request), request=request)

TEMPLATES = {'0': "form1.html",
             '1': "form2.html",
             '2': "form3.html",}

class MyWizard(SessionWizardView):

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def get_context_data(self, form, **kwargs):
        if self.steps.current == 0:

            list = MyModel.objects.all()   # query my database

            # convert list to dict

            return context   # return context with the dict

    def done(self, form_list, **kwargs):
        form_data = process_form_data(self.request, form_list)

        return render_to_response('process-completed.html', {'form_data': form_data,})

Thank you.

2

There are 2 answers

0
niekas On BEST ANSWER

This example specifies how to pass initial data to the wizard.

In your case you need more complex processing, so you should override get_form_initial() method, e.g.:

def get_form_initial(self, step):
    initial = {}
    if step == 1:
        client_pk = self.kwargs.get('client_pk')
        initial.update({
            'client': Client.objects.get(pk=client_pk)
        })
    return self.initial_dict.get(step, initial)
0
pypy On

Thank you very much!! I write my code below to show how I solved my problem based on your code.

def get_form_initial(self, step):
    initial = {}
    if step == '0':
        t = MyModel.objects.all() # Get the list of objects of my database
        initial = {x.id: x.name for x in t} # Convert this list to python dictionary
    return self.initial_dict.get(step, initial)

Hope this is useful.