我正在学习django,并在网上跟随了一个教程,我试图为“ home”创建一个新视图,但我一直收到属性错误。 AttributeError: module 'pages.views' has no attribute 'home'
我已经检查过我没有做错什么,所以我认为本教程可能已经过时了,但是在urls.py文件中,它说的完全相同。
我已经在Google周围搜索并尝试在逗号之前删除空格,将导入名称更改为“。”,我已经尝试更改函数名称和url中的名称。
views.py:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def home(*args, **kwargs):
return HttpResponse("<h1>Hello World!</h1>")
urls.py:
"""trydjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from pages import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
]
我想将主视图更改为只说“ hello world”,但是它返回属性错误,如果我删除“ path(”,views.home,name =“ home”),则可以正常工作(使用默认主页)
答案 0 :(得分:0)
我认为您导入的 views.py 路径错误。
尝试一下:
"""trydjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views #Import views file from your current root directory
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
]
对不起,我没有检查,但希望能奏效。抱歉,如果这对您的情况没有帮助。
答案 1 :(得分:0)
django中的视图是可调用的,可接收请求并返回响应。 因此,我认为您应该向视图添加参数请求。
尝试一下:
def home(request,*args, **kwargs):
return HttpResponse("<h1>Hello World!</h1>")