>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('test', email='[email protected]', password='password', is_staff=True)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/coen/git/prive/tvdordrecht.nl/env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 183, in create_user
**extra_fields)
TypeError: _create_user() got multiple values for keyword argument 'is_staff'
Expected:
>>> user.is_staff
From StackOverflow:
http://stackoverflow.com/questions/30711544/create-staff-user-in-django/30946633#30946633
Related https://github.com/bak1an/django/commit/dc2f67679712412e2f8bdfbecc340f796d6dbc24
https://code.djangoproject.com/ticket/20541
Interestingly, prior to cab333cb16656cbb7d2bcfb06b2f7aeab9bac7af (which landed in 1.6), doing User.objects.create_user(..., is_staff=True)
actually worked, but User.objects.create_superuser(..., is_staff=False)
would raise a similar error to what we have now.
I think the fix should be to allow these parameters to be passed. It can lead to weird code like User.objects.create_superuser(..., is_superuser=False)
but I don't think we should code against that.
The fix is then quite straighforward:
def create_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, email, password, **extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self._create_user(username, email, password, **extra_fields)
Seems like we can have a cheeseburger without cheese :). Forgiveness is cool. But we can also raise an error for the superuser.
def create_user(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(username, email, password, **extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if not extra_fields.get('is_staff'):
raise ValueError('Superuser needs to be staff. Do not set is_staff.')
if not extra_fields.get('is_superuser'):
raise ValueError('Superuser needs to be superuser. Do not set is_superuser.')
return self._create_user(username, email, password, **extra_fields)
Last edited 9 years ago by Coen van der Kamp (previous)
(diff)