Upgrade de Django vers la version 1.2.5
[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
fdcf5874 3from chercheurs.forms import ChercheurSearchForm, SetPasswordForm, ChercheurFormGroup, AuthenticationForm
43ed73e7 4from chercheurs.models import Chercheur
695930dd 5from chercheurs.utils import get_django_user_for_email
fdcf5874 6from datamaster_modeles.models import Etablissement, Region
fa6a2a07 7from django.conf import settings
932eef9a 8from django.shortcuts import render_to_response
fdcf5874 9from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseNotFound
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
fdcf5874 16from django.contrib.auth.decorators import login_required
fa6a2a07 17from django.contrib.sites.models import RequestSite, Site
219710da 18from django.utils import simplejson
43ed73e7 19from django.utils.http import int_to_base36, base36_to_int
a7b16ec9 20from django.views.decorators.cache import never_cache
72923b8e 21from django.contrib.auth import authenticate, login
3eb00212 22from django.shortcuts import get_object_or_404
fdcf5874 23from savoirs.models import PageStatique, Discipline
510b5321 24
f0692c02 25def index(request):
f8c16b3d 26 """Répertoire des chercheurs"""
fdcf5874
EMS
27 search_form = ChercheurSearchForm(request.GET)
28 search = search_form.save(commit=False)
29 chercheurs = search.run().select_related('etablissement')
7020ea3d
EMS
30 sort = request.GET.get('tri')
31 if sort is not None and sort.endswith('_desc'):
32 sort = sort[:-5]
33 direction = '-'
34 else:
35 direction = ''
36 if sort == 'nom':
acd5cd8f 37 chercheurs = chercheurs.order_by_nom(direction)
7020ea3d 38 elif sort == 'etablissement':
acd5cd8f 39 chercheurs = chercheurs.order_by_etablissement(direction)
7020ea3d 40 elif sort == 'pays':
acd5cd8f 41 chercheurs = chercheurs.order_by_pays(direction)
7020ea3d
EMS
42 else:
43 chercheurs = chercheurs.order_by('-date_modification')
f09bc1c6
EMS
44
45 try:
46 p = PageStatique.objects.get(id='repertoire')
47 entete = p.contenu
48 except PageStatique.DoesNotExist:
49 entete = u'<h1>Répertoire des chercheurs</h1>'
7020ea3d 50
9f7c169e 51 nb_chercheurs = chercheurs.count()
fdcf5874 52
3efbacbe 53 return render_to_response("chercheurs/index.html",
f09bc1c6
EMS
54 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs,
55 search_form=search_form, entete=entete),
3efbacbe 56 context_instance=RequestContext(request))
588d6b93 57
f0692c02 58def inscription(request):
932eef9a 59 if request.method == 'POST':
a7b16ec9
EMS
60 forms = ChercheurFormGroup(request.POST)
61 if forms.is_valid():
43ed73e7
EMS
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'))
932eef9a 70 else:
a7b16ec9 71 forms = ChercheurFormGroup()
932eef9a 72
a7b16ec9
EMS
73 return render_to_response("chercheurs/inscription.html",
74 dict(forms=forms),
75 context_instance=RequestContext(request))
9af73c99 76
43ed73e7
EMS
77def activation(request, id_base36, token):
78 """Activation d'un chercheur"""
79 id = base36_to_int(id_base36)
3e556e66 80 chercheur = get_object_or_404(Chercheur.all_objects, id=id)
43ed73e7
EMS
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()
695930dd
EMS
90 user = get_django_user_for_email(email)
91 user.set_password(password)
92 user.save()
43ed73e7
EMS
93
94 # Auto-login
3e556e66 95 auth_login(request, authenticate(username=email, password=password))
43ed73e7
EMS
96 return HttpResponseRedirect(url('chercheurs.views.perso'))
97 else:
98 form = SetPasswordForm()
99 else:
100 form = None
101 validlink = False
102 return render_to_response('chercheurs/activation.html', dict(form=form, validlink=validlink),
103 context_instance=RequestContext(request))
104
518d0b44 105@chercheur_required
8baa2a56
EMS
106def desinscription(request):
107 """Désinscription du chercheur"""
518d0b44 108 chercheur = request.chercheur
8baa2a56
EMS
109 if request.method == 'POST':
110 if request.POST.get('confirmer'):
13ec4813
EMS
111 chercheur.actif = False
112 chercheur.save()
8baa2a56
EMS
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
518d0b44 121@chercheur_required
a7b16ec9 122@never_cache
f0692c02 123def edit(request):
b3e1079e 124 """Edition d'un chercheur"""
518d0b44 125 chercheur = request.chercheur
b3e1079e 126 if request.method == 'POST':
a7b16ec9
EMS
127 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
128 if forms.is_valid():
129 forms.save()
91112855
EMS
130 request.flash['message'] = "Votre fiche a bien été enregistrée."
131 return HttpResponseRedirect(url('chercheurs.views.perso'))
b3e1079e 132 else:
a7b16ec9 133 forms = ChercheurFormGroup(chercheur=chercheur)
b3e1079e 134
a7b16ec9
EMS
135 return render_to_response("chercheurs/edit.html",
136 dict(forms=forms, chercheur=chercheur),
595ab4d6 137 context_instance=RequestContext(request))
b3e1079e 138
518d0b44 139@chercheur_required
f0692c02 140def perso(request):
0d9d1c4d 141 """Espace chercheur (espace personnel du chercheur)"""
518d0b44 142 chercheur = request.chercheur
2a36714f 143 modification = request.GET.get('modification')
e4d01d1d
EMS
144 return render_to_response("chercheurs/perso.html",
145 dict(chercheur=chercheur, modification=modification),
518d0b44 146 context_instance=RequestContext(request))
da091176 147
f0692c02 148def retrieve(request, id):
da091176 149 """Fiche du chercheur"""
3eb00212 150 chercheur = get_object_or_404(Chercheur, id=id)
e4d01d1d
EMS
151 return render_to_response("chercheurs/retrieve.html",
152 dict(chercheur=chercheur),
c1b134f8 153 context_instance=RequestContext(request))
d9885bf7 154
f0692c02 155def conversion(request):
c1b134f8
EMS
156 return render_to_response("chercheurs/conversion.html", {},
157 context_instance=RequestContext(request))
8baa2a56 158
e836f6f7 159def etablissements_autocomplete(request, pays=None):
219710da 160 term = request.GET.get('term')
e76f8899 161 noms = Etablissement.objects.all().filter(membre=True, actif=True)
e836f6f7
EMS
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])
219710da
EMS
167 json = simplejson.dumps(noms)
168 return HttpResponse(json, mimetype='application/json')
fa6a2a07
EMS
169
170def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
171 "The Django login view, but using a custom form."
172 redirect_to = request.REQUEST.get(redirect_field_name, '')
173
174 if request.method == "POST":
175 form = AuthenticationForm(data=request.POST)
176 if form.is_valid():
177 # Light security check -- make sure redirect_to isn't garbage.
178 if not redirect_to or ' ' in redirect_to:
179 redirect_to = settings.LOGIN_REDIRECT_URL
180
181 # Heavier security check -- redirects to http://example.com should
182 # not be allowed, but things like /view/?param=http://example.com
183 # should be allowed. This regex checks if there is a '//' *before* a
184 # question mark.
185 elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
186 redirect_to = settings.LOGIN_REDIRECT_URL
187
188 # Okay, security checks complete. Log the user in.
189 auth_login(request, form.get_user())
190
191 if request.session.test_cookie_worked():
192 request.session.delete_test_cookie()
193
194 return HttpResponseRedirect(redirect_to)
195
196 else:
197 form = AuthenticationForm(request)
198 request.session.set_test_cookie()
199
200 if Site._meta.installed:
201 current_site = Site.objects.get_current()
202 else:
203 current_site = RequestSite(request)
204
205 return render_to_response(template_name, {
206 'form': form,
207 redirect_field_name: redirect_to,
208 'site': current_site,
209 'site_name': current_site.name,
210 }, context_instance=RequestContext(request))
211login = never_cache(login)