У меня было чтение этогоКак создать собственный django-сервер для django-регистрации?
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)
выше идет в моем инициализации .py файла (whetever, что есть)
Тогда у меня в urls.py код:
url(r'^accounts/register/$',
register,
{ 'backend': 'myapp.forms.customRegistrationForm' },
name='registration_register'),
... #other urls here!
Теперь, когда я иду к/счета/зарегистрировать страницу, я получаю следующее сообщение об ошибке:
AttributeError at /accounts/register/
'customRegistrationForm' object has no attribute 'registration_allowed'
Что странно. Кажется, мне говорят, что мне нужен метод «registration_allowed», добавленный в мой подкласс. НО, подкласс является подклассом RegistrationForm, который отлично работает и не имеет того, что определено ... Я знаю, что я может добавить этих членов, но, похоже, он превзошел цель расширения, не так ли?
UPDATE
Вот код сейчас, это работает!
Я разогнал различные классы в разной INIT .py файлов в разных папках - один под названием «форму» и один под названием «движки», оба из которых сидят в папке «djangoRegistration» под моим основным проектом.
/Опалубка/Инициализационных .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)
/бэкэнды/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!
В качестве заключительной записки у меня было добавить код для «заказа», как поля были представлены, что и есть init метод в customRegistrationForm делает
спасибо!
hahahah! спасибо, это фантастика. позвольте мне попробовать это! (я просто выпустил большой ol «ohhhhhhhhh», когда я прочитал ваш ответ) – bharal
хороший, сквайр. Оно работает! – bharal