Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Save and restore a form's state using a cookie

I want to make a form that once submitted, on each next rendering of the form for the same user, the form will be already filled out with the data from the last time the user submitted it. sounds like something that django should have shortcut for - does it have it? if not what would be the easiest way to do it?

The best I could come up with is pickeling cleaned_data and saving it as a cookie, recreating the form from it later.

like image 319
olamundo Avatar asked Feb 11 '11 13:02

olamundo


2 Answers

This already sounds like a good plan. But if there is no pressure on using cookies, I would resort to using the session instead. That way you won't hit a size limit on cookies, and transmitting cookies with higher size can slow down your response time.

form = MyForm(initial=request.session.get('form_data'))
...
if form.is_valid():
    request.session['form_data'] = form.cleaned_data
like image 130
Reiner Gerecke Avatar answered Sep 16 '22 18:09

Reiner Gerecke


As an extension to this, here is a way I have found to use sessions to save the form data with a class-based view:

from django.views.generic.edit import FormView

class MyFormView(FormView):
    template_name = 'myform.html'
    form_class = MyForm
    success_url = '/success/'

    def get_form_kwargs(self):
        """
        The FormMixin uses this to populate the data from the POST request.
        Here, first try to populate it from the session data, if any;
        if there is POST data, it should override the session data.
        """
        kwargs = {'data': self.request.session.get('form_data', None)}
        kwargs.update(super(MyFormView, self).get_form_kwargs())
        return kwargs

    def form_valid(self, form):
        ...
        # save the form data to the session so it comes up as default next time
        self.request.session['form_data'] = form.cleaned_data
        ...
like image 20
Racing Tadpole Avatar answered Sep 19 '22 18:09

Racing Tadpole