2

Hello I am working on a simple form. The form submits fine but if I refresh the page it resubmits the data. Seems the form is holding the data after submit and I assume since after the submit the request method is post. Question is what is the best way after the submit to clear the form in Django. After the submit the form variables should not be holding the values anymore. Thanks

def testimonials(request, template_name="testimonials.html"):
reviews = Reviews.objects.all()
if request.method == 'POST':
    form = forms.ReviewsForm(data = request.POST)
    # create a new item

    if form.is_valid(): # All validation rules pass
        # Process the data in form.cleaned_data
        # ...
        if form.is_valid():
            nameIn = form.cleaned_data['name']
            reviewIn = form.cleaned_data['review']
            newReview = Reviews(name = nameIn, review = reviewIn)
            newReview.save()
            return render_to_response(template_name, locals(), context_instance=RequestContext(request))

else:
    # This the the first page load, display a blank form
    form = forms.ReviewsForm()

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
mcd
  • 6,446
  • 9
  • 27
  • 32

3 Answers3

5

Typically, you would issue a redirect after processing a form/POST request (this is common web development practice to avoid the resubmission issue you mentioned). So instead of a render_to_response, you might issue a HttpResponseRedirect like so:

if form.is_valid(): 
        # Process form as desired here
        # Simple example; use reverse() to avoid hard-coding URLs
        return HttpResponseRedirect('/success/')

Check out the using a form in view for a skeleton of how forms are typically processed.

stellarchariot
  • 2,872
  • 1
  • 19
  • 28
  • I tried your solution and got "The view someview didn't return an HttpResponse object. It returned None instead." error, any Idea? – Bheid May 08 '17 at 19:56
  • I'd recommend posting a new StackOverflow question instead of commenting here, but are you sure the form is valid? – stellarchariot May 09 '17 at 01:42
1

use reverse instead of render to response

 if form.is_valid():
        nameIn = form.cleaned_data['name']
        reviewIn = form.cleaned_data['review']
        newReview = Reviews(name = nameIn, review = reviewIn)
        newReview.save()
        return HttpResponseRedirect(reverse('app_name:url'))
catherine
  • 22,492
  • 12
  • 61
  • 85
0

You could also use the 'redirect' shortcut:

from django.shortcuts import redirect

...
return redirect(newReview)

This is assuming you have get_absolute_url defined in your Review Model.

See the docs for more info.

Lysergia25
  • 134
  • 2
  • 6