Forms Session

2

What I did

I have a view that calls a template with a form. In a certain case, I need to save some data in the session scope and send it to another url - which will call another view and another template.

My Problem

I created the session and redirected to the URL. This URL is pointing to MinhaSegundaView , which calls a different form and template. I did a test and displayed the session data in the template using the session.order_id syntax, and I wanted to do the same in my form FormDois , as I use it to construct the inputs in the template. However, if I put initial request , it says that this element does not exist. I believe I did not have access to the request object.

What can I do?

My Code

Views.py

class MinhaView()
    template_name = 'arquivo.html'
    form_class = FormUm

    def post()
        request.session['order_id'] = order_id
        HttpResponseRedirect(reverse('url_email'))

class MinhaSegundaView()
    template_name = 'arquivodois.html'
    form_class = FormDois

class FormDois(forms.Form):
    order_id = forms.CharField(label=u'Pedido', initial=request.session['order_id'], required=True)
    
asked by anonymous 11.12.2015 / 14:02

1 answer

2

This problem is happening because your form does not have 'request'. Your request happens in the view, when you call a form, there is no sending of the request or any parameter to it.

The first thing to do is init for your form:

class FormDois(forms.Form):
        order_id = forms.CharField(label=u'Pedido', required=True)

    def __init__(self, *args, **kwargs):
        super(FormDois, self).__init__(*args, **kwargs)
        self.fields['order_id'].initial = kwargs['initial']['order_id']

And to use class based view, it's important that you know how things are implemented. If you open the django code and see the implementation that is used for the form_class, you will see that there is a face called "get_initial", that is, it picks up the initial information. With this you can override this face:

class MinhaSegundaView(View):
    template_name = 'arquivosdois.html'
    form_class = FormDois

    def get_initial(self):
        return { 'order_id': self.request.session['order_id'], }
    
13.12.2015 / 18:39