Utilisé l'héritage de modèles entre Chercheur et Personne
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / chercheurs / views.py
CommitLineData
588d6b93 1# -*- encoding: utf-8 -*-
5ecd9e43 2import hashlib
932eef9a 3from django.shortcuts import render_to_response
0e9597af 4from django.http import HttpResponseRedirect, HttpResponse
932eef9a 5from django.template import Context, RequestContext
e427f068 6from django.template.loader import get_template
51515982 7from django.core.urlresolvers import reverse as url
0e9597af
AJ
8from django.core.mail import send_mail
9from django.conf import settings
219710da 10from django.utils import simplejson
a7b16ec9 11from django.views.decorators.cache import never_cache
e8e9e4fd 12
932eef9a 13from forms import *
e8e9e4fd 14from django.forms.models import inlineformset_factory
932eef9a
AJ
15
16from auf_references_client.models import Discipline, TypeImplantation
13ec4813 17from models import Personne, Groupe, ChercheurGroupe
932eef9a 18
72923b8e 19from django.contrib.auth import authenticate, login
9af73c99 20from django.contrib.auth.decorators import login_required
72923b8e 21from django.contrib.auth.forms import AuthenticationForm as OriginalAuthenticationForm
8baa2a56 22from django.contrib.auth.models import User
13146d99 23
510b5321 24from django.db.models import Q
3eb00212 25from django.shortcuts import get_object_or_404
510b5321 26
c18af6bd 27from django.utils.translation import ugettext_lazy as _
c18af6bd 28
0e9597af
AJ
29#TODO: Migrer tout ce qui a rapport aux users dans une nouvelle app
30
c18af6bd 31class AuthenticationForm(OriginalAuthenticationForm):
b5af3133 32 username = forms.CharField(label='Adresse électronique', max_length=255)
c18af6bd 33
f0692c02 34def send_password(request):
0e9597af
AJ
35 if request.method == "POST":
36 form = SendPasswordForm(data=request.POST)
37 if form.is_valid():
13ec4813 38 u = Personne.objects.get(courriel=form.cleaned_data['email'])
92990258 39 code = u.get_new_password_code()
d0c97f36 40 link = "%s/accounts/new_password/%s/%s/" % (settings.SITE_ROOT_URL, u.courriel, code)
e427f068
AJ
41
42 variables = { 'user': u,
43 'link': link,
206989d4
AJ
44 'SITE_ROOT_URL': settings.SITE_ROOT_URL,
45 'CONTACT_EMAIL': settings.CONTACT_EMAIL,
e427f068
AJ
46 }
47 t = get_template('accounts/email_password.html')
48 content = t.render(Context(variables))
49
0e9597af 50 send_mail('Savoirs en partage: changement de mot de passe',
e427f068 51 content, settings.CONTACT_EMAIL,
0e9597af
AJ
52 [u.courriel], fail_silently=False)
53 else:
54 form = SendPasswordForm()
55
56 variables = { 'form': form,
57 }
58 return render_to_response ("accounts/send_password.html", \
59 Context (variables),
60 context_instance = RequestContext(request))
e427f068 61
0e9597af 62def new_password(request, email, code):
13ec4813 63 u = Personne.objects.get(courriel=email)
92990258 64 original_code = u.get_new_password_code()
e427f068 65 message=""
0e9597af 66 if(code == original_code):
e427f068
AJ
67 if request.method == "POST":
68 form = NewPasswordForm(data=request.POST)
69 if form.is_valid():
92990258 70 u.set_password(form.cleaned_data['password'])
e427f068
AJ
71 u.save()
72 message = "Votre mot de passe a été modifié."
73 else:
74 form = NewPasswordForm()
0e9597af
AJ
75 else:
76 return HttpResponseRedirect('/')
e427f068
AJ
77 variables = { 'form': form,
78 'message': message,
0e9597af
AJ
79 }
80 return render_to_response ("accounts/new_password.html", \
81 Context (variables),
82 context_instance = RequestContext(request))
c18af6bd 83
e427f068 84@login_required()
f0692c02 85def change_password(request):
e427f068 86 context_instance = RequestContext(request)
13ec4813 87 u = context_instance['user_chercheur']
e427f068
AJ
88 message = ""
89 if request.method == "POST":
90 form = NewPasswordForm(data=request.POST)
91 if form.is_valid():
92990258 92 u.set_password(form.cleaned_data['password'])
e427f068
AJ
93 u.save()
94 message = "Votre mot de passe a été modifié."
95 else:
96 form = NewPasswordForm()
97 variables = { 'form': form,
98 'message': message,
99 }
100 return render_to_response ("accounts/new_password.html", \
101 Context (variables),
102 context_instance = RequestContext(request))
103
f0692c02 104def chercheur_login(request):
c18af6bd 105 "Displays the login form and handles the login action."
c18af6bd
AJ
106 if request.method == "POST":
107 form = AuthenticationForm(data=request.POST)
108 if form.is_valid():
c18af6bd
AJ
109 from django.contrib.auth import login
110 login(request, form.get_user())
111 if request.session.test_cookie_worked():
112 request.session.delete_test_cookie()
0539c4e2 113 return HttpResponseRedirect(url('chercheurs.views.perso'))
c18af6bd
AJ
114 else:
115 form = AuthenticationForm(request)
116 request.session.set_test_cookie()
c1b134f8
EMS
117 return render_to_response('accounts/login.html', dict(form=form),
118 context_instance=RequestContext(request))
c18af6bd 119
f0692c02 120def index(request):
f8c16b3d 121 """Répertoire des chercheurs"""
f0692c02 122 search_form = RepertoireSearchForm(request.GET)
13ec4813 123 chercheurs = search_form.get_query_set().select_related('etablissement')
7020ea3d
EMS
124 sort = request.GET.get('tri')
125 if sort is not None and sort.endswith('_desc'):
126 sort = sort[:-5]
127 direction = '-'
128 else:
129 direction = ''
130 if sort == 'nom':
13ec4813 131 chercheurs = chercheurs.order_by(direction + 'nom', 'prenom', '-date_modification')
7020ea3d
EMS
132 elif sort == 'etablissement':
133 chercheurs = chercheurs.extra(select=dict(nom_etablissement='IFNULL(ref_etablissement.nom, chercheurs_chercheur.etablissement_autre_nom)'),
134 order_by=[direction + 'nom_etablissement', '-date_modification'])
135 elif sort == 'pays':
39ab0656
EMS
136 chercheurs = chercheurs.extra(select=dict(
137 pays_etablissement='(SELECT nom FROM ref_pays WHERE ref_pays.code = IFNULL(ref_etablissement.pays, chercheurs_chercheur.etablissement_autre_pays))'
138 ), order_by=[direction + 'pays_etablissement', '-date_modification'])
7020ea3d
EMS
139 else:
140 chercheurs = chercheurs.order_by('-date_modification')
141
9f7c169e 142 nb_chercheurs = chercheurs.count()
3efbacbe 143 return render_to_response("chercheurs/index.html",
e9b0d630 144 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs, search_form=search_form),
3efbacbe 145 context_instance=RequestContext(request))
588d6b93 146
f0692c02 147def inscription(request):
932eef9a 148 if request.method == 'POST':
a7b16ec9
EMS
149 forms = ChercheurFormGroup(request.POST)
150 if forms.is_valid():
151 forms.save()
152 # login automatique
13ec4813
EMS
153 login(request, authenticate(username=forms.chercheur.cleaned_data['courriel'],
154 password=forms.chercheur.cleaned_data['password']))
0539c4e2 155 return HttpResponseRedirect(url('chercheurs.views.perso'))
932eef9a 156 else:
a7b16ec9 157 forms = ChercheurFormGroup()
932eef9a 158
a7b16ec9
EMS
159 return render_to_response("chercheurs/inscription.html",
160 dict(forms=forms),
161 context_instance=RequestContext(request))
9af73c99 162
0e9597af 163@login_required()
8baa2a56
EMS
164def desinscription(request):
165 """Désinscription du chercheur"""
166 try:
13ec4813 167 chercheur = Chercheur.objects.get(courriel=request.user.email, actif=True)
8baa2a56
EMS
168 except Chercheur.DoesNotExist:
169 return HttpResponseRedirect(url('chercheurs.views.chercheur_login'))
170 if request.method == 'POST':
171 if request.POST.get('confirmer'):
13ec4813
EMS
172 chercheur.actif = False
173 chercheur.save()
174 User.objects.filter(username=chercheur.courriel).delete()
8baa2a56
EMS
175 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
176 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
177 else:
178 request.flash['message'] = "Opération annulée."
179 return HttpResponseRedirect(url('chercheurs.views.perso'))
180 return render_to_response("chercheurs/desinscription.html", {},
181 context_instance=RequestContext(request))
182
183@login_required()
a7b16ec9 184@never_cache
f0692c02 185def edit(request):
b3e1079e
AJ
186 """Edition d'un chercheur"""
187 context_instance = RequestContext(request)
188 chercheur = context_instance['user_chercheur']
189 if request.method == 'POST':
a7b16ec9
EMS
190 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
191 if forms.is_valid():
192 forms.save()
0539c4e2 193 return HttpResponseRedirect(url('chercheurs.views.perso') + '?modification=1')
b3e1079e 194 else:
a7b16ec9 195 forms = ChercheurFormGroup(chercheur=chercheur)
b3e1079e 196
a7b16ec9
EMS
197 return render_to_response("chercheurs/edit.html",
198 dict(forms=forms, chercheur=chercheur),
595ab4d6 199 context_instance=RequestContext(request))
b3e1079e 200
0e9597af 201@login_required()
f0692c02 202def perso(request):
0d9d1c4d 203 """Espace chercheur (espace personnel du chercheur)"""
9af73c99
AJ
204 context_instance = RequestContext(request)
205 chercheur = context_instance['user_chercheur']
2a36714f 206 modification = request.GET.get('modification')
0d9d1c4d 207 if not chercheur:
0539c4e2 208 return HttpResponseRedirect(url('chercheurs.views.chercheur_login'))
e4d01d1d
EMS
209 return render_to_response("chercheurs/perso.html",
210 dict(chercheur=chercheur, modification=modification),
8baa2a56 211 context_instance=context_instance)
da091176 212
f0692c02 213def retrieve(request, id):
da091176 214 """Fiche du chercheur"""
3eb00212 215 chercheur = get_object_or_404(Chercheur, id=id)
e4d01d1d
EMS
216 return render_to_response("chercheurs/retrieve.html",
217 dict(chercheur=chercheur),
c1b134f8 218 context_instance=RequestContext(request))
d9885bf7 219
f0692c02 220def conversion(request):
c1b134f8
EMS
221 return render_to_response("chercheurs/conversion.html", {},
222 context_instance=RequestContext(request))
8baa2a56 223
e836f6f7 224def etablissements_autocomplete(request, pays=None):
219710da 225 term = request.GET.get('term')
e836f6f7
EMS
226 noms = Etablissement.objects.all()
227 for word in term.split():
228 noms = noms.filter(nom__icontains=word)
229 if pays:
230 noms = noms.filter(pays=pays)
231 noms = list(noms.values_list('nom', flat=True)[:20])
219710da
EMS
232 json = simplejson.dumps(noms)
233 return HttpResponse(json, mimetype='application/json')