How to clear form fields after a submit in Django


Question

I've this:

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 render(request, "profile.html", {'username': username, 'form': form, 'messages': messages})

This form submit a message and return the same page. My problem is that after the submit I see again my field filled with my information. How to clear it after the submit?

1
18
4/24/2011 9:41:11 PM

Accepted Answer

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('')
24
4/24/2011 11:13:38 PM

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()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon