[Django]-How to clear form fields after a submit in Django

35👍

✅

It’s standard to redirect after form submission to prevent duplicates.

Just return a redirect to your form on success.

if form.is_valid():
    form.save()
    return http.HttpResponseRedirect('')

51👍

After saving form instead of showing post dict assign the empty form

form = EmployeeForm()
    if request.method == "POST":
        pDict = request.POST.copy() 
        form = EmployeeForm(pDict) #if not valid shows error with previous post values in corresponding field
        if form.is_valid():
            form.save()
            form = EmployeeForm() # show empty form no need to give HttpResponseRedirect()

2👍

after save() you can return ‘form’ key with MessagesForm(request.GET) value.

return render(request, "profile.html", {
        'username': username,
        'form': MessagesForm(request.GET),
        'messages': messages,
    })

0👍

Usually you can initialize the same empty form after you have saved datas:

if request.method == "POST":
    rf = RegistrationForm(request.POST)
    if rf.is_valid():
        print 'Saving datas..'
        #logic to save datas
        rf = PreRegistrationForm()
        return render_to_response('registration/confirmation_required.html', {'settings': settings}, context_instance=RequestContext(request))

0👍

Try using HttpResponseRedirect('/') instead of HttpResponseRedirect('') in @Karthikkumar’s answer, especially if your home view is an empty path, for instance you have in your urls.py file:

urlpatterns = [path('',views.home_view),]

I had similar issues as those discussed above where HttpResponseRedirect('') directed me to a blank page. Let me know if adding the slash works for you!

0👍

You can use this:

Sometimes you can use this idea take attrs={ "autocomplete":"off"} for each inputs.

0👍

You can redirect back to the initial post

post_url = request.build_absolute_uri(post.get_absolute_url())
return HttpResponseRedirect(post_url)

please note that ‘post’ is an instance of the model created

0👍

I am hoping you have already defined a logic for GET methods. In the case that you have, all you can do is simply add return request.META[‘HTTP_REFERER’] at the end.

See what I mean:

def profile(request, username):
    if request.method == 'POST':
        if request.user.is_authenticated():
            new_message = Message(author = request.user)
            form = MessagesForm(request.POST, instance = new_message)
        else:
            form = MessagesForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        to_user = User.objects.get(username = username)
        form = MessagesForm(initial = {'user': to_user.pk})
    
    return HttpResponseRedirect(request.META['HTTP_REFERER'])

This should work, I just tested it.

0👍

**Maybe I am late but for Django 4.x developers can use: **

from .forms import TodoForm
from django.contrib import messages
from django.http import HttpResponseRedirect

def mytodos(request):
   form = TodoForm()
   if request.method =='POST':
      form=TodoForm(request.POST)
      if form.is_valid:
         form.save()
         messages.success(request,'Task saved successfully')
         return HttpResponseRedirect('/todo/')
   mycontext={'form':form}
   return render(request, 'todo/todo.html',mycontext)

in my urls.py: , i have set path('todo/',views.mytodo, name='todolist')
As you can see, after saving form, mycode will redirect to /todo/ which is automatically refreshed after every submit and a fresh form comes again everytime. If you are a good django dev, you will understand what I did. Make sure to reply if you have any queries .Thanks 🙂

0👍

When we reload the page (F5 or ctrl+shift+R), it submits the previously sent data. so instead of refreshing, we will directly hit the url using return HttpResponseRedirect('/posts/')

This way it will show the page with empty form (now even if you refresh it will only show data, won’t submit it previous data again)

from django.shortcuts import render, HttpResponseRedirect
from django.views import View
from .models import Post
from .forms import PostForm

class PostListView(View):    
    def post(self, request, *args, **kwargs):
        posts = Post.objects.filter(author=request.user).order_by('-created_on')
        form = PostForm(request.POST)

        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.author = request.user 
            new_post.save()
            return HttpResponseRedirect('/posts/')

        context = {
            'post_list': posts,
            'form': form
        }

        return render(request, 'social/post_list.html', context)

Leave a comment