2

私はこれを読んだことがあります

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 ページに移動すると、次のエラーが表示されます。

/accounts/register/ の AttributeError

「customRegistrationForm」オブジェクトには属性「registration_allowed」がありません

これは奇妙です。サブクラスに「registration_allowed」メソッドを追加する必要があると言っているようです。しかし、サブクラスはRegistrationFormのサブクラスであり、正常に動作し、そのようなものが定義されていません...これらのメンバーを追加できることはわかっていますが、拡張の目的に勝っているようですよね?

アップデート

動作するようになったコードは次のとおりです。

さまざまなクラスをさまざまなフォルダーのさまざまなinit .py ファイルに分割しました。1 つは "forms" と呼ばれ、もう 1 つは "backends" と呼ばれ、どちらもメイン プロジェクトの下のフォルダー "djangoRegistration" にあります。

/フォーム/ 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)

/バックエンド/ 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メソッドが行っていることです。

ありがとう!

4

1 に答える 1

7

フォームをバックエンドとして使用しようとしていますが、それはバックエンドとはまったく異なります。リンク先のドキュメントで説明されているように、バックエンドは、を含む特定のメソッドを実装するクラスですregistration_allowed。フォームはこれらのいずれも実装していません。これは、バックエンドアクションではなく、ユーザー入力と検証を目的としているため、驚くことではありません。

ただし、そのページには、これを実装する正しい方法に関するヒントが記載されています。バックエンドが定義できるメソッドの1つは、ですget_form_class()。これは、使用するフォームクラスを返します。registration.backends.default.DefaultBackendしたがって、必要なのは、メソッドのみを継承してオーバーライドするカスタムバックエンドであるように見えます。このget_form_classメソッドは単に。を返しますcustomRegistrationForm

于 2012-05-09T13:51:22.023 に答える