0

When making views in django, is it allowable to pass in POST data as context? That is:

def view( request ):
    #view operations here
    #...

    c = Context({
        'POST':request.POST,
    })
    return render_to_response("/templatePath/", c, context_instance=RequestContext(request))

My goal is to maintain data in fields already filled without having to save them to a db. That is, when you click the option to add additional field entries, the data you've put in is kept and automatically filled back into the forms. I feel this might be sloppy or perhaps unsafe. Is there any reason this is a bad or unsafe technique? Is there a better way to maintain data?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
WonderBoy55
  • 41
  • 1
  • 3
  • 6
  • 1
    post would be in the context anyway? {{request.POST}} – JamesO Jun 01 '11 at 14:09
  • In any case, you *must* redirect after a HTTP POST request, to ensure the next request is HTTP GET. I'm not sure you can implement this behavior directly without writing the form contents to the database, but that will become very tricky. – André Caron Jun 01 '11 at 14:17

1 Answers1

4

Although nothing is inherently bad about passing the request.POST variable to the template, everything you're trying to achieve is already handled by the stereotypical form view. If you go down your current path, you will end up with a buggy version of the recommended way to handle forms in Django.

See using a form in a view in the the Django documentation.

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form
    return render_to_response('contact.html', {
        'form': form,
    })

In you case, you'll want to make sure the redirect URL redirects to the same form. See django.shortcuts.redirect().

André Caron
  • 44,541
  • 12
  • 67
  • 125
  • Note: you cannot pass the `form` instance directly to the redirected view because the redirect issues a HTTP 30x response and a separate request will be made. However, if your form is based on some model, then the form initialization should handle setting the previously set fields in the form. – André Caron Jun 01 '11 at 14:19