Browse Source

formulaire de création d’utilisateur

Élie Bouttier 8 years ago
parent
commit
5c68ca8258

+ 1 - 1
accounts/forms.py

@@ -1,6 +1,6 @@
 from django.forms import ModelForm
-from django.contrib.auth.models import User
 
+from adhesions.models import User
 from .models import Profile
 
 

+ 22 - 0
accounts/migrations/0004_auto_20170517_2301.py

@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11 on 2017-05-17 21:01
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('accounts', '0003_profile_notes'),
+        ('adhesions', '0011_auto_20170517_2301'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='profile',
+            name='user',
+            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to='adhesions.User', verbose_name='Utilisateur'),
+        ),
+    ]

+ 2 - 20
accounts/models.py

@@ -1,10 +1,9 @@
 from django.db import models
-from django.contrib.auth.models import User
 from django.contrib.contenttypes.models import ContentType
 from django.urls import reverse
 
 
-from adhesions.models import Adhesion, Corporation
+from adhesions.models import Adhesion, User, Corporation
 
 
 class Profile(models.Model):
@@ -17,22 +16,5 @@ class Profile(models.Model):
     class Meta:
         verbose_name = 'profil'
 
-    @property
-    def adhesion(self): # user adhesion
-        ctype = ContentType.objects.get_for_model(User)
-        try:
-            return Adhesion.objects.get(adherent_type=ctype, adherent_id=self.user.pk)
-        except Adhesion.DoesNotExist:
-            return None
-
-    @property
-    def adhesions(self): # user and corporations (for which the user is a member) adhesions
-        user_type = ContentType.objects.get_for_model(User)
-        corp_type = ContentType.objects.get_for_model(Corporation)
-        return Adhesion.objects.filter(
-            models.Q(adherent_type=user_type, adherent_id=self.user.pk)
-            | models.Q(adherent_type=corp_type, adherent_id__in=Corporation.objects.filter(members=self.user).values_list('pk'))
-        )
-
     def __str__(self):
-        return self.user.get_full_name() or self.user.username
+        return str(self.user)

+ 10 - 1
accounts/signals.py

@@ -1,8 +1,9 @@
 from django.dispatch import receiver
 from django.db.models.signals import pre_save, post_save
-from django.contrib.auth.models import User
+from django.template.defaultfilters import slugify
 
 from .models import Profile
+from adhesions.models import User
 
 
 @receiver(pre_save, sender=User, dispatch_uid='set_unusable_password')
@@ -11,6 +12,14 @@ def set_unusable_password(sender, instance, **kwargs):
         instance.set_unusable_password()
 
 
+@receiver(pre_save, sender=User, dispatch_uid='set_default_username')
+def set_default_username(sender, instance, **kwargs):
+    print(1, instance.username)
+    if not instance.username:
+        instance.username = slugify(instance.get_full_name())
+    print(2, instance.username)
+
+
 @receiver(post_save, sender=User, dispatch_uid='create_profile')
 def create_profile(sender, instance, created, **kwargs):
     if created:

+ 35 - 20
adhesions/admin.py

@@ -1,12 +1,13 @@
 from django.contrib import admin
-from django.contrib.auth.models import User, Group
 from django.contrib.contenttypes.admin import GenericStackedInline, GenericTabularInline
 from django.db.models import Q
 from django.contrib.contenttypes.models import ContentType
+from django.contrib.auth.models import User as AuthUser, Group
 from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
+from django.http import HttpResponseRedirect
 
-from .forms import AdhesionForm
-from .models import ProxyUser, Corporation, Adhesion
+from .forms import AdhesionForm, UserCreationForm
+from .models import User, Corporation, Adhesion
 from accounts.models import Profile
 from services.models import Service
 from banking.admin import PaymentInline
