gpt4 book ai didi

python - TypeError at/string 索引必须是整数

转载 作者:行者123 更新时间:2023-11-30 22:09:29 25 4
gpt4 key购买 nike

我正在尝试制作一个定制的用户创建表单,用户可以在其中输入用户名、密码和电子邮件以在我的网站中注册。但我无法调试这个错误。它指的是哪种类型错误?我使用 django 2.1 和 postgresql 10.3 作为数据库。

表单.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

url.py

from django.urls import path
from .views import SignUpView
urlpatterns = [
path('',SignUpView,name = 'signup')
]

View .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})

回溯错误

环境:

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

最佳答案

您定义clean功能为:

class SignUpForm(forms.Form):

# ...

def <b>clean</b>(self):
password = self.cleaned_data.get('password')
# ...
<b>return password</b>

super(..)但是,应该返回 cleaned_data ,所以一本字典。通过覆盖它并返回 passwordform.cleaned_data 的“最终产品”不再是一个类似字典的对象,而是一个字符串。或者像 documentation on form-cleaning [Django-doc]指定:

The form subclass's clean() method can perform validation that requires access to multiple form fields. This is where you might put in checks such as "if field A is supplied, field B must contain a valid email address". This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data.

因此,password将取代cleaned_data (而且它不是一个类似字典的对象),所以我们无法再获取 form.cleaned_data['username'] ,自 'some_password'['username'] ,当然对 Python 来说没有任何意义。

我们可以重写 clean函数通过返回self.cleaned_data最后(例如通过调用 super().clean() 函数):

from django import forms

class SignUpForm(forms.Form):
# ...

def <b>clean</b>(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')
<b>return super().clean()</b>

其他错误:验证表单后,您的目标是创建 User对象:

user = User(<b>request</b>, username=username,email=email)

但是我并不奇怪为什么你在这里使用 request目的。我认为应该是:

user = User(username=username, email=email, password=<b>hashed_password</b>)

您还需要首先对密码进行哈希处理,否则将构成严重的安全威胁。请参阅the Django documentation on password hashing了解更多信息。

关于python - TypeError at/string 索引必须是整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com