本文将带您了解关于TypeError:method()接受1个位置参数,但给出了2个的新内容,同时我们还将为您解释remove方法接受一个参数表示的相关知识,另外,我们还将为您提供关于Django2.
本文将带您了解关于TypeError:method() 接受 1 个位置参数,但给出了 2 个的新内容,同时我们还将为您解释remove方法接受一个参数表示的相关知识,另外,我们还将为您提供关于Django 2.1.3错误:__init __()接受1个位置参数,但给出了2个、django-rest-knox在生产中:“ TypeError:create()接受1个位置参数,但给出了2个”、Django: TypeError at /login/ __init__() 需要 1 个位置参数,但给出了 2 个、geolocator.reverse()TypeError:reverse()接受2个位置参数,但在pyspark中给出了3个的实用信息。
本文目录一览:- TypeError:method() 接受 1 个位置参数,但给出了 2 个(remove方法接受一个参数表示)
- Django 2.1.3错误:__init __()接受1个位置参数,但给出了2个
- django-rest-knox在生产中:“ TypeError:create()接受1个位置参数,但给出了2个”
- Django: TypeError at /login/ __init__() 需要 1 个位置参数,但给出了 2 个
- geolocator.reverse()TypeError:reverse()接受2个位置参数,但在pyspark中给出了3个
TypeError:method() 接受 1 个位置参数,但给出了 2 个(remove方法接受一个参数表示)
如果我有课…
class MyClass: def method(arg): print(arg)
…我用来创建一个对象…
my_object = MyClass()
…我method("foo")
这样称呼…
>>> my_object.method("foo")Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: method() takes exactly 1 positional argument (2 given)
…为什么 Python 告诉我我给了它两个参数,而我只给了一个参数?
答案1
小编典典在 Python 中,这是:
my_object.method("foo")
…是语法糖,解释器在幕后将其翻译成:
MyClass.method(my_object, "foo")
…正如您所见,它确实有两个参数 - 从调用者的角度来看,只是第一个参数是隐含的。
这是因为大多数方法对它们被调用的对象做一些工作,所以需要有某种方法可以在方法内部引用该对象。按照惯例,第一个参数self
在方法定义中被调用:
class MyNewClass: def method(self, arg): print(self) print(arg)
如果您调用method("foo")
的实例MyNewClass
,它将按预期工作:
>>> my_new_object = MyNewClass()>>> my_new_object.method("foo")<__main__.MyNewClass object at 0x29045d0>foo
偶尔(但不经常),你真的 不
关心你的方法绑定到的对象,在这种情况下,你可以用内置函数来装饰方法,这样说:staticmethod()
class MyOtherClass: @staticmethod def method(arg): print(arg)
…在这种情况下,您不需要向self
方法定义添加参数,它仍然有效:
>>> my_other_object = MyOtherClass()>>> my_other_object.method("foo")foo
Django 2.1.3错误:__init __()接受1个位置参数,但给出了2个
我正在尝试开发带有Django 2.1.3和python 3.7.1的网站,当我转到主页时出现此错误:
/ init ()处的TypeError接受1个位置参数,但给出了2个
以下是有关我编写的代码的一些详细信息:
回车
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.1.3
Python Version: 3.7.1
Installed Applications:
['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','core','crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e,request)
File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request,*callback_args,**callback_kwargs)
File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request,*args,**kwargs)
Exception Type: TypeError at /
Exception Value: __init__() takes 1 positional argument but 2 were given
core / models.py
这只是DB上的一张表:
from django.db import models
class Evento(models.Model):
titolo_evento = models.CharField(max_length=30)
data_inizio = models.DateTimeField()
data_fine = models.DateTimeField()
def __str__(self):
return self.titolo_evento
class Meta:
verbose_name = 'Evento'
verbose_name_plural = 'Eventi'
核心/views.py
在这里,我只想通过用户身份验证即可在主页上看到数据库“ Eventi”,我认为错误在这里,但是我不知道在哪里:
from django.contrib.auth.decorators import login_required
from .models import Evento
from django.views.generic.list import ListView
@login_required
class HomeView(ListView):
queryset = Evento.objects.all()
template_name = 'core/homepage.html'
context_object_name = 'lista_eventi'
核心/ urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.HomeView,name='homepage'),]
urls.py(项目)
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/',admin.site.urls),path('',include('core.urls')),path('accounts/',include('django.contrib.auth.urls'))
]
django-rest-knox在生产中:“ TypeError:create()接受1个位置参数,但给出了2个”
Queryset.Create
仅接受关键字参数。验证时不会发生该错误。它正在创建令牌,这意味着您可以自动创建一些令牌,或者进行续订或通过用户名/密码登录,然后创建令牌。
由于您的开发用户可能已经拥有令牌,因此在开发过程中不会看到该错误。
Django: TypeError at /login/ __init__() 需要 1 个位置参数,但给出了 2 个
如何解决Django: TypeError at /login/ __init__() 需要 1 个位置参数,但给出了 2 个?
我试图在我的简单项目中将 Django 版本从 1.9 更新到 3.2.5,一切看起来都不错。但是当我尝试访问登录页面时,在浏览器中出现以下错误:
Request Method: GET
Request URL: http://localhost:49801/login/
Django Version: 3.2.5
Exception Type: TypeError
Exception Value: __init__() takes 1 positional argument but 2 were given
Exception Location: C:\Program Files (x86)\Microsoft Visual Studio\Shared\python37_64\lib\site-packages\django\core\handlers\base.py,line 181,in _get_response
Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\python37_64\python.exe
Python Version: 3.7.8
Python Path:
[''C:\\source\\repos\\aud'',''C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\python37_64\\python37.zip'',''C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\python37_64\\DLLs'',''C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\python37_64\\lib'',''C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\python37_64'',''C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\python37_64\\lib\\site-packages'']
追溯:
Environment:
Request Method: GET
Request URL: http://localhost:49801/login/
Django Version: 3.2.5
Python Version: 3.7.8
Installed Applications:
[''app'',''django.contrib.admin'',''django.contrib.auth'',''django.contrib.contenttypes'',''django.contrib.sessions'',''django.contrib.messages'',''django.contrib.staticfiles'']
Installed Middleware:
[''django.middleware.security.SecurityMiddleware'',''django.contrib.sessions.middleware.SessionMiddleware'',''django.middleware.common.CommonMiddleware'',''django.middleware.csrf.CsrfViewMiddleware'',''django.contrib.auth.middleware.AuthenticationMiddleware'',''django.contrib.messages.middleware.MessageMiddleware'',''django.middleware.clickjacking.XFrameOptionsMiddleware'']
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\python37_64\lib\site-packages\django\core\handlers\exception.py",line 47,in inner
response = get_response(request)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\python37_64\lib\site-packages\django\core\handlers\base.py",in _get_response
response = wrapped_callback(request,*callback_args,**callback_kwargs)
Exception Type: TypeError at /login/
Exception Value: __init__() takes 1 positional argument but 2 were given
来自 settings.py 的其他信息:
TEMPLATES = [
{
''BACKEND'': ''django.template.backends.django.DjangoTemplates'',''Dirs'': [],''APP_Dirs'': True,''OPTIONS'': {
''context_processors'': [
''django.template.context_processors.debug'',''django.template.context_processors.request'',''django.contrib.auth.context_processors.auth'',''django.contrib.messages.context_processors.messages'',''django.template.context_processors.media'',''app.context_processors.cart'',],},]
forms.py:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from django.db import models
from.models import Comment,Blog,OptionsModel,Order
class BootstrapAuthenticationForm(AuthenticationForm):
"""Authentication form which uses boostrap CSS."""
username = forms.CharField(max_length=254,widget=forms.TextInput({
''class'': ''form-control'',''placeholder'': ''Имя пользователя''}))
password = forms.CharField(label=_("Password"),widget=forms.PasswordInput({
''class'': ''form-control'',''placeholder'':''Пароль пользователя''}))
urls.py:
from datetime import datetime
from django.conf.urls import url,include
import django.contrib.auth.views
import app.forms,app.views
# Uncomment the next lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.views.generic import RedirectView
urlpatterns = [
url(r''^about$'',app.views.about,name=''about''),url(r''^links$'',app.views.links,name=''links''),url(r''^registration$'',app.views.registration,name=''registration''),url(r''^login/$'',django.contrib.auth.views.LoginView,{
''template_name'': ''app/login.html'',''authentication_form'': app.forms.BootstrapAuthenticationForm,''extra_context'':
{
''title'': ''Вход пользователя'',''year'': datetime.Now().year,}
},name=''login''),url(r''^logout$'',django.contrib.auth.views.logoutView,{
''next_page'': ''/'',name=''logout''),]
views.py:
from django.shortcuts import render,redirect,get_object_or_404
from django.views.decorators.http import require_POST
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.db import models
登录.html:
{% extends "app/layout.html" %}
<!--♕-->
{% block content %}
<h2>{{ title }}</h2>
<div>
<div>
<section id="loginForm">
<form action="." method="post">
{% csrf_token %}
<h4>Используйте аккаунт для входа.</h4>
<hr />
<div>
<label for="id_username">Имя пользователя</label>
<div>
{{ form.username }}
</div>
</div>
<div>
<label for="id_password">Пароль</label>
<div>
{{ form.password }}
</div>
</div>
<div>
<div>
<input type="hidden" name="next" value="/" />
<input type="submit" value="Войти"/>
</div>
</div>
{% if form.errors %}
<p>Введите правильное имя пользователя и/или пароль.</p>
{% endif %}
</form>
</section>
</div>
<div>
<section id="socialLoginForm"></section>
</div>
</div>
{% endblock %}
{% block scripts %}
{% load static %}
<script src="{% static ''app/scripts/jquery.validate.min.js'' %}"></script>
{% endblock %}
还更新了许多脚本:bootstrap.js 和 .css 从 3 到 v5.0.2; jquery 从 1.10.2 到 3.6.0; jquery.validate.js 和 respond.js 到最新版本。
如果有人对我收到此错误的原因有任何见解,我将不胜感激。
更新了 url.py 但有同样的错误(感谢 Willem Van Onsem):
from django.conf.urls import include,re_path
re_path(r''^login/$'',django.contrib.auth.views.LoginView.as_view(
{
''template_name'': ''app/login.html'',''extra_context'':
{
''title'': ''Вход пользователя'',}
}),re_path(r''^logout$'',django.contrib.auth.views.logoutView.as_view(
{
''next_page'': ''/'',}),
仅在 urls.py 中使用此代码,错误消失了,但出现了新的错误:
re_path(r''^login/$'',django.contrib.auth.views.LoginView.as_view(),django.contrib.auth.views.logoutView.as_view(),
错误(因为我无法传输 as_view({''template_name'': ''app/login.html''}) ):
TemplateDoesNotExist at /login/
registration/login.html
Request Method: GET
Request URL: http://localhost:62067/login/
Django Version: 3.2.5
Exception Type: TemplateDoesNotExist
Exception Value: registration/login.html
解决方法
LoginView
和 LogoutView
是基于类的视图,因此您需要将其包装在带有 .as_view()
[Django-doc] 的函数中:
url(
r''^login/$'',django.contrib.auth.views.LoginView.as_view(
template_name=''app/login.html'',authentication_form=app.forms.BootstrapAuthenticationForm,extra_context{ ''title'': ''Вход пользователя'',''year'': datetime.now().year }
)
name=''login''
),url(
r''^logout$'',django.contrib.auth.views.LogoutView.as_view(next_page=''/'')
name=''logout''
)
注意:从 django-3.1 开始,url(…)
[Django-doc] 是
不赞成使用 re_path(…)
[Django-doc]。
此外,路径转换器还引入了一种新的路径语法:
为此使用 path(…)
[Django-doc]。
geolocator.reverse()TypeError:reverse()接受2个位置参数,但在pyspark中给出了3个
我也尝试过:
def direccion_func(coordenadas):
dir = geolocator.reverse(coordenadas)
return dir.address
direccion = pandas_udf(direccion_func,returnType = StringType())
paradasRuta1DF =
paradasRuta1DF.withColumn('Direccion',direccion_func(F.col("LatLong")))
并显示错误:TypeError:无法从Column
创建Point实例 ,我认为您收到此错误的原因是 reverse 函数应将包含给定坐标的元组或列表作为参数。
今天关于TypeError:method() 接受 1 个位置参数,但给出了 2 个和remove方法接受一个参数表示的讲解已经结束,谢谢您的阅读,如果想了解更多关于Django 2.1.3错误:__init __()接受1个位置参数,但给出了2个、django-rest-knox在生产中:“ TypeError:create()接受1个位置参数,但给出了2个”、Django: TypeError at /login/ __init__() 需要 1 个位置参数,但给出了 2 个、geolocator.reverse()TypeError:reverse()接受2个位置参数,但在pyspark中给出了3个的相关知识,请在本站搜索。
本文标签: