[英]TypeError at / string indices must be integers
I am trying to make a custom made user creation form where user can type username,password and email to register in my site. 我正在尝试制作一个自定义用户创建表单,用户可以在其中键入用户名,密码和电子邮件以在我的站点中注册。 but I am unable to debug this error. 但我无法调试此错误。 What kind of type error its referring to? 它指的是什么类型的错误? I am using django 2.1 and postgresql 10.3 as db. 我使用django 2.1和postgresql 10.3作为db。
forms.py forms.py
from django import forms
class SignUpForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'password'}))
password_confirmation = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'password confirmation'}))
email = forms.EmailField()
def clean(self):
password = self.cleaned_data.get('password')
password_confirmation = self.cleaned_data.get('password_confirmation')
print(password)
print(password_confirmation)
if password != password_confirmation:
raise forms.ValidationError('Password Must Match')
return password
urls.py urls.py
from django.urls import path
from .views import SignUpView
urlpatterns = [
path('',SignUpView,name = 'signup')
]
views.py views.py
from django.shortcuts import render
from .forms import SignUpForm
from django.contrib.auth.models import User
from django.shortcuts import HttpResponse
def SignUpView(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
user = User(request,username=username,email=email)
user.set_password(password)
user.save()
return HttpResponse('User Created')
else:
form =SignUpForm()
return render(request,'signup.html',{'form':form})
TraceBack Error TraceBack错误
Environment: 环境:
Request Method: POST
Request URL: http://127.0.0.1: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',
'account']
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\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\HP\Desktop\muvi_2\account\views.py" in SignUpView
10. username = form.cleaned_data['username']
Exception Type: TypeError at /
Exception Value: string indices must be integers
You define the clean
function as: 您将clean
函数定义为:
class SignUpForm(forms.Form):
# ...
def clean(self):
password = self.cleaned_data.get('password')
# ...
return password
The super(..)
however, is supposed to return the cleaned_data
, so a dictionary. 然而, super(..)
应该返回cleaned_data
,所以是字典。 By overwriting it and returning the password
, the "endproduct" of form.cleaned_data
is no longer a dictionary-like object, but a string. 通过覆盖它并返回password
, form.cleaned_data
“ form.cleaned_data
”不再是类字典对象,而是字符串。 Or like the documentation on form-cleaning [Django-doc] specifies: 或者像表格清理文档[Django-doc]指定:
The form subclass's
clean()
method can perform validation that requires access to multiple form fields. 表单子类的clean()
方法可以执行需要访问多个表单字段的验证。 This is where you might put in checks such as "if field A is supplied, field B must contain a valid email address". 您可以在此处进行检查,例如“如果提供了字段A,则字段B必须包含有效的电子邮件地址”。 This method can return a completely different dictionary if it wishes, which will be used as thecleaned_data
. 如果愿意, 此方法可以返回完全不同的字典 ,该字典将用作cleaned_data
。
So as a result, password
will take the place of the cleaned_data
(and it is not a dictionary-like object), so we can no longer obtain form.cleaned_data['username']
, since 'some_password'['username']
, of course makes no sense to Python. 因此, password
将取代cleaned_data
(并且它不是类似字典的对象),因此我们无法再获得form.cleaned_data['username']
,因为'some_password'['username']
,当然对Python没有意义。
We can rewrite the clean
function by returning the self.cleaned_data
at the end (by calling the super().clean()
function for example): 我们可以通过在末尾返回self.cleaned_data
来重写clean
函数(例如通过调用super().clean()
函数):
from django import forms
class SignUpForm(forms.Form):
# ...
def clean(self):
password = self.cleaned_data.get('password')
password_confirmation = self.cleaned_data.get('password_confirmation')
print(password)
print(password_confirmation)
if password != password_confirmation:
raise forms.ValidationError('Password Must Match')
return super().clean()
Additional error(s) : after the form is validated, you aim to create a User
object with: 其他错误 :在验证表单后,您的目标是创建一个User
对象:
user = User(request, username=username,email=email)
It is however not crear to me why you here use the request
object. 然而,对我来说,为什么你在这里使用request
对象并不是一个问题。 I think it should be: 我认为它应该是:
user = User(username=username, email=email, password=hashed_password)
You will also need to hash the password first, since otherwise it is a serious security threat . 您还需要首先哈希密码,否则它是一个严重的安全威胁 。 See the Django documentation on password hashing for more information. 有关更多信息,请参阅有关密码散列的Django文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.