gpt4 book ai didi

python - 我如何为 Django 注册创建自定义 Django 后端?

转载 作者:行者123 更新时间:2023-11-28 20:51:14 25 4
gpt4 key购买 nike

我读过这个

http://docs.b-list.org/django-registration/0.8/backend-api.html

而且我尝试过制作自己的后端。我这样做是因为我想创建一个后端,不允许使用相同的电子邮件进行注册,并且我想更改电子邮件错误消息。我也想加入我自己的领域!

这是我想出的:

from django import forms
from registration.forms import RegistrationForm
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from registration.forms import attrs_dict

class customRegistrationForm(RegistrationForm):
email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_("Confirm email"))

def clean_email(self):
"""
Validate that the email is alphanumeric and is not already
in use.
"""
try:
email = User.objects.get(email__iexact=self.cleaned_data['email'])
except User.DoesNotExist:
return self.cleaned_data['email']
raise forms.ValidationError(_("That email already exists - if you have forgotten your password, go to the login screen and then select \"forgot password\""))

def clean(self):
"""
Verifiy that the values entered into the two email fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.

"""
if 'email' in self.cleaned_data and 'email2' in self.cleaned_data:
if self.cleaned_data['email'] != self.cleaned_data['email2']:
raise forms.ValidationError(_("The two email fields didn't match."))
return super(RegistrationForm,clean)

以上内容在我的init.py 文件中(不管是什么)

然后,我的 urls.py 代码中有:

url(r'^accounts/register/$',
register,
{ 'backend': 'myapp.forms.customRegistrationForm' },
name='registration_register'),
... #other urls here!

现在,当我转到/accounts/register 页面时,出现以下错误:

AttributeError at /accounts/register/

'customRegistrationForm' object has no attribute 'registration_allowed'

这很奇怪。它似乎在告诉我,我需要将“registration_allowed”方法添加到我的子类中。但是,该子类是 RegistrationForm 的子类,它工作正常并且没有定义那些东西......我知道我可以添加这些成员,但它似乎违背了扩展的目的,对吧?

更新

这是现在可以运行的代码!

我将不同的类分解为不同文件夹中的不同 init.py 文件 - 一个称为“forms”,一个称为“backends”,两者都位于我的文件夹“djangoRegistration”中主要项目。

/forms/init.py

from django import forms
from registration.forms import RegistrationForm
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from registration.forms import attrs_dict

class customRegistrationForm(RegistrationForm):
def __init__(self, *args, **kw):
super(RegistrationForm, self).__init__(*args, **kw)
self.fields.keyOrder = [
'username',
'email',
'email2',
'password1',
'password2'
]

email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
maxlength=75)),
label=_("Confirm email"))

def clean_email(self):
"""
Validate that the email is alphanumeric and is not already
in use.
"""
try:
email = User.objects.get(email__iexact=self.cleaned_data['email'])
except User.DoesNotExist:
return self.cleaned_data['email']
raise forms.ValidationError(_("That email already exists - if you have forgotten your password, go to the login screen and then select \"forgot password\""))

def clean(self):
"""
Verifiy that the values entered into the two email fields
match. Note that an error here will end up in
``non_field_errors()`` because it doesn't apply to a single
field.

"""
if 'email' in self.cleaned_data and 'email2' in self.cleaned_data:
if self.cleaned_data['email'] != self.cleaned_data['email2']:
raise forms.ValidationError(_("The two email fields didn't match."))
return super(RegistrationForm,clean)

/backends/init.py

from registration.backends.default import DefaultBackend
from dumpstownapp.djangoRegistration.forms import customRegistrationForm

class customDefaultBackend(DefaultBackend):
def get_form_class(self, request):
"""
Return the default form class used for user registration.

"""
return customRegistrationForm

最后,我的 urls.py 只是引用了新的后端:

url(r'^accounts/register/$',
register,
{ 'backend': 'myapp.djangoRegistration.backends.customDefaultBackend' },
name='registration_register'),
#more urls here! yay!

作为最后的说明,我必须添加一些代码来“排序”字段的显示方式,这就是 customRegistrationForm 中的 init 方法所做的

谢谢!

最佳答案

您正在尝试使用表单作为后端,但这根本不是后端。正如您链接到的文档所解释的那样,后端是一个实现某些方法的类,包括 registration_allowed。该表单没有实现任何这些,这并不奇怪,因为它用于用户输入和验证,而不是后端操作。

但是,该页面确实给出了有关实现它的正确方法的提示。后端可以定义的方法之一是 get_form_class(),它返回要使用的表单类。因此,您似乎需要的是一个自定义后端,它继承自 registration.backends.default.DefaultBackend 并仅覆盖 get_form_class 方法,该方法仅返回 customRegistrationForm

关于python - 我如何为 Django 注册创建自定义 Django 后端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10517391/

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