Django HTMLForms AttributeError AttributeError: module 'polls.views' 没有属性'index'



我正在使用Django创建一个简单的HTML输入页面,现在我只是使用DjangoForms的教程,但我得到了错误AttributeError:模块'polls.views'没有属性'index'

以下是所有相关文件:

这就是错误发生的地方:

$ mysite/polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]

这是views.py:

$ polls/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)
# 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('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})

这是forms.py

$ /polls/forms.py
from Django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)

这里是name.html:

$ /polls/name.html
<html>
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<html>

我很困惑为什么会发生这种情况,因为当我将它与一起使用时,编写你的第一个Django应用程序教程是有效的,但当我使用表单时,它不会

提前感谢

您的视图名称不是index而是get_name

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

您的民意测验/urls.py:

from django.urls import path
from . import views
app_name = 'polls' # add this line
urlpatterns = [
path('', views.index, name='index'),
]

最新更新