57 lines
2.0 KiB
Python
57 lines
2.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
# Generated by Django 1.9.7 on 2016-08-01 14:54
|
|
from __future__ import unicode_literals
|
|
|
|
from django.core.exceptions import ObjectDoesNotExist
|
|
from django.db import migrations
|
|
|
|
|
|
def migrate_groups_and_user_permissions(apps, schema_editor):
|
|
"""
|
|
This function migrates the database to the new groups logic:
|
|
- Rename Group 'Anonymous' (pk=1) to 'Default'
|
|
- Rename Group 'Registered users' (pk=2) to 'Previous group Registered'
|
|
- Add all users who are not in any group to this group (pk=2)
|
|
- Add all permissions of 'Previous group Registered' to all other groups (exclude 'Default')
|
|
|
|
But only do this migration if:
|
|
- there are groups in the database
|
|
- the name of the first group is 'Guests'.
|
|
"""
|
|
User = apps.get_model('users', 'User')
|
|
Group = apps.get_model('auth', 'Group')
|
|
|
|
if Group.objects.exists():
|
|
try:
|
|
group_default = Group.objects.filter(pk=1)
|
|
if group_default.get().name == 'Guests':
|
|
group_default.update(name='Default')
|
|
|
|
group_old_registered = Group.objects.filter(pk=2)
|
|
group_old_registered.update(name='Previous group Registered')
|
|
group_old_registered = group_old_registered.get()
|
|
|
|
users = User.objects.all()
|
|
for user in users:
|
|
if not user.groups.exists():
|
|
user.groups.add(group_old_registered.pk)
|
|
|
|
groups = Group.objects.filter(pk__gt=2)
|
|
for group in groups:
|
|
for permission in group_old_registered.permissions.all():
|
|
group.permissions.add(permission)
|
|
except ObjectDoesNotExist:
|
|
# If the first or second group doesn't exists, just pass this migraition
|
|
pass
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
|
('users', '0003_user_number'),
|
|
]
|
|
|
|
operations = [
|
|
migrations.RunPython(migrate_groups_and_user_permissions),
|
|
]
|