首页 > 解决方案 > Django HTMLForms AttributeError AttributeError:模块'polls.views'没有属性'index'

问题描述

我正在使用 Django 创建一个简单的 HTML 输入页面,现在我只是使用 Django Forms 的教程,但我收到错误 AttributeError: module 'polls.views' has no attribute '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 应用程序教程一起使用时,它起作用了,但是当我使用表单时它没有

提前致谢

标签: pythondjango

解决方案


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

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

推荐阅读