Home > Enterprise >  Avoid Django form being resubmitted by using HttpResponseRedirect
Avoid Django form being resubmitted by using HttpResponseRedirect

Time:07-22

My views.py runs code fine when I press a button on my HTML page, views.py:

def start_or_end_fast(request):
   
  #If starting fast, add a row to the db:
  #fast_finished = False
  #start_date_time using = current time 
  #end_date_time using = current time 
  if request.method == 'POST' and 'start_fast' in request.POST:
    add_fast = logTimes(fast_finished=False,start_date_time=datetime.now(),end_date_time=datetime.now())
    add_fast.save()
    print(add_fast.start_date_time,add_fast.end_date_time) 
    print('Fast started')
    #return render(request,'startandstoptimes/index.html')
    return HttpResponseRedirect('startandstoptimes/index.html')

You can see my commented return line, this works but when I refresh the page I can resubmit the data, I want to avoid this. In researching my solution, I saw this could be solved using HttpResponseRedirect but I am not able to get this to work with my code, the more I change the more broken things become.

My application urls.py:

from turtle import home
from django.urls import path,include
from . import views

urlpatterns = [
    path('', views.start_or_end_fast,name="start_or_end_fast")
]

My project urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('startandstoptimes.urls'))
]

I believe it is related to the URLs, due to the 404 message I see:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/startandstoptimes/index.html
Using the URLconf defined in myfastingsite.urls, Django tried these URL patterns, in this order:

admin/
[name='start_or_end_fast']
The current path, startandstoptimes/index.html, didn’t match any of these.

Am I going down the right route trying to use HttpResponseRedirect or is there a better solution?

CodePudding user response:

class HttpResponseRedirect¶

The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. 'https://www.yahoo.com/search/'), an absolute path with no domain (e.g. '/search/'), or even a relative path (e.g. 'search/'). In that last case, the client browser will reconstruct the full URL itself according to the current path. See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302.

See this link for more details: docs

As what the documentation says, HttpResponseRedirect accepts URL and not the path of your template. You should be doing it something like this:

 from django.urls import reverse
 return HttpResponseRedirect(reverse('start_or_end_fast'))
  • Related