__init__() 采用 1 个位置参数,但给出了 2 个 "TypeError at /hello/"

__init__() takes 1 positional argument but 2 were given "TypeError at /hello/"

我尝试设置 hello world 项目,但出现此错误:

TypeError at /hello/
__init__() takes 1 positional argument but 2 were given
Request Method: GET
Request URL:    http://127.0.0.1:8000/hello/
Django Version: 3.1.5
Exception Type: TypeError
Exception Value:    
__init__() takes 1 positional argument but 2 were given
Exception Location: C:\Users\usama\OneDrive\Documents\atom\Django\FirstPro\app\views.py, line 7, in index
Python Executable:  C:\Users\usama\anaconda3\envs\MyEnv\python.exe
Python Version: 3.9.1
Python Path:    
['C:\Users\usama\OneDrive\Documents\atom\Django\FirstPro',
 'C:\Users\usama\anaconda3\envs\MyEnv\python39.zip',
 'C:\Users\usama\anaconda3\envs\MyEnv\DLLs',
 'C:\Users\usama\anaconda3\envs\MyEnv\lib',
 'C:\Users\usama\anaconda3\envs\MyEnv',
 'C:\Users\usama\anaconda3\envs\MyEnv\lib\site-packages']

urls.py

from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
    path('hello/', views.index),
    path('admin/', admin.site.urls),
]

views.py

from django.shortcuts import render
from django.http import HttpRequest
# Create your views here.


def index(request):
    return HttpRequest('hello , world!')

在项目的 setting.py

中安装了应用
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
]

原因是您正在使用 HttpRequest,但 Django 视图必须 return 一个 响应 。 使用这个:

from django.http import HttpResponse

def index(request):
    # pay attention this is HttpResponse not HttpRequest
    return HttpResponse('hello , world!')