Pytest-django: admin_user doesn't like django_username_field being set to email

Created on 18 Jun 2017  路  6Comments  路  Source: pytest-dev/pytest-django

I'm using https://github.com/tmm/django-username-email which uses the email in place of having a separate user name, this generally works well but it breaks the admin_user fixture because this:

if username_field != 'username':
    extra_fields[username_field] = 'admin'

leads to this

user = UserModel._default_manager.create_superuser(
    'admin', '[email protected]', 'password', **extra_fields)

raising this

TypeError: create_superuser() got multiple values for argument 'email'

Most helpful comment

In my case I actually had an adapted UserModel._default_manager.create_superuser method that does not take a username argument. That's what you tend to do if you have a custom UserModel that does not have a username field (but an email field).

So, your code change is indeed better, but does not cover the case when you have no username field. Which is moot anyway, because you can't cover all custom cases of course. Thanks for the follow up.

All 6 comments

I have the same problem.

Did you find a solution for this?

I overrode the admin_user fixture in conftest.py, you just declare a function there with the same name. Mine looks like:

@pytest.fixture()
def admin_user(db, django_user_model, django_username_field):
    """A Django admin user.

    This uses an existing user with username 'admin', or creates a new one with
    password 'password'.
    """
    UserModel = django_user_model
    username_field = django_username_field

    try:
        user = UserModel._default_manager.get(**{username_field: '[email protected]'})
    except UserModel.DoesNotExist:
        extra_fields = {}
        user = UserModel._default_manager.create_superuser(
            '[email protected]', 'password', **extra_fields)
    return user

Yeah, I also overwrote it. Easy enough to do. It looks like the authors of pytest-django took the effort of making it work for the case where username=email, but then in practice, this doesn't work.

In my case I actually had an adapted UserModel._default_manager.create_superuser method that does not take a username argument. That's what you tend to do if you have a custom UserModel that does not have a username field (but an email field).

So, your code change is indeed better, but does not cover the case when you have no username field. Which is moot anyway, because you can't cover all custom cases of course. Thanks for the follow up.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rodrigorodriguescosta picture rodrigorodriguescosta  路  4Comments

aljosa picture aljosa  路  8Comments

koxu1996 picture koxu1996  路  3Comments

arne-cl picture arne-cl  路  8Comments

blueyed picture blueyed  路  7Comments