None typeobject in success_url django



我有一个用户注册表单,如下面的代码所示。一旦提交表单并成功将行添加到数据库中,就会发生错误。

views.py

class UserCreateView(CreateView):
form_class = UserCreateForm
model = User
template_name = 'internethq/user_form.html'
success_url = '/internethq/login'

forms.py

class UserCreateForm(UserCreationForm):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
email = forms.EmailField(required=True)
class Meta:
model = User
fields = [
'first_name',
'last_name',
'username',
'email',
'password1',
'password2'
]
def clean_password1(self):
exp = re.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$")
if exp.match(self.cleaned_data['password1']):
return self.cleaned_data['password1']
else:
raise ValidationError('Must contain one uppercase letter, one lowercase letter, one number and one special character.')

def save(self, commit = True):
user = super().save(commit = False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()

误差

Internal Server Error: /internethq/signup/
AttributeError at /internethq/signup/ 'NoneType' object has no attribute '__dict__'  Traceback (most recent call last): 
bit of trimming here...

File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) 
File "/home/togi/atollaviation/env/lib/python3.6/site-packages/django/python3.6/site-packages/django/views/generic/edit.py", line 113, in get_success_url url = self.success_url.format(**self.object.__dict__)

我认为success_url看起来正确,但有一个错误,我错过了?

此代码在开发服务器中运行良好。

谢谢你的帮助。

您需要从Form.save方法返回创建的对象

class UserCreateForm(UserCreationForm):

...

def save(self, commit = True):
user = super().save(commit = False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user

返回的对象在很多地方使用,包括一般的表单处理视图。通常只是返回创建的对象,有时是在保存之前修改对象,类似下面的

obj = form.save(commit=False)
obj.attr = value
obj.save()

相关内容

  • 没有找到相关文章

最新更新