Session in Forms

Asked

Viewed 86 times

2

What I did

I have a view that calls a template with a form. In a given 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 it to the URL. This URL is pointing to MinhaSegundaView, calling a different form and template. I ran a test and displayed the session data in the template using the syntax session.order_id, and wanted to do the same in my form FormDois, because I use it to build inputs in the template. However, if I do initial the request, he says that this element does not exist. I believe because he does 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)

1 answer

2


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

The first thing to be done is a 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 visualize the implementation that is used for form_class, you will see that there is a guy named "get_initial", that is, he takes the initial information. With that you can override this guy:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.