找不到发布请求的Django Page

时间:2020-09-28 17:21:02

标签: python django

因此,我是Django的新手,我正在尝试创建HTML表单(仅在输入名称的教程之后进行操作),并且我可以输入名称,但无法定向到/thanks.html页面。

$ 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'),
]

当我转到页面时,可以输入我的名字,但是当我提交时,我会得到

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.

即使Thanks.html位于/ polls

很抱歉,如果修复程序非常简单,我只是以前从未使用过Django。

谢谢:)

2 个答案:

答案 0 :(得分:1)

在views.py中创建名为thanks的视图

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

现在,通过将/poll/thanks/添加到民意调查应用程序的urls.py中,将thanks URL链接到path('thanks/', views.thanks, name='thanks')模板。

$ mysite/polls/urls.py

from django.urls import path

from polls import views

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

最后在您的get_name视图中更改以下行

return HttpResponseRedirect('/polls/thanks/')

答案 1 :(得分:0)

更改主urls.py

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

在您应用的urls.py中:

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

然后在您的views.py中将其更改为:

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