@@ -71,27 +72,41 @@ class UserIsAdherentFilter(admin.SimpleListFilter):
 class UserAdmin(AuthUserAdmin):
     list_display = AuthUserAdmin.list_display + ('adherent_id',)
     list_filter = (AuthUserAdmin.list_filter[2], UserIsAdherentFilter) # [2] = actif
-    inlines = (ProfileInline, AdhesionInline,)
 
     def adherent_id(self, user):
-        adherent = user.profile.adhesion
+        adherent = user.adhesion
         if adherent:
             return adherent.id
     adherent_id.short_description = 'Numéro d’adhérent'
 
+    def get_form(self, request, obj=None, **kwargs):
+        if obj:
+            UserAdmin.inlines = (ProfileInline, AdhesionInline,)
+            return super().get_form(request, obj, **kwargs)
+        else:
+            UserAdmin.inlines = (AdhesionInline,)
+            return UserCreationForm
+
     def get_fieldsets(self, request, obj=None):
-        return (
-            AuthUserAdmin.fieldsets[0],
-            AuthUserAdmin.fieldsets[1],
-            (AuthUserAdmin.fieldsets[2][0], {
-                'classes': ('collapse',),
-                'fields': ('is_active', 'is_staff', 'is_superuser',), # removing groups and user_permissions
-            }),
-            (AuthUserAdmin.fieldsets[3][0], {
-                'classes': ('collapse',),
-                'fields': AuthUserAdmin.fieldsets[3][1]['fields'],
-            }),
-        )
+        if obj:
+            return (
+                AuthUserAdmin.fieldsets[0],
+                AuthUserAdmin.fieldsets[1],
+                (AuthUserAdmin.fieldsets[2][0], {
+                    'classes': ('collapse',),
+                    'fields': ('is_active', 'is_staff', 'is_superuser',), # removing groups and user_permissions
+                }),
+                (AuthUserAdmin.fieldsets[3][0], {
+                    'classes': ('collapse',),
+                    'fields': AuthUserAdmin.fieldsets[3][1]['fields'],
+                }),
+            )
+        else:
+            return (
+                (None, {
+                    'fields': ('first_name', 'last_name', 'username',),
+                }),
+            )
 
     def get_actions(self, request):
         actions = super().get_actions(request)
@@ -100,7 +115,7 @@ class UserAdmin(AuthUserAdmin):
         return actions
 
     def has_delete_permission(self, request, obj=None):
-        return obj and not obj.profile.adhesion
+        return obj and not obj.adhesion
 
 
 class AdherentTypeFilter(admin.SimpleListFilter):
@@ -185,8 +200,8 @@ class CorporationAdmin(admin.ModelAdmin):
         return obj and not obj.adhesion
 
 
-admin.site.unregister(User)
+admin.site.unregister(AuthUser)
 admin.site.unregister(Group)
-admin.site.register(ProxyUser, UserAdmin)
+admin.site.register(User, UserAdmin)
 admin.site.register(Corporation, CorporationAdmin)
 admin.site.register(Adhesion, AdhesionAdmin)

+ 15 - 2
adhesions/forms.py

@@ -1,8 +1,21 @@
 from django import forms
-from django.contrib.auth.models import User
+
 
 from djadhere.utils import StringWidget
-from .models import Adhesion, Corporation
+from .models import Adhesion, Corporation, User
+
+
+class UserCreationForm(forms.ModelForm):
+
+    class Meta:
+        model = User
+        fields = ('first_name', 'last_name', 'username',)
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.fields['first_name'].required = True
+        self.fields['last_name'].required = True
+        self.fields['username'].required = False
 
 
 class AdhesionForm(forms.ModelForm):

+ 40 - 0
adhesions/migrations/0011_auto_20170517_2301.py

