我无法理解authenticate()和login()应该做什么。例如,在这样的视图中:
class HomeView(FormView):
template_name = 'home/index.html'
form_class = AuthenticationForm
success_url = '/'
@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self, *args, **kwargs):
return super(HomeView, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
if 'next' in self.request.GET:
context['next'] = self.request.GET['next']
return context
def form_valid(self, form):
if form.data['next']:
self.success_url = form.data['next']
login(self.request, form.get_user())
return super(HomeView, self).form_valid(form)
我已经使用活动和非活动用户进行了测试,它的行为就像我不需要authenticate()(即,如果用户处于活动状态,我可以登录,但如果不活动则不能登录)。为什么会这样?感谢名单!
答案 0 :(得分:0)
你可以理解它快速挖掘django源代码(也使用django docs):
Authenticate检查用户名和密码:
def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
正如您所看到的,在未经过身份验证的情况下登录用户并不是一个好主意。
答案 1 :(得分:0)
authenticate()
这将根据给定的用户名/电子邮件检查您的密码/无论它是否有效它将返回用户对象
login()
将为用户创建会话ID并持久保存(在db / cache / etc后端保存会话)用户,这样您就不必在每次用户发送请求时进行身份验证()。