Tanuj KS
Tanuj KS

Reputation: 165

Django Page not found with post request

So I am new to Django and I'm trying to create a HTML form (just following the tutorial for the name input) and I can input the name but can't direct to the /thanks.html page.

$ views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        print(form)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/polls/thanks.html')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})
$ name.html
<html>
  <form action="/polls/thanks.html" method="post">
      {% csrf_token %}
      {{ form }}
      <input type="submit" value="Submit">
  </form>
<html>
$ /mysite/urls
from django.contrib import admin
from django.urls import include, path

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

]
$ mysite/polls/urls.py

from django.urls import path

from polls import views

urlpatterns = [
    path('', views.get_name, name='index'),
]

When I go to to the page, I can enter my name fine but then when I submit i get

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

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

Even though thanks.html is inside /polls

Sorry if the fix is super easy I just haven't used Django before.

Thanks :)

Upvotes: 0

Views: 64

Answers (2)

Dran Dev
Dran Dev

Reputation: 519

Change your main urls.py:

url(r'^polls/', include('polls.urls')),

And in your app's urls.py:

url(r'^$', views.get_name, name='index'),

And in your views.py change to:

if form.is_valid():
        # process the data in form.cleaned_data as required
        # ...
        # redirect to a new URL:
        return render(request, 'thanks.html')

Upvotes: 0

Stack
Stack

Reputation: 4526

Create a view called thanks in views.py

def thanks(request):
    return render(request, 'thanks.html')

Now, Link the /poll/thanks/ url to the thanks template by adding path('thanks/', views.thanks, name='thanks') to your urls.py of the polls app.

$ mysite/polls/urls.py

from django.urls import path

from polls import views

urlpatterns = [
    path('thanks/', views.thanks, name='thanks'),
]

Finally change the following line in your get_name view

return HttpResponseRedirect('/polls/thanks/')

Upvotes: 1

Related Questions