djangodjango-southdata-migration

Login fails with user from data migration


I try to add a new user with help of data migration (django 1.6.7 + south). My migration:

class Migration(DataMigration):

    def forwards(self, orm):
        user = User(
            pk=1, 
            username="admin", 
            password="admin",
            is_active=True,
            is_superuser=True,
            is_staff=True,
            last_login="2011-09-01T13:20:30+03:00", 
            email="email@gmail.com",
            date_joined="2011-09-01T13:20:30+03:00"
        )
        user.save()

    def backwards(self, orm):
        raise RuntimeError("Cannot reverse this migration.")

User creation works as I'm able to obtain the user instance via the shell:

>>> from django.contrib.auth.models import User
>>> user = User.objects.get(pk=1)
>>> user.username
u'admin'
>>> user.password
u'admin'

The problem is when I'm trying to authorise via the admin panel, there is an error:

Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.


Solution

  • You can't add a password in this way for a User object (i.e. password="admin"). When Django authenticates a user it hashes the password you enter in the admin login screen using your settings.SECRET_KEY. When Django attempts to match this hash against your stored password, it is matching against the string 'admin'.

    You need to update your migration to look like the following:

        user = User(pk=1, username="admin", is_active=True,
                    is_superuser=True, is_staff=True,
                    last_login="2011-09-01T13:20:30+03:00"
                    email="email@gmail.com",
                    date_joined="2011-09-01T13:20:30+03:00")
        user.set_password('admin')
        user.save()
    

    Note the removal of the password='admin' and the addition of the useful User model method set_password

    HTH