Django用户身份验证和使用DRY登录

时间:2015-10-11 06:13:52

标签: python django authentication

我正在尝试使用Django身份验证创建一个简单的登录。这里的所有代码都有效,但我认为它违反了DRY原则。我会解释一下:

在我的 forms.py 中,我有一个简单的登录表单:

class LoginForm(forms.Form):
  email = forms.CharField()
  password = forms.PasswordField()

  def clean(self):
    email = self.cleaned_data.get('email', None)
    password = self.cleaned_data.get('password', None)
    u = authenticate(email, password)
    if u is None:
      raise forms.ValidationError(ERROR_MSG)
      if not u.is_active:
        raise forms.ValidationError(ERROR_MSG)

所以我已经在这里检查了用户。但是,在我的 views.py

def login(request):
  login_form = LoginForm(request or None)
  if login_form.is_valid():
    #This part is repeated
    email = request.POST.get('email')
    password = request.POST.get('password')
    u = authenticate(email, password)
    login(request, u)

  return render(request, 'home.html', {})

我再次查询数据库,这对我来说似乎违反了DRY。有人有更好的方法吗?我想重用 LoginForm 用于其他用途,但也希望干净利落。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以在request.env["HTTP_SESSION_KEY"] = sess.key 对象上设置authenticate(),然后在视图中使用此user,而不是form两次。

<强> forms.py

user

<强> views.py

class LoginForm(forms.Form):
    email = forms.CharField()
    password = forms.PasswordField()

    def clean(self):
        email = self.cleaned_data.get('email', None)
        password = self.cleaned_data.get('password', None)
        self.u = authenticate(email, password) # set the user as an instance variable
        if self.u is None:
            raise forms.ValidationError(ERROR_MSG)
        if not self.u.is_active:
            raise forms.ValidationError(ERROR_MSG)