The Great Magnet. What a fool I was to defy him.

Entries tagged as ‘Form Preview’

Django Form Preview and Confirmation Page

May 1, 2008 · 1 Comment

If you need to create a form preview and confirmation page in Django, you can always find the snippets online or read the docs http://www.djangoproject.com/documentation/form_preview/

I think we can all agree Django has some amazing docs. It warrants the common IRC response: “This is the answer to your question, as the docs clearly state”.

I want to note that this is not what I recommend doing. Use some of the more robust form preview classes. But for purposes of LEARNING, I think it is great to make something on your own. It’s the only way I learn, at least. Programming devices beyond my skill level are as good as magic to me.

So, a few months ago I was making some forms and wanted a form preview, but I couldn’t figure out how to make it. You know, those things where you click “continue” and the next page redisplays all of your data and says: “Please make sure this information is accurate”.

Anyways, being new to Django myself, I wanted to make my own instead of downloading a snippet. Again, I can’t learn that way. It stays magic, and I’m not trying to learn magic.

I just thought of a simple workaround and put a hidden form field in the form whose value is changed depending on the submit stage.

Turns out that is exactly how the form_preview works!

Basically, a simple data entry view would look like this:

from myapp import myform
def entry(request):

 if request.POST:
  form = myform(request.POST)
  if form.is_valid():
   form.save()
  return render_to_response('form.html',{'form':form})

 form = myform()
 return render_to_response('form.html', {'form':form})

This would render the form, and on POST, it would call save() if form is valid. Otherwise, re-render the form w/ errors.

To change this to accept a confirmation view, add a hidden variable to your form Template.
How about something like this:

<input type="hidden" name="stage" id="id_stage" value="{{ stage }}"/>

Now we can pass the stage variable to the template via the view.


def entry(request):
 if request.POST: #If POST
  form = myform(request.POST) #fill form data
  if form.is_valid():
   if request.POST['stage'] == '1':
    form.save()
   return render_to_response('form.html', {'form':form, 'stage':'1'}) #Set stage to 1 since form is valid
  return render_to_response('form.html', {'form':form})
 form = myform()
 return render_to_response('form.html', {'form':form})

You can see that this now adds the value “1″ to hidden field “stage” if the form is valid. It then re displays the form. If you POST again while stage == “1″, the form saves. If the form is not valid , the original form is redisplayed anyways and stage is blank.

So, it turns out the form_preview does basically this with some clever tricks that is useful to look at.

Enjoy!

Categories: Django
Tagged: , , ,