Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

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

I tried to setup hello world project but it gives me this error:

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:UsersusamaOneDriveDocumentsatomDjangoFirstProappviews.py, line 7, in index
Python Executable:  C:Usersusamaanaconda3envsMyEnvpython.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!')

installed app in project's setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
]
question from:https://stackoverflow.com/questions/65911851/init-takes-1-positional-argument-but-2-were-given-typeerror-at-hello

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason is you are using HttpRequest but the Django view must return a response. Use this:

from django.http import HttpResponse

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...