2012-05-09 9 views
2

У меня было чтение этогоКак создать собственный 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 делает

спасибо!

ответ

7

Вы пытаетесь использовать форму в качестве бэкэнд, но это не то, что у вас есть. Как указывается в документе, который вы ссылаетесь на пояснения, бэкендом является класс, который реализует определенные методы, включая registration_allowed. Форма не реализует ни одно из них, что неудивительно, потому что оно предназначено для ввода и проверки пользователя, а не для бэкэнд-действий.

Однако эта страница дает подсказку относительно правильного способа ее реализации. Один из методов, который может определить базовый сервер, - get_form_class(), который возвращает класс формы для использования.Итак, кажется, что вам нужен пользовательский бэкэнд, который наследует от и переопределяет только метод get_form_class, который просто возвращает customRegistrationForm.

+0

hahahah! спасибо, это фантастика. позвольте мне попробовать это! (я просто выпустил большой ol «ohhhhhhhhh», когда я прочитал ваш ответ) – bharal

+0

хороший, сквайр. Оно работает! – bharal