Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear form fields after a submit in Django

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?

like image 709
Fred Collins Avatar asked Sep 28 '22 08:09

Fred Collins


People also ask

How can I delete post data after submitting form?

Form reset() Method The reset() method resets the values of all elements in a form (same as clicking the Reset button).

How do I delete a form in Django after submitting?

It's standard to redirect after form submission to prevent duplicates. Just return a redirect to your form on success. after save() you can return 'form' key with MessagesForm(request.

How do you clear a form in Python?

Python Set clear() method removes all elements from the set.

What does form clean Do Django?

The form subclass's clean() method can perform validation that requires access to multiple form fields. This is where you might put in checks such as “if field A is supplied, field B must contain a valid email address”.


2 Answers

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()
like image 48
Karthikkumar Avatar answered Sep 30 '22 21:09

Karthikkumar


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('')
like image 34
Yuji 'Tomita' Tomita Avatar answered Sep 30 '22 21:09

Yuji 'Tomita' Tomita