@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11 on 2017-05-17 21:01
+from __future__ import unicode_literals
+
+import django.contrib.auth.models
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('auth', '0008_alter_user_username_max_length'),
+        ('adhesions', '0010_auto_20170514_1539'),
+    ]
+
+    operations = [
+        migrations.DeleteModel(
+            name='ProxyUser',
+        ),
+        migrations.CreateModel(
+            name='User',
+            fields=[
+            ],
+            options={
+                'verbose_name': 'personne physique',
+                'verbose_name_plural': 'personnes physiques',
+                'proxy': True,
+                'indexes': [],
+            },
+            bases=('auth.user',),
+            managers=[
+                ('objects', django.contrib.auth.models.UserManager()),
+            ],
+        ),
+        migrations.AlterField(
+            model_name='corporation',
+            name='members',
+            field=models.ManyToManyField(blank=True, related_name='corporations', related_query_name='corporation', to='adhesions.User', verbose_name='Membres'),
+        ),
+    ]

+ 22 - 11
adhesions/models.py

@@ -1,6 +1,6 @@
 from django.db import models
 from django.urls import reverse
-from django.contrib.auth.models import User
+from django.contrib.auth.models import User as AuthUser
 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.contrib.contenttypes.models import ContentType
 from django.core.urlresolvers import reverse
@@ -61,14 +61,8 @@ class Adhesion(models.Model):
     get_adherent_name.short_description = 'Nom ou raison sociale'
 
     def get_adherent_link(self):
-        if self.is_physical():
-            name = str(self.adherent.profile)
-            model_name = 'proxyuser'
-        else:
-            name = str(self.adherent)
-            model_name = 'corporation'
-        url = reverse('admin:adhesions_%s_change' % model_name, args=(self.adherent.id,))
-        return format_html(u'<a href="{}">{}</a>', url, name)
+        url = reverse('admin:adhesions_%s_change' % self.adherent._meta.model_name, args=(self.adherent.id,))
+        return format_html(u'<a href="{}">{}</a>', url, str(self.adherent))
     get_adherent_link.short_description = 'Nom ou raison sociale'
 
     def __str__(self):
@@ -79,7 +73,7 @@ class Adhesion(models.Model):
             return 'ADT%d (%s)' % (self.id, self.get_adherent_name())
 
 
-class ProxyUser(User):
+class User(AuthUser):
     class Meta:
         proxy = True
         verbose_name = 'personne physique'
@@ -87,9 +81,26 @@ class ProxyUser(User):
 
     def get_model_perms(self, request):
         return {}
+
+    @property
+    def adhesion(self): # user adhesion
+        ctype = ContentType.objects.get_for_model(User)
+        try:
+            return Adhesion.objects.get(adherent_type=ctype, adherent_id=self.pk)
+        except Adhesion.DoesNotExist:
+            return None
+
+    @property
+    def adhesions(self): # user and corporations (for which the user is a member) adhesions
+        user_type = ContentType.objects.get_for_model(User)
+        corp_type = ContentType.objects.get_for_model(Corporation)
+        return Adhesion.objects.filter(
+            models.Q(adherent_type=user_type, adherent_id=self.user.pk)
+            | models.Q(adherent_type=corp_type, adherent_id__in=Corporation.objects.filter(members=self.user).values_list('pk'))
+        )
     
     def __str__(self):
-        return str(self.profile)
+        return self.get_full_name() or self.username
 
 
 class Corporation(models.Model):

+ 5 - 4
adhesions/views.py

@@ -1,16 +1,17 @@
 from django.contrib.auth.decorators import login_required
 from django.core.exceptions import PermissionDenied
 from django.shortcuts import render, get_object_or_404
-from django.contrib.auth.models import User
 
-from .models import Corporation
+from .models import User, Corporation
 
 
 @login_required
 def user(request):
+    # request.user is concrete model whereas user is proxy model
+    user = User.objects.get(pk=request.user.pk)
     return render(request, 'adhesions/user.html', {
-        'adherent': request.user,
-        'adhesion': request.user.profile.adhesion,
+        'adherent': user,
+        'adhesion': user.adhesion,
     })
 
 @login_required