diff --git a/users/forms.py b/users/forms.py index b8c9785..e007a53 100644 --- a/users/forms.py +++ b/users/forms.py @@ -1,3 +1,4 @@ +from django.contrib import admin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.forms import ModelForm, TextInput @@ -21,6 +22,66 @@ class UserMetaForm(ModelForm): model = CustomUser fields = ['real_name', 'student_number'] widgets = { - 'real_name': TextInput(attrs={'placeholder': 'Robbe Van Herck'}), + 'real_name': TextInput(attrs={'placeholder': 'Robbe Van Herck'}), 'student_number': TextInput(attrs={'placeholder': '001700000'}) } + + +# Add user to groups in django admin + +from django import forms +from django.contrib.auth import get_user_model +from django.contrib.admin.widgets import FilteredSelectMultiple +from django.contrib.auth.models import Group + +User = get_user_model() + + +# Create ModelForm based on the Group model. +class GroupAdminForm(forms.ModelForm): + class Meta: + model = Group + exclude = [] + + # Add the users field. + users = forms.ModelMultipleChoiceField( + queryset=User.objects.all(), + required=False, + # Use the pretty 'filter_horizontal widget'. + widget=FilteredSelectMultiple('users', False) + ) + + def __init__(self, *args, **kwargs): + # Do the normal form initialisation. + super(GroupAdminForm, self).__init__(*args, **kwargs) + # If it is an existing group (saved objects have a pk). + if self.instance.pk: + # Populate the users field with the current Group users. + self.fields['users'].initial = self.instance.user_set.all() + + def save_m2m(self): + # Add the users to the Group. + self.instance.user_set.set(self.cleaned_data['users']) + + def save(self, *args, **kwargs): + # Default save + instance = super(GroupAdminForm, self).save() + # Save many-to-many data + self.save_m2m() + return instance + + +# Unregister the original Group admin. +admin.site.unregister(Group) + + +# Create a new Group admin. +class GroupAdmin(admin.ModelAdmin): + # Use our custom form. + form = GroupAdminForm + # Filter permissions horizontal as well. + filter_horizontal = ['permissions'] + + +# Register the new Group ModelAdmin. +admin.site.register(Group, GroupAdmin) diff --git a/users/migrations/0002_auto_20200724_2340.py b/users/migrations/0002_auto_20200724_2340.py new file mode 100644 index 0000000..f9d04c3 --- /dev/null +++ b/users/migrations/0002_auto_20200724_2340.py @@ -0,0 +1,57 @@ +# Generated by Django 3.0.8 on 2020-07-24 21:40 +import logging + +from django.contrib.auth import get_user_model +from django.core.management.sql import emit_post_migrate_signal +from django.db import migrations +from django.utils import timezone + +logger = logging.getLogger(__name__) + + +def create_superuser(apps, schema_editor): + superuser = get_user_model()( + is_superuser=True, + is_staff=True, + username="admin", # os.environ['ADMIN_USERNAME'], + last_login=timezone.now(), + ) + # superuser.set_password(os.environ['ADMIN_PASSWORD']) + superuser.set_password('admin') + superuser.save() + + +kers_group_permissions = { + "Bestuur": [ + "add_event", + "delete_event", + "change_event", + ] +} + + +def add_group_permissions(apps, schema_editor): + db_alias = schema_editor.connection.alias + emit_post_migrate_signal(2, False, db_alias) + + Group = apps.get_model('auth', 'Group') + Permission = apps.get_model('auth', 'Permission') + + for group in kers_group_permissions: + role, created = Group.objects.get_or_create(name=group) + logger.info(f'{group} Group created') + for perm in kers_group_permissions[group]: + role.permissions.add(Permission.objects.get(codename=perm)) + logger.info(f'Permitting {group} to {perm}') + role.save() + + +class Migration(migrations.Migration): + dependencies = [ + ('users', '0001_initial'), + ] + + operations = [ + migrations.RunPython(create_superuser), + migrations.RunPython(add_group_permissions), + ]