UserCreationFormでemailも必須項目に

元々のUserCreationForm。これを元にemailの登録を必須にする(パスワードをリセットするときにメールアドレスが必要なので)。
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and password.
"""
username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
help_text = _("Enter the same password as above, for verification."))

class Meta:
model = User
fields = ("username",)

def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_("A user with that username already exists."))

def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2

def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user

アカウント作成アプリ - shisogohanの日記とUserCreationFormのusernameをあたりを参考にしてMyUserCreationFormを作ると以下のようになる。
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(label=_("Email"), required=True)

class Meta(UserCreationForm.Meta):
fields = ("username", "email")

def clean_email(self):
email = self.cleaned_data["email"]
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError(_("A user with that email already exists."))

使うときは元のUserCreationFormは消してこんなかんじでimportすればOK。エラーテキストもちゃんと表示されていいかんじ。
from forms import MyUserCreationForm as UserCreationForm



posted by 右京 | Python
blog comments powered by Disqus
×

この広告は1年以上新しい記事の投稿がないブログに表示されております。