所以我是 Django 新手,我正在尝试创建一个 HTML 表单(只需按照名称输入教程进行操作),我可以输入名称,但无法直接进入 /thanks.html 页面。$ views.pyfrom django.http import HttpResponseRedirectfrom django.shortcuts import renderfrom .forms import NameFormdef 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/urlsfrom django.contrib import adminfrom django.urls import include, pathurlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls),]$ mysite/polls/urls.pyfrom django.urls import pathfrom polls import viewsurlpatterns = [ 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 回答
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
Cats萌萌
TA贡献1805条经验 获得超9个赞
创建一个视图,thanks在views.py中调用
def thanks(request):
return render(request, 'thanks.html')
现在,通过添加到投票应用程序的 urls.py将/poll/thanks/URL 链接到模板。thankspath('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/')
![?](http://img1.sycdn.imooc.com/53339fdf00019de902200220-100-100.jpg)
暮色呼如
TA贡献1853条经验 获得超9个赞
改变你的主要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')
添加回答
举报
0/150
提交
取消