Commit 930e9f04 authored by fred.perso's avatar fred.perso

Update top bar menus and add account forms (create account and change password)

parent 6440430c
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
from collections import OrderedDict
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import (AccordionHolder, AccordionItem, Fieldset,
ButtonHolder, Column, Layout, Row, Submit, InlineSwitchField)
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm, PasswordResetForm
from django.utils.translation import ugettext_lazy as _
from leaflet.forms.widgets import LeafletWidget
from .models import User
class UserCreateForm(UserCreationForm):
class Meta:
model = User
fields = UserCreationForm.Meta.fields + (
'first_name', 'last_name', 'email', 'is_resp', 'coord_territory', 'geom', 'access_all_data',
'edit_all_data', 'catchauth',
# 'organism','mobile_phone', 'home_phone', 'addr_appt', 'addr_building', 'addr_street', 'addr_city', 'addr_city_code',
# 'addr_dept', 'addr_country',
'comment', 'id_bdsource', 'bdsource', 'geom')
widgets = {'geom': LeafletWidget(), }
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.layout = Layout(
AccordionHolder(
AccordionItem('Informations principales',
Fieldset(_("Caractéristiques principales"),
Row(
Column(
'username', css_class='small-12 medium-12 large-4'),
Column('password1',
css_class='small-12 medium-6 large-4'),
Column('password2',
css_class='small-12 medium-6 large-4'),
),
Row(
Column('email',
css_class='small-12 medium-12 large-4'),
Column('first_name',
css_class='small-12 medium-6 large-4'),
Column('last_name',
css_class='small-12 medium-6 large-4'),
),
),
Fieldset(_("Nom et email"),
),
Fieldset(_("Responsabilité et autorisations"),
Column(
InlineSwitchField('is_resp', label_column='large-12',
input_column='large-12'),
css_class='small-12 medium-3 large-2'
),
Column(
'coord_territory', css_class='small-12 medium-9 large-10'),
Column(InlineSwitchField('access_all_data', label_column='large-12',
input_column='large-12'),
css_class='small-12 large-6'),
Column(InlineSwitchField('edit_all_data', label_column='large-12',
input_column='large-12'),
css_class='small-12 large-6'),
Column('catchauth', css_class='large-12'),
),
# Fieldset("Coordonnées",
#
# ),
Fieldset("Localisation",
Column('geom', css_class='large-12'),
), ),
AccordionItem(
'Source',
Row(
Column('bdsource', css_class='medium-6 small-12',
readonly=True),
Column('id_bdsource', readonly=True,
css_class='medium-6 small-12')
),
),
AccordionItem(
'Commentaire',
Row(
Column('comment', css_class='large-12'),
),
),
),
ButtonHolder(
Submit('submit', 'Enregistrer', css_class='button large'),
),
)
self.helper.form_action = 'submit'
self.helper.form_show_errors = True
super(UserCreateForm, self).__init__(*args, **kwargs)
# class PasswordUpdateForm(PasswordChangeForm):
#
# def __init__(self, *args, **kwargs):
# self.helper = FormHelper()
# # self.helper.form_method = 'post'
# self.helper.layout = Layout(
# Row(
# Column(
# 'old_password', css_class='small-12 medium-12 large-4'),
# Column('new_password1',
# css_class='small-12 medium-6 large-4'),
# Column('new_password1',
# css_class='small-12 medium-6 large-4'),
# ),
# ButtonHolder(
# Submit('submit', 'Enregistrer', css_class='button large'),
# ),
# )
#
# self.helper.form_action = 'submit'
# self.helper.form_show_errors = True
#
# super(PasswordUpdateForm, self).__init__(*args, **kwargs)
class PasswordUpdateForm(PasswordChangeForm):
# this is now only needed for styling purposes
helper = FormHelper()
helper.form_tag = False
helper.label_class = 'medium-5'
helper.field_class = 'medium-7'
helper.layout = Layout('old_password','new_password1','new_password2',
ButtonHolder(
Submit('submit', 'Enregistrer', css_class='button large'), css_class='text-right'
),
)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(PasswordUpdateForm, self).__init__(user, *args, **kwargs)
# ensures correct ordering of form fields
PasswordUpdateForm.base_fields = OrderedDict(
(k, PasswordUpdateForm.base_fields[k])
for k in ['old_password', 'new_password1', 'new_password2']
)
class PasswordResetForm(PasswordResetForm):
def __init__(self, *args, **kw):
super(PasswordResetFormExtra, self).__init__(*args, **kw)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'small-12 medium-6 large-4'
self.helper.field_class = 'small-12 medium-6 large-8'
self.helper.layout = Layout(
'email',
Div(
Submit('submit', 'Réinitialiser le mot de passe', css_class='button'),
HTML('<a class="button alert" href="/">Annuler</a>'),
css_class='text-right',
)
)
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-17 00:00
# Generated by Django 1.11.3 on 2017-11-18 16:13
from __future__ import unicode_literals
import django.contrib.auth.models
......@@ -32,8 +32,8 @@ class Migration(migrations.Migration):
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('is_resp', models.BooleanField(default=False, verbose_name='Responsable dun territoire')),
('auth_access_alldata', models.BooleanField(default=False, verbose_name='Peut voir toutes les données')),
('auth_edit_alldata', models.BooleanField(default=False, verbose_name='Peut éditer toutes les données')),
('access_all_data', models.BooleanField(default=False, verbose_name='Peut voir toutes les données')),
('edit_all_data', models.BooleanField(default=False, verbose_name='Peut éditer toutes les données')),
('organism', models.CharField(blank=True, max_length=255, null=True, verbose_name='Organisme')),
('home_phone', models.CharField(blank=True, max_length=50, null=True, verbose_name='Numéro de téléphone fixe')),
('mobile_phone', models.CharField(blank=True, max_length=50, null=True, verbose_name='Numéro de téléphone portable')),
......
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-17 00:00
# Generated by Django 1.11.3 on 2017-11-18 16:13
from __future__ import unicode_literals
from django.db import migrations, models
......@@ -10,10 +10,10 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0008_alter_user_username_max_length'),
('accounts', '0001_initial'),
('management', '0001_initial'),
('auth', '0008_alter_user_username_max_length'),
('geodata', '0001_initial'),
('management', '0001_initial'),
]
operations = [
......
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-19 00:08
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20171118_1713'),
]
operations = [
migrations.AddField(
model_name='user',
name='creator',
field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
File mode changed from 100644 to 100755
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.contrib.gis.db import models
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from geodata.models import Territory
......@@ -9,12 +10,26 @@ from management.models import CatchAuth
# Create your models here.
# def generate_username(first_name, last_name):
# val = "{0}{1}".format(first_name[0], last_name).lower()
# x = 0
# while True:
# if x == 0 and User.objects.filter(username=val).count() == 0:
# return val
# else:
# new_val = "{0}{1}".format(val, x)
# x += 1
# if User.objects.filter(username=new_val).count() == 0:
# return new_val
# if x > 1000000:
# raise Exception("Name is super popular!")
class User(AbstractUser):
is_resp = models.BooleanField(default=False, verbose_name=_('Responsable d''un territoire'))
coord_territory = models.ManyToManyField(Territory, blank=True,
verbose_name=_('Territoires du rôle de coordinateur'))
auth_access_alldata = models.BooleanField(default=False, verbose_name=_('Peut voir toutes les données'))
auth_edit_alldata = models.BooleanField(default=False, verbose_name=_('Peut éditer toutes les données'))
access_all_data = models.BooleanField(default=False, verbose_name=_('Peut voir toutes les données'))
edit_all_data = models.BooleanField(default=False, verbose_name=_('Peut éditer toutes les données'))
catchauth = models.ManyToManyField(
CatchAuth,
blank=True, verbose_name=_('Authorisations de capture'))
......@@ -32,14 +47,26 @@ class User(AbstractUser):
comment = models.TextField(blank=True, null=True, verbose_name=_('Commentaire'))
id_bdsource = models.CharField(max_length=100, blank=True, null=True)
bdsource = models.CharField(max_length=100, blank=True, null=True)
geom = models.PointField(srid=settings.GEODATA_SRID, blank=True, null=True, verbose_name=_('Localisation géographique'))
geom = models.PointField(srid=settings.GEODATA_SRID, blank=True, null=True,
verbose_name=_('Localisation géographique'))
timestamp_create = models.DateTimeField(
auto_now_add=True, editable=False)
timestamp_update = models.DateTimeField(
auto_now=True, editable=False)
creator = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, db_index=True, editable=False)
def save(self, *args, **kwargs):
# self.username = generate_username(self.first_name,self.last_name)
# self.creator = current_user()
super(User, self).save(*args, **kwargs)
def __str__(self):
return self.username
def get_absolute_url(self):
# return reverse('user_detail', kwargs={'pk': self.id_user})
return reverse_lazy('home')
class Meta:
verbose_name_plural = "Détails des utilisateurs"
File mode changed from 100644 to 100755
from django.conf.urls import url
from .views import UserCreate, change_password
urlpatterns = [
url(r'^create/$', UserCreate.as_view(), name='user_create'),
url(r'^password/$', change_password, name='change_password'),
]
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import CreateView
from django.shortcuts import redirect
# Create your views here.
from .forms import UserCreateForm, PasswordUpdateForm
from .models import User
class ManageAccountAuthMixin(LoginRequiredMixin):
'''
Classe mixin de vérification que l'utilisateur possède les droits de modifier la donnée:
Soit il est créateur de la donnée,
Soit il dispose de l'authorisation de modifier toutes les données ( :get_user_model():access_all_data is True)
'''
def dispatch(self, request, *args, **kwargs):
user = request.user
if user.is_authenticated and (user.is_resp or user.access_all_data or user.edit_all_data or user.is_staff or user.is_superuser):
print('access granted')
return super(ManageAccountAuthMixin, self).dispatch(request, *args, **kwargs)
else:
return redirect('home')
class UserCreate(ManageAccountAuthMixin, CreateView):
"""Create view for the Place model."""
model = User
form_class = UserCreateForm
template_name = 'leaflet_form.html'
def form_valid(self, form):
form.instance.creator = self.request.user
return super(UserCreate, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(UserCreate, self).get_context_data(**kwargs)
context['title'] = '<h1><i class="fi-torsos"></i> Création d\'un utilisateur</h1>'
return context
@login_required()
def change_password(request):
form = PasswordUpdateForm(user=request.user)
title = _('<h1><i class="fi-lock"></i> Modifier son mot de passe</h1>')
if request.method == 'POST':
form = PasswordUpdateForm(user=request.user, data=request.POST)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return render(request, 'normal_form.html', {
'form': form, 'title': title,
})
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
......@@ -10,13 +10,6 @@ urlpatterns = [
url(r'^place.geojson$',
login_required(GeoJSONLayerView.as_view(model=Place, properties=('name', 'pk', 'municipality'), simplify=0.5)),
name='geodata_place'),
# url(r'^place.geojson$', GeoJSONPlaceData.as_view(),
# name='geodata_place'),
# url(r'^place.geojson$', GeoJSONData.as_view(model=Place, properties=('name', 'pk', 'municipality')),
# name='geodata_place'),
# url(r'^place/(?P<z>\d+)/(?P<x>\d+)/(?P<y>\d+).geojson$',
# TiledGeoJSONData.as_view(model=Place, trim_to_boundary=True, properties=('name', 'pk', 'municipality')),
# name='geodata_place_tile'),
url(r'^municipality.geojson$', login_required(
GeoJSONLayerView.as_view(model=Municipality, precision=3, simplify=0.5, properties=('name', 'code'))),
name='geodata_municipality'),
......
......@@ -86,7 +86,7 @@ def PlaceAsGeoJSON(request):
'''
loggeduser = request.user
userdetail = get_user_model().objects.get(id=loggeduser.id)
if userdetail.auth_access_alldata == True:
if userdetail.access_all_data == True:
print('Chargement de la carte pour l\'utilisateur avec accès total')
place_list = Place.objects.all()
elif userdetail.is_resp:
......
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-17 00:00
# Generated by Django 1.11.3 on 2017-11-18 16:13
from __future__ import unicode_literals
import ckeditor.fields
......
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from .views import actus, actus_detail
urlpatterns = [
url(r'^$', actus, name='home'),
url(r'^actus/(?P<pk>\d+)$', actus_detail, name='actus_detail'),
]
from django.shortcuts import render
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from .models import Actu
# Create your views here.
# class Actus(ListView):
# model = Actu
#
def actus(request):
"""
Vue de la page d'accueil listant les actualités du site par ordre décroissant de date de mise à jour.
"""
lastactus = Actu.objects.filter(
timestamp_update__lte=timezone.now()).order_by('-timestamp_update')
return render(request, 'home.html', {'lastactus': lastactus})
def actus_detail(request, pk):
"""
Vue détaillée d'une actualité du site.
"""
actusdetail = get_object_or_404(Actu, pk=pk)
return render(request, 'actus.html', {'actusdetail': actusdetail})
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
......@@ -45,9 +45,9 @@ INSTALLED_APPS = [
'django.contrib.admindocs',
'haystack',
'debug_toolbar',
'accounts',
'geodata',
'management',
'accounts',
'dicts',
'sights',
'blog',
......@@ -80,7 +80,7 @@ TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'webview/template'),
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
......@@ -108,10 +108,10 @@ WSGI_APPLICATION = 'dbchiro.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'dbchirodjango', # Indiquez ici le nom de la base de données
'USER': 'dbadmin',
'NAME': 'dbchirodb', # Indiquez ici le nom de la base de données
'USER': 'dbchiro',
# Changer dbadmin par l'identifiant du superutilisateur postgresql créé pour gérer la base de données
'PASSWORD': 'dbadminpasswd', # Changer password par le mot de passe du superutilisateur
'PASSWORD': 'dbpassword', # Changer password par le mot de passe du superutilisateur
'HOST': '127.0.0.1',
'PORT': '5432', # Changer password par le mot de passe du superutilisateur
}
......
......@@ -28,11 +28,14 @@ urlpatterns = [
{'template_name': 'login.html'}, name='login'),
url(r'^logout/$', auth_views.logout,
{'template_name': 'logout.html'}, name='logout'),
url(r'^dbgestion/', admin.site.urls),
url(r'^dbgestion/doc/', include('django.contrib.admindocs.urls'),
url(r'^admin/', admin.site.urls),
url(r'^admin/doc/', include('django.contrib.admindocs.urls'),
name='dbgestion-doc'),
url(r'', include('webview.urls')),
url(r'^accounts/', include('accounts.urls')),
url(r'', include('blog.urls')),
url(r'', include('sights.urls')),
url(r'^api/', include('api.urls')),
] + static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
......
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-17 00:00
# Generated by Django 1.11.3 on 2017-11-18 16:13
from __future__ import unicode_literals
from django.db import migrations, models
......@@ -227,8 +227,8 @@ class Migration(migrations.Migration):
('month_end', models.IntegerField()),
],
options={
'ordering': ['id'],
'verbose_name_plural': 'Catégories des périodes du cycle annuel',
'ordering': ['id'],
},
),
migrations.CreateModel(
......@@ -462,8 +462,8 @@ class Migration(migrations.Migration):
('descr', models.CharField(max_length=200)),
],
options={
'ordering': ['category', 'code'],
'verbose_name_plural': 'Catégories des types de localités',
'ordering': ['category', 'code'],
},
),
]
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-17 00:00
# Generated by Django 1.11.3 on 2017-11-18 16:13
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
......
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-17 00:00
# Generated by Django 1.11.3 on 2017-11-18 16:13
from __future__ import unicode_literals
from django.conf import settings
......@@ -73,9 +73,9 @@ class Migration(migrations.Migration):
('creator', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'Etudes',
'ordering': ['-timestamp_create'],
'verbose_name': 'Etude',
'verbose_name_plural': 'Etudes',
},
),
migrations.AddIndex(
......
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
File mode changed from 100644 to 100755
......@@ -2,19 +2,19 @@ from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView