Search code examples
djangodjango-views

django form resubmitted upon refresh pag


After I submit the form for the first time and then refresh the form it gets resubmitted and and I don't want that. How can I fix this ?

Here are my views:

from django.shortcuts import render
from django.http import HttpResponse
from free.models import contact

def index(request):
    if request.method == 'POST':
        fullname = request.POST.get('fullname')
        email = request.POST.get('email')
        message = request.POST.get('message')
    
        en = contact(fullname=fullname, email=email, message=message)
        en.save()
    
    return render(request, 'index.html')

Solution

  • In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser, so:

    from django.shortcuts import redirect
    
    
    def index(request):
        if request.method == 'POST':
            fullname = request.POST.get('fullname')
            email = request.POST.get('email')
            message = request.POST.get('message')
            contact.objects.create(fullname=fullname, email=email, message=message)
            return redirect('name-of-some-view')
        return render(request, 'index.html')

    Note: It is better to use a Form [Django-doc] than to perform manual validation and cleaning of the data. A Form will not only simplify rendering a form in HTML, but it also makes it more convenient to validate the input, and clean the data to a more convenient type.


    Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from contact to Contact.