使用django用户帐户设置年龄限制
我想对django用户帐户实现的帐户注册过程设置年龄限制。我在注册表单中添加了一个字段,如中的示例。在我的自定义视图中,我有以下内容:使用django用户帐户设置年龄限制,django,authentication,Django,Authentication,我想对django用户帐户实现的帐户注册过程设置年龄限制。我在注册表单中添加了一个字段,如中的示例。在我的自定义视图中,我有以下内容: import user_accounts_custom.forms from profiles.models import ArtistProfile, UserProfile from datetime import date import math class SignupView(SignupView): form_class = user_a
import user_accounts_custom.forms
from profiles.models import ArtistProfile, UserProfile
from datetime import date
import math
class SignupView(SignupView):
form_class = user_accounts_custom.forms.SignupForm
def create_user(self, form, commit=True, **kwargs):
old_enough = self.birthday_check(form)
if old_enough:
return super(SignupView, self).create_user(self, form,
commit=True, **kwargs)
else:
return super(SignupView, self).create_user(self, form,
commit=False, **kwargs)
def birthday_check(self, form):
birthdate = form.cleaned_data["birthdate"]
fraud_detect = abs(date.today() - birthdate)
if ( (fraud_detect.days / 365.0) < 13 ):
# WHAT ABOUT THE BABIES!!!!
return False
else:
return True
将commit设置为False会在SignupView实例的方法中进一步给我一个类型错误,因为它试图返回一个用户对象,但正如我所希望的那样,它没有创建一个。我想发送一个HttpResponseForbidden对象或一条消息,但鉴于上下文,我不确定如何在这里实现它。我正在考虑的另一个选择是使用一个虚拟用户对象,特别是我的匿名用户对象,并简单地重定向而不创建帐户;我不确定哪条路径最简单。这帮助我解决了问题,下面是我如何实现它的:
def clean(self):
cleaned_data = super(SignupForm, self).clean()
bday = self.cleaned_data["birthdate"]
fraud_detect = abs(date.today() - bday)
if ( (fraud_detect.days / 365.0) < 13 ):
# WHAT ABOUT THE BABIES!!!!
raise forms.ValidationError("Sorry, you cannot create an account.",
code="too_young",
)
return cleaned_data
诀窍是在我为自定义django用户帐户而创建的forms.py中截取clean方法
帮助验证的一些附加链接注意:这些链接指向django 1.6版:
Django视图代码应该只有与显示视图相关的逻辑。如果有帮助的话,表单验证应该移到你的forms.py。谢谢你的提示!每个人都说“瘦视图”和“胖模型”,但在你进入战壕之前,不一定清楚什么是最佳实践。是的,你给出的答案正确地做到了这一点,并通过覆盖clean方法将表单逻辑分离为forms.py。干杯基本上,任何与应用程序某个部分相关的逻辑都应该位于对其所做工作最有意义的位置。瘦视图非常容易阅读,只输出视图的最终上下文等@AronYsidoro再次感谢!