523dfab591ea4a02a16424b8c191bd1092ce132b
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / chercheurs / views.py
1 # -*- encoding: utf-8 -*-
2 import hashlib
3 from chercheurs.decorators import chercheur_required
4 from chercheurs.forms import RepertoireSearchForm, SetPasswordForm, ChercheurFormGroup
5 from chercheurs.models import Chercheur
6 from datamaster_modeles.models import Etablissement
7 from django.shortcuts import render_to_response
8 from django.http import HttpResponseRedirect, HttpResponse
9 from django.template import Context, RequestContext
10 from django.template.loader import get_template
11 from django.core.urlresolvers import reverse as url
12 from django.core.mail import send_mail
13 from django.conf import settings
14 from django.contrib.auth.tokens import default_token_generator as token_generator
15 from django.contrib.sites.models import RequestSite
16 from django.utils import simplejson
17 from django.utils.http import int_to_base36, base36_to_int
18 from django.views.decorators.cache import never_cache
19
20 from django.forms.models import inlineformset_factory
21
22 from auf_references_client.models import Discipline, TypeImplantation
23 from models import Personne, Groupe, ChercheurGroupe
24
25 from django.contrib.auth import authenticate, login
26 from django.contrib.auth.decorators import login_required
27 from django.contrib.auth.models import User
28
29 from django.db.models import Q
30 from django.shortcuts import get_object_or_404
31
32 from django.utils.translation import ugettext_lazy as _
33
34 def index(request):
35 """Répertoire des chercheurs"""
36 search_form = RepertoireSearchForm(request.GET)
37 chercheurs = search_form.get_query_set().select_related('etablissement')
38 sort = request.GET.get('tri')
39 if sort is not None and sort.endswith('_desc'):
40 sort = sort[:-5]
41 direction = '-'
42 else:
43 direction = ''
44 if sort == 'nom':
45 chercheurs = chercheurs.order_by_nom(direction)
46 elif sort == 'etablissement':
47 chercheurs = chercheurs.order_by_etablissement(direction)
48 elif sort == 'pays':
49 chercheurs = chercheurs.order_by_pays(direction)
50 else:
51 chercheurs = chercheurs.order_by('-date_modification')
52
53 nb_chercheurs = chercheurs.count()
54 return render_to_response("chercheurs/index.html",
55 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs, search_form=search_form),
56 context_instance=RequestContext(request))
57
58 def inscription(request):
59 if request.method == 'POST':
60 forms = ChercheurFormGroup(request.POST)
61 if forms.is_valid():
62 chercheur = forms.save()
63 id_base36 = int_to_base36(chercheur.id)
64 token = chercheur.activation_token()
65 template = get_template('chercheurs/activation_email.txt')
66 domain = RequestSite(request).domain
67 message = template.render(Context(dict(chercheur=chercheur, id_base36=id_base36, token=token, domain=domain)))
68 send_mail('Votre inscription à Savoirs en partage', message, None, [chercheur.courriel])
69 return HttpResponseRedirect(url('chercheurs-inscription-faite'))
70 else:
71 forms = ChercheurFormGroup()
72
73 return render_to_response("chercheurs/inscription.html",
74 dict(forms=forms),
75 context_instance=RequestContext(request))
76
77 def activation(request, id_base36, token):
78 """Activation d'un chercheur"""
79 id = base36_to_int(id_base36)
80 chercheur = get_object_or_404(Chercheur, id=id)
81 if token == chercheur.activation_token():
82 validlink = True
83 if request.method == 'POST':
84 form = SetPasswordForm(request.POST)
85 if form.is_valid():
86 password = form.cleaned_data['password']
87 email = chercheur.courriel
88 chercheur.actif = True
89 chercheur.save()
90 chercheur.user.set_password(password)
91 chercheur.user.save()
92
93 # Auto-login
94 login(request, authenticate(username=email, password=password))
95 return HttpResponseRedirect(url('chercheurs.views.perso'))
96 else:
97 form = SetPasswordForm()
98 else:
99 form = None
100 validlink = False
101 return render_to_response('chercheurs/activation.html', dict(form=form, validlink=validlink),
102 context_instance=RequestContext(request))
103
104 @chercheur_required
105 def desinscription(request):
106 """Désinscription du chercheur"""
107 chercheur = request.chercheur
108 if request.method == 'POST':
109 if request.POST.get('confirmer'):
110 chercheur.actif = False
111 chercheur.save()
112 User.objects.filter(username=chercheur.courriel).delete()
113 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
114 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
115 else:
116 request.flash['message'] = "Opération annulée."
117 return HttpResponseRedirect(url('chercheurs.views.perso'))
118 return render_to_response("chercheurs/desinscription.html", {},
119 context_instance=RequestContext(request))
120
121 @chercheur_required
122 @never_cache
123 def edit(request):
124 """Edition d'un chercheur"""
125 chercheur = request.chercheur
126 if request.method == 'POST':
127 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
128 if forms.is_valid():
129 forms.save()
130 request.flash['message'] = "Votre fiche a bien été enregistrée."
131 return HttpResponseRedirect(url('chercheurs.views.perso'))
132 else:
133 forms = ChercheurFormGroup(chercheur=chercheur)
134
135 return render_to_response("chercheurs/edit.html",
136 dict(forms=forms, chercheur=chercheur),
137 context_instance=RequestContext(request))
138
139 @chercheur_required
140 def perso(request):
141 """Espace chercheur (espace personnel du chercheur)"""
142 chercheur = request.chercheur
143 modification = request.GET.get('modification')
144 return render_to_response("chercheurs/perso.html",
145 dict(chercheur=chercheur, modification=modification),
146 context_instance=RequestContext(request))
147
148 def retrieve(request, id):
149 """Fiche du chercheur"""
150 chercheur = get_object_or_404(Chercheur, id=id)
151 return render_to_response("chercheurs/retrieve.html",
152 dict(chercheur=chercheur),
153 context_instance=RequestContext(request))
154
155 def conversion(request):
156 return render_to_response("chercheurs/conversion.html", {},
157 context_instance=RequestContext(request))
158
159 def etablissements_autocomplete(request, pays=None):
160 term = request.GET.get('term')
161 noms = Etablissement.objects.all().filter(membre=True)
162 for word in term.split():
163 noms = noms.filter(nom__icontains=word)
164 if pays:
165 noms = noms.filter(pays=pays)
166 noms = list(noms.values_list('nom', flat=True)[:20])
167 json = simplejson.dumps(noms)
168 return HttpResponse(json, mimetype='application/json')