8đź‘Ť
âś…
Well a User
is actually just another Django model (of course it has some extra bindings in Django which makes it a “popular” and “special” model, but it has the same interface, and you can construct instances like with other models). So you can import that model, and create a User
.
For example:
from django.contrib.auth.models import User
my_user = User.objects.create(username='Testuser')
Typically in tests, one however uses a factory (for example with the Factory Boy) to make it easy to construct objects with some data. For example:
import factory
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = factory.Sequence('testuser{}'.format)
email = factory.Sequence('testuser{}@company.com'.format)
class Meta:
model = User
You can then create a user with:
my_user2 = UserFactory()
my_user3 = UserFactory(username='alice')
my_user4 = UserFactory(username='bob', email='bob@work.com')
Source:stackexchange.com