如何在提交註冊表單後測試用戶是否已登錄?測試用戶是否已成功登錄
我嘗試了以下方法,但即使在將登錄邏輯添加到我的註冊視圖之前,它也會返回True
。
def test_that_user_gets_logged_in(self):
response = self.client.post(reverse('auth-registration'),
{ 'username':'foo',
'password1':'bar',
'password2':'bar' })
user = User.objects.get(username='foo')
assert user.is_authenticated()
多數民衆贊成被測試代碼:
class RegistrationView(CreateView):
template_name = 'auth/registration.html'
form_class = UserCreationForm
success_url = '/'
def auth_login(self, request, username, password):
'''
Authenticate always needs to be called before login because it
adds which backend did the authentication which is required by login.
'''
user = authenticate(username=username, password=password)
login(request, user)
def form_valid(self, form):
'''
Overwrite form_valid to login.
'''
#save the user
response = super(RegistrationView, self).form_valid(form)
#Get the user creditials
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
#authenticate and login
self.auth_login(self.request, username, password)
return response
您是否嘗試過'response.request.user.is_authenticated()'? – 2011-04-14 09:29:01
我做了但請求對象沒有用戶對象。 – Pickels 2011-04-14 09:34:26