我有一个UserProfile模型,可以为我的用户模型添加一些内容,我想做的一件事是为用户提供唯一的电子邮件,所以我在我的UserProfile模型中添加了一个电子邮件属性,并将其设置为unique=True
:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
email = models.EmailField(unique=True)
avatar = models.ForeignKey(Avatar)
...
我为注册创建了一个自定义表单,以便直接向我的UserProfile添加一些信息:
class CreateUserForm(forms.Form):
username = forms.CharField(max_length=30, label="Pseudo")
password1 = forms.CharField(widget=forms.PasswordInput, label="Password")
password2 = forms.CharField(widget=forms.PasswordInput, label="Confirmez pwd")
email = forms.EmailField(widget=forms.EmailInput, label="E-mail")
avatar = AvatarChoiceField(widget=forms.RadioSelect, queryset=Avatar.objects.all(), label="Avatar")
def clean_username(self):
username = self.cleaned_data.get('username')
if User.objects.filter(username=username).exists():
raise forms.ValidationError("This username is already used")
return username
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 != password2:
raise forms.ValidationError("Your passwords do not match")
return password1
def clean_email(self):
email = self.cleaned_data.get('email')
if UserProfile.objects.filter(email=email).exists():
raise forms.ValidationError("This email is already used")
return email
然后在我的views.py中,我对待我的表格:
def create_user(request):
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
username = form.clean_username()
email = form.clean_email()
password = form.clean_password2()
username = form.cleaned_data['username']
avatar = form.cleaned_data['avatar']
user = User.objects.create_user(username=username, password=password)
user.save()
user_profile = UserProfile(user=user, email=email, avatar=avatar)
user_profile.save()
else:
form = CreateUserForm()
return render(request, 'accounts/create.html', locals())
最后,我将表单的电子邮件用于我的UserProfile模型,而不是我的用户模型。通过这种方式,我为我的用户提供了一个独特的电子邮件。它正在发挥作用。
我做得对吗还是有更好的方法来实现我想要的目标吗?
答案 0 :(得分:1)
你走在正确的轨道上,唯一看起来不正确的是你不应该像这样手动调用sscanf(path.data(),"%*[D:/Resize/Resize/ScaledImages2/CamLeft_]%s", &cam_value);
// ^^ The * indicates ignore the data. Don't read into any variable.
方法:
clean
# These are not needed in your view method
username = form.clean_username()
email = form.clean_email()
password = form.clean_password2()
已调用它们。有关详细信息,请参阅this SO问题。