kers/users/forms.py

88 lines
2.5 KiB
Python
Raw Normal View History

from django.contrib import admin
2020-07-22 00:52:02 +02:00
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
2020-07-24 23:33:11 +02:00
from django.forms import ModelForm, TextInput
2020-07-22 00:52:02 +02:00
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
2020-07-22 05:03:01 +02:00
fields = ('username', 'student_number', 'real_name',)
2020-07-22 00:52:02 +02:00
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
2020-07-22 05:03:01 +02:00
fields = ('username', 'student_number', 'real_name',)
2020-07-22 16:06:04 +02:00
class UserMetaForm(ModelForm):
class Meta:
model = CustomUser
2020-07-24 23:33:11 +02:00
fields = ['real_name', 'student_number']
widgets = {
2020-07-25 13:32:38 +02:00
'real_name': TextInput(attrs={'placeholder': 'Robbe Van Herck'}),
'student_number': TextInput(attrs={'placeholder': '01701111', 'pattern': '[0-9]{8,}'})
2020-07-24 23:33:11 +02:00
}
# 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)