Ajouté les filtres les plus faciles.
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / chercheurs / views.py
CommitLineData
588d6b93 1# -*- encoding: utf-8 -*-
518d0b44 2from chercheurs.decorators import chercheur_required
fa6a2a07 3from chercheurs.forms import RepertoireSearchForm, SetPasswordForm, ChercheurFormGroup, AuthenticationForm
43ed73e7 4from chercheurs.models import Chercheur
695930dd 5from chercheurs.utils import get_django_user_for_email
43ed73e7 6from datamaster_modeles.models import Etablissement
fa6a2a07 7from django.conf import settings
932eef9a 8from django.shortcuts import render_to_response
0e9597af 9from django.http import HttpResponseRedirect, HttpResponse
932eef9a 10from django.template import Context, RequestContext
e427f068 11from django.template.loader import get_template
51515982 12from django.core.urlresolvers import reverse as url
0e9597af 13from django.core.mail import send_mail
fa6a2a07
EMS
14from django.contrib.auth import REDIRECT_FIELD_NAME
15from django.contrib.auth import login as auth_login
16from django.contrib.sites.models import RequestSite, Site
219710da 17from django.utils import simplejson
43ed73e7 18from django.utils.http import int_to_base36, base36_to_int
a7b16ec9 19from django.views.decorators.cache import never_cache
72923b8e 20from django.contrib.auth import authenticate, login
3eb00212 21from django.shortcuts import get_object_or_404
f09bc1c6 22from savoirs.models import PageStatique
510b5321 23
f0692c02 24def index(request):
f8c16b3d 25 """Répertoire des chercheurs"""
f0692c02 26 search_form = RepertoireSearchForm(request.GET)
13ec4813 27 chercheurs = search_form.get_query_set().select_related('etablissement')
7020ea3d
EMS
28 sort = request.GET.get('tri')
29 if sort is not None and sort.endswith('_desc'):
30 sort = sort[:-5]
31 direction = '-'
32 else:
33 direction = ''
34 if sort == 'nom':
acd5cd8f 35 chercheurs = chercheurs.order_by_nom(direction)
7020ea3d 36 elif sort == 'etablissement':
acd5cd8f 37 chercheurs = chercheurs.order_by_etablissement(direction)
7020ea3d 38 elif sort == 'pays':
acd5cd8f 39 chercheurs = chercheurs.order_by_pays(direction)
7020ea3d
EMS
40 else:
41 chercheurs = chercheurs.order_by('-date_modification')
f09bc1c6
EMS
42
43 try:
44 p = PageStatique.objects.get(id='repertoire')
45 entete = p.contenu
46 except PageStatique.DoesNotExist:
47 entete = u'<h1>Répertoire des chercheurs</h1>'
7020ea3d 48
9f7c169e 49 nb_chercheurs = chercheurs.count()
3efbacbe 50 return render_to_response("chercheurs/index.html",
f09bc1c6
EMS
51 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs,
52 search_form=search_form, entete=entete),
3efbacbe 53 context_instance=RequestContext(request))
588d6b93 54
f0692c02 55def inscription(request):
932eef9a 56 if request.method == 'POST':
a7b16ec9
EMS
57 forms = ChercheurFormGroup(request.POST)
58 if forms.is_valid():
43ed73e7
EMS
59 chercheur = forms.save()
60 id_base36 = int_to_base36(chercheur.id)
61 token = chercheur.activation_token()
62 template = get_template('chercheurs/activation_email.txt')
63 domain = RequestSite(request).domain
64 message = template.render(Context(dict(chercheur=chercheur, id_base36=id_base36, token=token, domain=domain)))
65 send_mail('Votre inscription à Savoirs en partage', message, None, [chercheur.courriel])
66 return HttpResponseRedirect(url('chercheurs-inscription-faite'))
932eef9a 67 else:
a7b16ec9 68 forms = ChercheurFormGroup()
932eef9a 69
a7b16ec9
EMS
70 return render_to_response("chercheurs/inscription.html",
71 dict(forms=forms),
72 context_instance=RequestContext(request))
9af73c99 73
43ed73e7
EMS
74def activation(request, id_base36, token):
75 """Activation d'un chercheur"""
76 id = base36_to_int(id_base36)
77 chercheur = get_object_or_404(Chercheur, id=id)
78 if token == chercheur.activation_token():
79 validlink = True
80 if request.method == 'POST':
81 form = SetPasswordForm(request.POST)
82 if form.is_valid():
83 password = form.cleaned_data['password']
84 email = chercheur.courriel
85 chercheur.actif = True
86 chercheur.save()
695930dd
EMS
87 user = get_django_user_for_email(email)
88 user.set_password(password)
89 user.save()
43ed73e7
EMS
90
91 # Auto-login
92 login(request, authenticate(username=email, password=password))
93 return HttpResponseRedirect(url('chercheurs.views.perso'))
94 else:
95 form = SetPasswordForm()
96 else:
97 form = None
98 validlink = False
99 return render_to_response('chercheurs/activation.html', dict(form=form, validlink=validlink),
100 context_instance=RequestContext(request))
101
518d0b44 102@chercheur_required
8baa2a56
EMS
103def desinscription(request):
104 """Désinscription du chercheur"""
518d0b44 105 chercheur = request.chercheur
8baa2a56
EMS
106 if request.method == 'POST':
107 if request.POST.get('confirmer'):
13ec4813
EMS
108 chercheur.actif = False
109 chercheur.save()
8baa2a56
EMS
110 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
111 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
112 else:
113 request.flash['message'] = "Opération annulée."
114 return HttpResponseRedirect(url('chercheurs.views.perso'))
115 return render_to_response("chercheurs/desinscription.html", {},
116 context_instance=RequestContext(request))
117
518d0b44 118@chercheur_required
a7b16ec9 119@never_cache
f0692c02 120def edit(request):
b3e1079e 121 """Edition d'un chercheur"""
518d0b44 122 chercheur = request.chercheur
b3e1079e 123 if request.method == 'POST':
a7b16ec9
EMS
124 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
125 if forms.is_valid():
126 forms.save()
91112855
EMS
127 request.flash['message'] = "Votre fiche a bien été enregistrée."
128 return HttpResponseRedirect(url('chercheurs.views.perso'))
b3e1079e 129 else:
a7b16ec9 130 forms = ChercheurFormGroup(chercheur=chercheur)
b3e1079e 131
a7b16ec9
EMS
132 return render_to_response("chercheurs/edit.html",
133 dict(forms=forms, chercheur=chercheur),
595ab4d6 134 context_instance=RequestContext(request))
b3e1079e 135
518d0b44 136@chercheur_required
f0692c02 137def perso(request):
0d9d1c4d 138 """Espace chercheur (espace personnel du chercheur)"""
518d0b44 139 chercheur = request.chercheur
2a36714f 140 modification = request.GET.get('modification')
e4d01d1d
EMS
141 return render_to_response("chercheurs/perso.html",
142 dict(chercheur=chercheur, modification=modification),
518d0b44 143 context_instance=RequestContext(request))
da091176 144
f0692c02 145def retrieve(request, id):
da091176 146 """Fiche du chercheur"""
3eb00212 147 chercheur = get_object_or_404(Chercheur, id=id)
e4d01d1d
EMS
148 return render_to_response("chercheurs/retrieve.html",
149 dict(chercheur=chercheur),
c1b134f8 150 context_instance=RequestContext(request))
d9885bf7 151
f0692c02 152def conversion(request):
c1b134f8
EMS
153 return render_to_response("chercheurs/conversion.html", {},
154 context_instance=RequestContext(request))
8baa2a56 155
e836f6f7 156def etablissements_autocomplete(request, pays=None):
219710da 157 term = request.GET.get('term')
e76f8899 158 noms = Etablissement.objects.all().filter(membre=True, actif=True)
e836f6f7
EMS
159 for word in term.split():
160 noms = noms.filter(nom__icontains=word)
161 if pays:
162 noms = noms.filter(pays=pays)
163 noms = list(noms.values_list('nom', flat=True)[:20])
219710da
EMS
164 json = simplejson.dumps(noms)
165 return HttpResponse(json, mimetype='application/json')
fa6a2a07
EMS
166
167def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
168 "The Django login view, but using a custom form."
169 redirect_to = request.REQUEST.get(redirect_field_name, '')
170
171 if request.method == "POST":
172 form = AuthenticationForm(data=request.POST)
173 if form.is_valid():
174 # Light security check -- make sure redirect_to isn't garbage.
175 if not redirect_to or ' ' in redirect_to:
176 redirect_to = settings.LOGIN_REDIRECT_URL
177
178 # Heavier security check -- redirects to http://example.com should
179 # not be allowed, but things like /view/?param=http://example.com
180 # should be allowed. This regex checks if there is a '//' *before* a
181 # question mark.
182 elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
183 redirect_to = settings.LOGIN_REDIRECT_URL
184
185 # Okay, security checks complete. Log the user in.
186 auth_login(request, form.get_user())
187
188 if request.session.test_cookie_worked():
189 request.session.delete_test_cookie()
190
191 return HttpResponseRedirect(redirect_to)
192
193 else:
194 form = AuthenticationForm(request)
195 request.session.set_test_cookie()
196
197 if Site._meta.installed:
198 current_site = Site.objects.get_current()
199 else:
200 current_site = RequestSite(request)
201
202 return render_to_response(template_name, {
203 'form': form,
204 redirect_field_name: redirect_to,
205 'site': current_site,
206 'site_name': current_site.name,
207 }, context_instance=RequestContext(request))
208login = never_cache(login)
209