1👍
✅
I couldn’t find a clean way to login a user without a password: the only way suggested overloading the test client. At the end of the day, I wrote a decorator which creates an admin user and logs the user in.
from functools import wraps
from django.contrib.auth.models import User
from faker import Faker
def create_admin_user_and_login(func):
@wraps(func)
def wrapper(self):
faker = Faker()
username = faker.pronounceable_unique_id(length=30)
password = faker.password()
user = User.objects.create_user(
username=username,
first_name=faker.word().title(),
last_name=faker.word().title(),
email=faker.email(),
password=password)
user.is_staff = True
user.is_superuser = True
user.save()
self.client.login(username=username, password=password)
return func(self)
return wrapper
Where faker.faker.Faker
is a class which generates some fake data.
0👍
I think a user has to be authenticated before login.
I don’t know whether User.objects.get() == authenticate(username, password), I think they are not.
Source:stackexchange.com