nouvelles vues pour users

This commit is contained in:
Hugo LEVY-FALK 2018-03-09 00:53:38 +01:00
parent b5a51e1bec
commit 0303710d26
5 changed files with 246 additions and 271 deletions

56
users/forms.py Normal file
View file

@ -0,0 +1,56 @@
from django import forms
from django.contrib.auth.models import User
from .models import School
class CreateSchool(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
class CreateUser(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
class EditPhone(forms.ModelForm):
class Meta:
model = School
fields = ['phone']
class EditLogo(forms.ModelForm):
class Meta:
model = School
fields = ['logo']
class EditMail(forms.ModelForm):
class Meta:
model = User
fields = ['email']
class EditJury1(forms.ModelForm):
class Meta:
model = School
fields = [
'first_name_j1',
'last_name_j1',
'phone_j1',
'mail_j1'
]
class EditJury2(forms.ModelForm):
class Meta:
model = School
fields = [
'first_name_j2',
'last_name_j2',
'phone_j2',
'mail_j2'
]

View file

@ -36,6 +36,10 @@ class School(models.Model):
null=True, null=True,
blank=False, blank=False,
) )
validated = models.BooleanField(
verbose_name="Inscription validé.",
default=False
)
first_name_j1 = models.CharField( first_name_j1 = models.CharField(
max_length=255, max_length=255,
verbose_name="Prénom juré n°1" verbose_name="Prénom juré n°1"

View file

@ -2,50 +2,17 @@
{% load bootstrap4 %} {% load bootstrap4 %}
{% block content %} {% block content %}
<h1>{{object.name}}</h1> <h1>{{school.name}}</h1>
{% if manager_right in perms %} {% if manager_right in perms %}
Numéro de téléphone : Numéro de téléphone :
{% if object.school.phone %}{{object.school.phone}} {% if school.phone %}{{school.phone}}
<a class="btn btn-primary btn-sm" href="{% url 'users:edit-school-name' object.pk %}">
<i class="fa fa-edit"></i>
Éditer
</a>
{%else%} {%else%}
Non indiqué{%endif%}<br/> Non indiqué{%endif%}<br/>
{%endif%} {%endif%}
{% if manager_right in perms %} <a class="btn btn-primary btn-sm" href="{% url 'users:edit-school-name' school.pk %}">
<h2>Membres</h2> <i class="fa fa-edit"></i>
<table class="table table-striped"> Éditer
<thead>
<th>Nom</th>
<th>Prénom</th>
<th>Pseudo</th>
<th>Administrer</th>
</thead>
<tbody>
{% for member in members %}
<tr>
<td>{{member.last_name}}</td>
<td>{{member.first_name}}</td>
<td>{{member.username}}</td>
<td>
{% if member in manager_group.user_set.all %}
<a class="btn btn-outline-danger btn-sm" href="{% url 'users:degrade-user' object.pk member.pk %}">
<i class="fa fa-trash"></i>
Enlever le privilège Administrateur
</a> </a>
{% else %}
<a class="btn btn-outline-warning btn-sm" href="{% url 'users:promote-user' object.pk member.pk %}">
<i class="fa fa-star"></i>
Promouvoir administrateur
</a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
<h2>Contenus</h2> <h2>Contenus</h2>
{% if manager_right in perms %} {% if manager_right in perms %}
<a class="btn btn-success btn-sm" href="{% url 'content:content-new' %}"> <a class="btn btn-success btn-sm" href="{% url 'content:content-new' %}">

View file

@ -1,79 +1,45 @@
from django.urls import path from django.urls import path, include
from .views import ( from . import views
CreateUser,
CreateSchool,
EditSchoolName,
EditSchoolPhone,
DeleteSchool,
Login,
Logout,
PasswordChange,
Profile,
School,
promote_user,
degrade_user
)
app_name = 'users' app_name = 'users'
urlpatterns = [ urlpatterns = [
path( path(
'user/new', 'user/new',
CreateUser.as_view(), views.create_user,
name='new-user' name='new-user'
), ),
path( path(
'login', 'user/',
Login.as_view(), include('django.contrib.auth.urls')
name='login'
),
path(
'logout',
Logout.as_view(),
name='logout',
),
path(
'change_password',
PasswordChange.as_view(),
name='change-password'
),
path(
'user/<int:pk>',
Profile.as_view(),
name='profile',
), ),
path( path(
'school/new', 'school/new',
CreateSchool.as_view(), views.create_school,
name='new-school' name='new-school'
), ),
path( path(
'school/<int:pk>', 'school/<int:pk>',
School.as_view(), views.school,
name='school' name='school',
), )
path(
'school/<int:school_pk>/degrade/<int:user_pk>',
degrade_user,
name='degrade-user'
),
path(
'school/<int:school_pk>/promote/<int:user_pk>',
promote_user,
name='promote-user'
),
path(
'school/<int:pk>/edit_name',
EditSchoolName.as_view(),
name='edit-school-name'
),
path( path(
'school/<int:pk>/edit_phone', 'school/<int:pk>/edit_phone',
EditSchoolPhone.as_view(), views.edit_phone,
name='edit-school-phone' name='edit-school-phone'
), ),
path( path(
'school/<int:pk>/delete', 'school/<int:pk>/edit_mail',
DeleteSchool.as_view(), views.edit_mail,
name='delete-school' name='edit-school-mail'
),
path(
'school/<int:pk>/jury_1',
views.edit_jury_1,
name='edit-jury-1'
),
path(
'school/<int:pk>/jury_2',
views.edit_jury_2,
name='edit-jury-2'
), ),
] ]

View file

@ -1,199 +1,181 @@
from django.contrib.auth.models import User, Group
from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin
from django.views.generic import CreateView, UpdateView, DeleteView, DetailView
from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView, login_required
from django.contrib.auth.hashers import make_password
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib import messages from django.contrib import messages
from django.urls import reverse, reverse_lazy from django.urls import reverse
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect, render
from django.contrib.admin.views.decorators import staff_member_required
from content.models import Category
from .models import School from .models import School
from content.models import Content from . import forms
class CreateUser(CreateView): @staff_member_required
model = User def create_user(request):
fields = [ user_form = forms.CreateUser(request.POST or None)
'first_name', if user_form.is_valid():
'last_name', u = user_form.save()
'email', messages.success(request, "L'utilisateur {} {} a bien été créé.".format(
'username', u.first_name, u.last_name))
'password', return redirect(reverse('settings:index'))
] return render(request, 'edit.html', {
template_name = 'edit.html' 'form': user_form,
'title': "Création d'un utilisateur",
def get_success_url(self): 'validate': "Créer"
return reverse( })
'users:create-userprofile',
kwargs={'pk': self.object.pk}
)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Inscription"
context['validate'] = "S'inscrire"
return context
def form_valid(self, form):
r = super().form_valid(form)
self.object.set_password(form.cleaned_data['password'])
self.object.save()
return r
class Profile(LoginRequiredMixin, UpdateView):
model = User
template_name = 'users/profile.html'
fields = [
'username',
'first_name',
'last_name',
'email'
]
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = self.object.username
context['validate'] = "Modifier"
return context
def get_success_url(self):
return reverse(
'users:profile',
kwargs={'pk': self.object.pk}
)
class CreateSchool(LoginRequiredMixin, PermissionRequiredMixin, CreateView): @staff_member_required
permission_required = 'users.add_schoolprofile' def create_school(request):
model = School school_form = forms.CreateSchool(request.POST or None)
fields = ['name'] if school_form.is_valid():
template_name = 'edit.html' s = school_form.save()
success_url = reverse_lazy('settings:index') messages.success(request, "L'école {} a bien été créée.".format(s.name))
return redirect(redirect('settings:index'))
def get_context_data(self, **kwargs): return render(request, 'edit.html', {
context = super().get_context_data(**kwargs) 'form': school_form,
context['title'] = "Création de l'école" 'title': "Création d'une école",
context['validate'] = "Créer" 'validate': "Créer"
return context })
def form_valid(self, form):
response = super(CreateSchool, self).form_valid(form)
profile = School()
profile.group = form.instance
profile.save()
return response
class EditSchoolName(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): def school(request, pk):
model = School school = get_object_or_404(School, pk=pk)
fields = ['name'] can = request.user.is_staff or request.user == school.admin
template_name = 'edit.html' if not can:
messages.error(request, 'Vous ne pouvez pas accéder à cette page')
def get_success_url(self): return redirect(reverse('home'))
return reverse('users:edit-school-phone', kwargs={'pk':self.object.school.pk}) return render(request, 'users/school.html', {'school':school})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Édition de l'école"
context['validate'] = "Modifier"
return context
def has_permission(self):
return self.request.user.has_perm('users.manage_'+str(self.kwargs['pk']))
def form_valid(self, *args, **kwargs):
r = super().form_valid(*args, **kwargs)
self.object.school.save()
return r
class EditSchoolPhone(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): def edit_phone(request, pk):
model = School school = get_object_or_404(School, pk=pk)
fields = ['phone'] can = request.user.is_staff or request.user == school.admin
template_name = 'edit.html' if not can:
messages.error(request, 'Vous ne pouvez pas accéder à cette page')
def get_success_url(self): return redirect(reverse('settings:index'))
return reverse('users:school', kwargs={'pk':self.object.group.pk}) school_form = forms.EditPhone(request.POST or None, instance=school)
if school_form.is_valid():
def get_context_data(self, **kwargs): s = school_form.save()
context = super().get_context_data(**kwargs) messages.success(request, "L'école {} a bien été modifiée.".format(s.name))
context['title'] = "Édition de l'école" return redirect(redirect('settings:index'))
context['validate'] = "Modifier" return render(request, 'edit.html', {
return context 'form': school_form,
'title': "Édition du numéro de téléphone",
def has_permission(self): 'validate': "Modifier"
return self.request.user.has_perm('users.manage_'+str(self.kwargs['pk'])) })
class DeleteSchool(LoginRequiredMixin, PermissionRequiredMixin, DeleteView): def edit_logo(request, pk):
model = Group school = get_object_or_404(School, pk=pk)
permission_required = 'users.delete_schoolprofile' can = request.user.is_staff or request.user == school.admin
if not can:
messages.error(request, 'Vous ne pouvez pas accéder à cette page')
return redirect(reverse('settings:index'))
school_form = forms.EditLogo(request.POST or None, instance=school)
if school_form.is_valid():
s = school_form.save()
messages.success(request, "L'école {} a bien été modifiée.".format(s.name))
return redirect(redirect('settings:index'))
return render(request, 'edit.html', {
'form': school_form,
'title': "Édition du logo",
'validate': "Modifier"
})
class School(LoginRequiredMixin, PermissionRequiredMixin, DetailView): def edit_mail(request, pk):
model = Group school = get_object_or_404(School, pk=pk)
template_name = "users/school.html" can = request.user.is_staff or request.user == school.admin
if not can:
def get_context_data(self, **kwargs): messages.error(request, 'Vous ne pouvez pas accéder à cette page')
context = super().get_context_data() return redirect(reverse('settings:index'))
context['contents'] = Content.objects.filter(school_owner=self.object.school) user_form = forms.EditMail(request.POST or None, instance=school.admin)
context['school'] = True if user_form.is_valid():
context['members'] = User.objects.filter(userprofile__school=self.object.school) s = user_form.save()
context['manager_right'] = 'users.manage_' + str(self.object.pk) messages.success(request, "L'école {} a bien été modifiée.".format(s.name))
context['manager_group'],_ = Group.objects.get_or_create(name=str(self.object.pk)+'_admins') return redirect(redirect('settings:index'))
return context return render(request, 'edit.html', {
'form': user_form,
def has_permission(self): 'title': "Édition du numéro du mail",
return self.request.user.has_perm('users.view_'+str(self.kwargs['pk'])) 'validate': "Modifier"
})
class Logout(SuccessMessageMixin, LogoutView): def edit_jury_1(request, pk):
success_message = "Vous vous êtes bien déconnecté." school = get_object_or_404(School, pk=pk)
can = request.user.is_staff or request.user == school.admin
if not can:
messages.error(request, 'Vous ne pouvez pas accéder à cette page')
return redirect(reverse('settings:index'))
school_form = forms.EditJury1(request.POST or None, instance=school)
if school_form.is_valid():
s = school_form.save()
messages.success(request, "L'école {} a bien été modifiée.".format(s.name))
return redirect(redirect('settings:index'))
return render(request, 'edit.html', {
'form': school_form,
'title': "Édition du jury 1",
'validate': "Modifier"
})
class Login(SuccessMessageMixin, LoginView): def edit_jury_2(request, pk):
template_name = "edit.html" school = get_object_or_404(School, pk=pk)
success_message = "Bienvenue !" can = request.user.is_staff or request.user == school.admin
extra_context = { if not can:
'title' : "Connexion", messages.error(request, 'Vous ne pouvez pas accéder à cette page')
'validate' : "Se connecter", return redirect(reverse('settings:index'))
} school_form = forms.EditJury2(request.POST or None, instance=school)
if school_form.is_valid():
s = school_form.save()
messages.success(request, "L'école {} a bien été modifiée.".format(s.name))
return redirect(redirect('settings:index'))
return render(request, 'edit.html', {
'form': school_form,
'title': "Édition du jury 2",
'validate': "Modifier"
})
class PasswordChange(SuccessMessageMixin, PasswordChangeView): def validate(request, pk):
template_name = "edit.html" school = get_object_or_404(School, pk=pk)
success_url = reverse_lazy("home") can = request.user.is_staff or request.user == school.admin
success_message = "Le mot de passe a été changé." if not can:
extra_context = { messages.error(request, 'Vous ne pouvez pas accéder à cette page')
'title' : "Changer le mot de passe", return redirect(reverse('settings:index'))
'validate' : "Changer", jury_1_ok = any([
} school.first_name_j1 is not None,
school.last_name_j1 is not None,
school.phone_j1 is not None,
school.mail_j1 is not None
])
jury_2_ok = any([
school.first_name_j2 is not None,
school.last_name_j2 is not None,
school.phone_j2 is not None,
school.mail_j2 is not None
])
logo_ok = school.logo is not None
phone_ok = school.phone is not None
mail_ok = school.admin.email is not None
if not jury_1_ok:
messages.warning(request, 'Pas de jury n°1 défini.')
if not jury_2_ok:
messages.warning(request, 'Pas de jury n°2 défini.')
if not logo_ok:
messages.warning(request, 'Pas de logo défini.')
if not phone_ok:
messages.error(request, 'Pas de téléphone défini.')
if not mail_ok:
messages.error(request, 'Pas de mail défini.')
for category in Category.objects.all():
if not category.content_set.filter(school_owner=school):
messages.warning(request, 'Pas de contenu dans la catégorie {}.'.format(category.name))
@login_required if phone_ok and mail_ok:
def promote_user(request, school_pk, user_pk): school.validated = True
school = get_object_or_404(Group, pk=school_pk) school.save()
user = get_object_or_404(User, pk=user_pk) messages.success(request, 'Inscription validée.')
if request.user.has_perm('manage_'+str(school.pk)):
admins,_ = Group.objects.get_or_create(name=str(school.pk)+'_admins')
user.groups.add(admins)
user.save()
messages.success(request, user.username + ' a été ajouté aux administrateurs de ' + school.name)
return redirect(reverse('users:school', kwargs={'pk':school.pk}))
messages.error(request, "Vous n'aves pas ce droit.")
return redirect('home')
return redirect(reverse('settings:index'))
@login_required
def degrade_user(request, school_pk, user_pk):
school = get_object_or_404(Group, pk=school_pk)
user = get_object_or_404(User, pk=user_pk)
if request.user.has_perm('manage_'+str(school.pk)):
admins,_ = Group.objects.get_or_create(name=str(school.pk)+'_admins')
user.groups.remove(admins)
user.save()
messages.success(request, user.username + ' a été enlevé des administrateurs de ' + school.name)
return redirect(reverse('users:school', kwargs={'pk':school.pk}))
messages.error(request, "Vous n'aves pas ce droit.")
return redirect('home')