错误:
AttributeError at /
'UserForm' object has no attribute 'get'
我无法调试此错误!我无视了我的代码很多次,但无法理解在哪里生成错误。请帮助我。提前致谢。
froms.py
class UserForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
password1 = forms.PasswordInput()
password2 = forms.PasswordInput()
def clean(self):
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 != password2:
raise forms.ValidationError('Password Should Match')
return self.cleaned_data
views.py
def userview(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password1 = form.cleaned_data['password1']
user = User(username=username,email=email,password =password1)
user.save()
return HttpResponse('User Created')
else:
form = UserForm()
return render(request,'home.html',{'form':form})
模板 home.html
<form method="post" id="post-form">
{% csrf_token %}
{{form.as_p}}
<input type='submit' value ='ok'>
</form>
项目级urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('useradd.urls'))
]
应用级urls.py
from django.urls import path
from . import views
urlpatterns =[
path('',views.UserForm,name = 'useradd')
]
完整追溯
Environment:
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 2.0.5
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'useradd']
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\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\deprecation.py" in __call__
97. response = self.process_response(request, response)
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\middleware\clickjacking.py" in process_response
26. if response.get('X-Frame-Options') is not None:
Exception Type: AttributeError at /
Exception Value: 'UserForm' object has no attribute 'get'
作为指示,我已经提供了对该错误的完整追溯。我认为我已经在views.py中定义了post方法,当方法未发布时,它将访问该函数的其他部分。但是仍然不明白为什么会发生这样的错误。
答案 0 :(得分:1)
在您的网址中出现问题。而不是视图,您正在将表单传递给url,应该是这样的:
urlpatterns =[
path('',views.userview,name = 'useradd')
]
答案 1 :(得分:0)
这是因为UserForm类没有称为get的方法或变量。您需要先定义一个。