【问题标题】:django.core.exceptions.ImproperlyConfigured: Error importing form class pages.custom_sign_up_form: "cannot import name 'BaseSignupForm'"django.core.exceptions.ImproperlyConfigured:导入表单类 pages.custom_sign_up_form 时出错:“无法导入名称‘BaseSignupForm’”
【发布时间】:2017-03-22 17:30:35
【问题描述】:

我正在尝试扩展 django allauth 的 SignupForm 以自定义我的注册表单。需要是因为我想检查提交的电子邮件是否被接受注册,它是通过检查来自该电子邮件的邀请是否被管理员接受来完成的。

我没有在 forms.py 中定义我的表单,而是使用了另一个名称“custom_sign_up_form.py”。以下是我的完整导入代码。

settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'pages.custom_sign_up_form.CustomSignupForm'

custom_sign_up_form.py

from allauth.account.adapter import DefaultAccountAdapter, get_adapter
from allauth.account.forms import SignupForm
from allauth.account import app_settings
# from django import forms

from invitation.models import Invitation

class CustomSignupForm(SignupForm):
    errors = {
        'not_invited': "Sorry! You are not yet invited.",
    }
    def __init__(self, *args, **kwargs):
        super(CustomSignupForm, self).__init__(*args, **kwargs)

    def clean(self):
        super(CustomSignupForm, self).clean()
        email = self.cleaned_data.get('email')
        email = get_adapter().clean_email(email)
        if email and app_settings.UNIQUE_EMAIL:
            email = self.validate_unique_email(email)
        try:
            Invitation.objects.get(email=email, request_approved=True)
        except Invitation.DoesNotExist:
            # raise forms.ValidationError(errors['Sorry! you are not yet invited'])
            self.add_error('email','Sorry! You are not yet invited')
        return email

【问题讨论】:

  • 这是同一个问题吗? github.com/pennersr/django-allauth/issues/572
  • 他说要使用 forms.Form 而不是扩展 SignupForm。所以我现在应该扩展 forms.Form 类。但是我很困惑我应该在哪里写我的验证逻辑。关于注册或清理功能?
  • 我知道如何回答你的问题。

标签: python django django-allauth


【解决方案1】:

ACCOUNT_SIGNUP_FORM_CLASS是SignupForm (BaseSignupForm)的父类...

https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py#L197

如果要更改表单验证逻辑,需要使用ACCOUNT_ADAPTER

# project/settings.py:
ACCOUNT_ADAPTER = 'project.users.adapter.MyAccountAdapter'

# project/users/adapter.py:
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter

class MyAccountAdapter(DefaultAccountAdapter):

    def clean_email(self, email):
        """
        Validates an email value. You can hook into this if you want to
        (dynamically) restrict what email addresses can be chosen.
        """
        try:
            Invitation.objects.get(email=email, request_approved=True)
        except Invitation.DoesNotExist:
            raise forms.ValidationError('Sorry! you are not yet invited')
        return email

另见https://stackoverflow.com/a/23328414/7724457

【讨论】:

    猜你喜欢
    • 2017-11-10
    • 2015-10-05
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 2022-01-21
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多