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