Created
October 15, 2014 07:37
-
-
Save kezabelle/f4b650881dfe1e5a380b to your computer and use it in GitHub Desktop.
This was for `benwilber` in #django in reference to this ML thread: https://groups.google.com/forum/#!topic/django-users/Zz9rKT7GVM0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def populate_initial_data(apps, schema_editor): | |
User = apps.get_model(settings.AUTH_USER_MODEL) | |
Group = apps.get_model('auth', 'Group') | |
user = User(username="test", email="[email protected]") | |
# you need to know how to set the password ... ugh | |
# I'm assuming User().set_password doesn't exist? | |
from django.contrib.auth.hashers import make_password | |
user.password = make_password('test') | |
user.save() | |
# this should, I hope, work, because neither is a real model | |
group = Group.objects.create(name="Test Group") | |
user.groups.add(group) | |
# Or you could probably do ... I can't recall if you need to | |
# .save() afterwards | |
user.groups = [group] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def populate_initial_data(apps, schema_editor): | |
# this is bad because now your historic data migration is | |
# tied to your current User model ... | |
from django.contrib.auth import get_user_model | |
User = get_user_model() | |
# realistically, if you've imported a conrete User instance, you may | |
# as well import the concrete Group instance, which would definitely avoid | |
# the TypeError. | |
Group = apps.get_model('auth', 'Group') | |
# this will work because you've imported the real model, but should be avoided | |
user = User.objects.create_user("test", email="[email protected]", password="test") | |
group = Group.objects.create(name="Test Group") | |
# this won't work because Group != auth.Group, technically. | |
# user.groups.add(group) | |
# This might work. | |
M2M = user.groups.through | |
M2M.objects.create(user_id=user.pk, group_id=group.pk) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment