How to clear form fields after a submit in Django

后端 未结 6 2203
我在风中等你
我在风中等你 2020-12-14 08:16

I\'ve this:

def profile(request, username):
    if request.method == \'POST\':
        if request.user.is_authenticate         


        
相关标签:
6条回答
  • 2020-12-14 08:34

    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()
    
    0 讨论(0)
  • 2020-12-14 08:34

    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 讨论(0)
  • 2020-12-14 08:41

    You can use this:

    Sometimes you can use this idea take attrs={ "autocomplete":"off"} for each inputs.
    
    0 讨论(0)
  • 2020-12-14 08:42

    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('')
    
    0 讨论(0)
  • 2020-12-14 09:00

    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 讨论(0)
  • 2020-12-14 09:01

    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 讨论(0)
提交回复
热议问题