Django allauth在注册或登录时根据不区分大小写来验证用户名的非法字符和唯一性。这很棒。但我想在我自己的配置文件表单上使用相同的验证,该表单上有OneToOne和User。就目前而言,我无法在我的个人资料表格中获得相同的逻辑。
我认为可能导入DefaultAccountAdapter
并覆盖def clean_username
,但我得到了:
TypeError at /accounts/profile/
clean_username() takes exactly 2 arguments (1 given)
我的forms.py
:
from allauth.account.adapter import DefaultAccountAdapter
from .profiles.models import Profile
class UserForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ('username', 'first_name', 'last_name',)
widgets = {
'username': forms.TextInput(
attrs={
'autocapitalize': 'off',
'autocorrect': 'off',
'placeholder': 'Username'
}
),
'first_name': forms.TextInput(
attrs={
'autocapitalize': 'words',
'autocorrect': 'off',
'placeholder': 'First name'
}
),
'last_name': forms.TextInput(
attrs={
'autocapitalize': 'words',
'autocorrect': 'off',
'placeholder': 'Last name'
}
),
}
help_texts = {
'username': '',
}
def clean_username(self, username):
adapter = DefaultAccountAdapter()
username = adapter.clean_username(username)
return username
答案 0 :(得分:1)
我最终想通了。过度思考它。
from allauth.account.adapter import get_adapter
#...
def clean_username(self):
value = self.cleaned_data['username']
value = get_adapter().clean_username(value)
return value