from django.http import FileResponse, HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth.views import LoginView
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from django.db.models import Avg

from BasicData.templatetags.custom_tag_obj import get_ue_by_ufr_set, get_niveau_etudiant
from EspaceEnseignant.forms import AnneeFilterForm, SeanceFilterForm
from .forms import *
# Create your views here.
from BasicData.models import *
from BasicData.custom_fonctions import *
from BasicData.templatetags.custom_tag import get_credit_ue, get_etudiant_moyenne_ue, get_etudiant_moyenne_ue2, \
    decision_annuelle_etudiant, get_etudiant_not_validate_ue_prev
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib import messages
from datetime import datetime
from datetime import timedelta


@login_required(login_url='BasicData:login')
class HomeView(TemplateView):
    template_name = "EspaceEtudiant/home_content.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        etudiantUes = EtudiantUe.objects.filter(etudiant=self.request.user,
                                                parcoursSemestreUe__annee=Annee.objects.last())

        return context


@login_required(login_url='BasicData:login')
class NoteDetailView(TemplateView):
    template_name = "EspaceEtudiant/note-detail.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        ue = Ue.objects.get(id=kwargs['ue'])
        context['ue'] = ue
        moyenneUe = MoyenneUe.objects.filter(etudiant=self.request.user, ue=ue).last()
        moyenneEcues = []
        for ecue in ue.ecues.all():
            moy = MoyenneEcue.objects.filter(moyenneUe=moyenneUe, ecue=ecue).last()
            infos = [ecue, moy]
            moyenneEcues.append(infos)

        context['moyenneEcues'] = moyenneEcues
        return context


class EtudiantLoginView(LoginView):
    form = EtudiantLoginForm
    template_name = "EspaceEtudiant/login.html"
    next_page = "EspaceEtudiant:liste_etudiant_ue"
    redirect_authenticated_user = True
    redirect_field_name = next_page


@login_required(login_url='BasicData:login')
class NoteView(TemplateView):
    template_name = "EspaceEtudiant/liste_ue.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        parcoursSemestreUes = ParcoursSemestreUe.objects.filter(
            etudiantUes__etudiant=self.request.user, annee=Annee.objects.last()
        )

        parcoursSemestre = parcoursSemestreUes.values_list('parcoursSemestre__parcours__libelle',
                                                           'parcoursSemestre__semestre__libelle').distinct()
        moyennneUes = []
        for psu in parcoursSemestreUes:
            try:
                moyennneUes.append(
                    MoyenneUe.objects.filter(etudiant=self.request.user, annee=Annee.objects.last(), ue=psu.ue).last()
                )
            except MoyenneUe.DoesNotExist:
                pass

        context['parcoursSemestreUes'] = parcoursSemestreUes
        context['parcoursSemestre'] = parcoursSemestre
        context['moyennes'] = moyennneUes
        return context


# ===========================================================================#
@login_required(login_url='BasicData:login')
def liste_etudiant_ue(request):
    AnUniv = Annee.objects.last()

    AFForm = AnneeFilterForm()
    if request.method == 'POST':
        if 'AnneeFilter' in request.POST:
            AFForm = AnneeFilterForm(request.POST)
            if AFForm.is_valid():
                cd = AFForm.cleaned_data
                libelle = cd.get('libelle')
                AnUniv = Annee.objects.get(id=libelle)

    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    # ON RECUPERE LE NIVEAU DE L'ETUDIANT
    nivEtud = NiveauEtudiant.objects.filter(annee=AnUniv, etudiant=etudiant).last()
    semestres = None
    if nivEtud:
        semestres = Semestre.objects.filter(niveau=nivEtud.niveau).order_by('libelle')

    # ON RECUPERE L'ANNEE PRECEDENTE
    prevAnnee = get_next_or_prev(AnUniv, 'prev')
    nextAnnee = get_next_or_prev(AnUniv, 'next')


    context = {
        'user': user,
        'etudiant': etudiant,
        'semestres': semestres,
        'EtudAn': [etudiant,AnUniv],
        'UFR': etudiant.ufr,
        'UfrAn':[etudiant.ufr.id,AnUniv.id],
        'AnUniv': AnUniv,
        'annee': AnUniv,
        'AFForm': AFForm,
        'prevAnnee': prevAnnee,
        'annees': Annee.objects.all().order_by('-id'),
    }
    return render(request, 'EspaceEtudiant/liste_ue.html', context)


@login_required(login_url='BasicData:login')
def detail_ue(request, ue, an):
    # ROLE
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    # On recupere toute les Ecues de l'Ue
    ueObj = Ue.objects.get(id=ue)
    AnneeObj = Annee.objects.get(id=an)
    ecues = Ecue.objects.filter(ue__id=ue,active=True)

    # On recupere l'etudiant
    #etudiant = Etudiant.objects.get(email=request.user.email)
    NivEtud = NiveauEtudiant.objects.filter(annee__id=an, etudiant=etudiant).last()
    niveau = None
    if NivEtud:
        niveau = NivEtud.niveau


    context = {
        'user': user,
        'enseignant': enseignant,
        'an': an,
        'ecues': ecues,
        'etudiant': etudiant,
        'niveau': niveau,
        'ue': ueObj,
        'ecues': ecues,
        'annee': AnneeObj,
        'args':[etudiant,AnneeObj]
    }
    return render(request, 'EspaceEtudiant/note-detail.html', context)


@login_required(login_url='BasicData:login')
def etudiant_profile_manage_password(request):
    # ROLE
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    show_form = 'show'
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            cd = form.cleaned_data
            an = cd.get('old_password')
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Votre mot de passe a bien été modifié!')
            show_form = 'hide'
        else:
            messages.error(request, 'Verifiez les champs')
    else:
        form = PasswordChangeForm(request.user)
    context = {'user': user, 'form': form, 'show_form': show_form, 'etudiant': etudiant}
    return render(request, 'EspaceEtudiant/change_password.html', context)


@login_required(login_url='login')
def etudiant_profile_infos(request):
    # ROLE
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    #etudiant = Etudiant.objects.get(email=request.user.email)
    context = {'user': user, 'etudiant': etudiant}
    return render(request, 'EspaceEtudiant/infos_perso.html', context)


@login_required(login_url='BasicData:login')
def etudiant_edt(request):
    # ROLE
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    annee = Annee.objects.last()

    prevAnnee = get_next_or_prev(annee, 'prev')

    # ON RECUPERE L'UFR DE L'ETUDIANT ET LE NIVEAU
    NivEtud = get_niveau_etudiant(etudiant,annee)
    NivPrev = get_niveau_etudiant(etudiant,prevAnnee)
    etdUFR = etudiant.ufr

    validite = Validite.objects.filter(done=False).order_by('dateDebut').first()
    validites = Validite.objects.filter(done=False).order_by('dateDebut')[:5]

    SDM1 = []
    TES2 = []
    ARHAI3 = []
    MPSI4 = []
    CPGE5 = []


    niveau_data_zip = []
    form = ChoosePeriodeForm()
    if request.method == 'POST':
        form = ChoosePeriodeForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            periode = cd.get('periode')

            if 'aucun' == periode:
                messages.error(request, 'Veuilliez sélectionner une période valide')
            else:
                validite = Validite.objects.get(id=periode)

    # ON RECUPERE LE PROGRAMME DE l'ETUDIANT
    p_lundi_m = []
    p_lundi_s = []
    p_mardi_m = []
    p_mardi_s = []
    p_mercredi_m = []
    p_mercredi_s = []
    p_jeudi_m = []
    p_jeudi_s = []
    p_vendredi_m = []
    p_vendredi_s = []
    p_samedi_m = []
    p_samedi_s = []

    ue_non_valide = get_etudiant_not_validate_ue_prev([annee,etudiant])
    #print(ue_non_valide)
    programmes = None
    programmes_prev = None
    if NivEtud:
        programmes = EmploiDuTemps2.objects.filter(ecue__ue__ufr=etdUFR,validite=validite,niveau=NivEtud,activated=True)
    if NivPrev:
        programmes_prev = EmploiDuTemps2.objects.filter(ecue__ue__in=ue_non_valide,ecue__ue__ufr=etdUFR,validite=validite,niveau=NivPrev,activated=True)


    if programmes or programmes_prev:
        for edt in [programmes,programmes_prev]:
            if edt:
                for pro in edt:

                    if pro.lundi != '':
                        debut_cours = get_horaire_split(pro.lundi, 'debut')
                        if debut_cours <= 12:
                            p_lundi_m.append(pro)
                        else:
                            p_lundi_s.append(pro)

                    if pro.mardi != '':
                        debut_cours = get_horaire_split(pro.mardi, 'debut')
                        if debut_cours <= 12:
                            p_mardi_m.append(pro)
                        else:
                            p_mardi_s.append(pro)

                    if pro.mercredi != '':
                        debut_cours = get_horaire_split(pro.mercredi, 'debut')
                        if debut_cours <= 12:
                            p_mercredi_m.append(pro)
                        else:
                            p_mercredi_s.append(pro)

                    if pro.jeudi != '':
                        debut_cours = get_horaire_split(pro.jeudi, 'debut')
                        if debut_cours <= 12:
                            p_jeudi_m.append(pro)
                        else:
                            p_jeudi_s.append(pro)

                    if pro.vendredi != '':
                        debut_cours = get_horaire_split(pro.vendredi, 'debut')
                        if debut_cours <= 12:
                            p_vendredi_m.append(pro)
                        else:
                            p_vendredi_s.append(pro)

                    if pro.samedi != '':
                        debut_cours = get_horaire_split(pro.samedi, 'debut')
                        if debut_cours <= 12:
                            p_samedi_m.append(pro)
                        else:
                            p_samedi_s.append(pro)

    context = {
        'user': user,
        'etudiant': etudiant,
        'annee': annee,
        'validite': validite,
        'validites': validites,
        'programmes': programmes,
        'niveau': NivEtud,
        'ufr': etdUFR,
        'p_lundi_m': p_lundi_m, 'p_lundi_s': p_lundi_s,
        'p_mardi_m': p_mardi_m, 'p_mardi_s': p_mardi_s,
        'p_mercredi_m': p_mercredi_m, 'p_mercredi_s': p_mercredi_s,
        'p_jeudi_m': p_jeudi_m, 'p_jeudi_s': p_jeudi_s,
        'p_vendredi_m': p_vendredi_m, 'p_vendredi_s': p_vendredi_s,
        'p_samedi_m': p_samedi_m, 'p_samedi_s': p_samedi_s,
        'SDM1': SDM1, 'TES2': TES2, 'ARHAI3': ARHAI3, 'MPSI4': MPSI4,
    }
    return render(request, 'EspaceEtudiant/etudiant_edt.html', context)


@login_required(login_url='BasicData:login')
def reclamation_home(request):
    # ROLE
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    # ON RECUPERE LE NIVEAU
    EtudNiv = NiveauEtudiant.objects.filter(etudiant=etudiant).last().niveau

    #Etudufr = EtudiantUe.objects.filter(etudiant=etudiant).last()
    ufr = etudiant.ufr

    show_form = 'show'
    form = ReclamationForm()
    if request.method == 'POST':
        form = ReclamationForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            type_disc = cd.get('type_discipline')
            code_disc = cd.get('code_discipline')
            motif = cd.get('motif')
            detail = cd.get('detail')
            annee = cd.get('annee')

            if type_disc == 'UE':
                try:
                    ue = Ue.objects.get(code=code_disc)
                except Ue.DoesNotExist:
                    ue = None
                if ue:
                    delib = DeliberationUe.objects.filter(annee=annee, ue=ue, session__id=1).last()
                else:
                    delib = None
            elif type_disc == 'ECUE':
                try:
                    ecue = Ecue.objects.get(code=code_disc)
                except Ecue.DoesNotExist:
                    ecue = None
                if ecue:
                    delib = DeliberationUe.objects.filter(annee=annee, ue=ecue.ue, session__id=1).last()
                else:
                    delib = None
            else:
                delib = None

            check_reclam = False
            Enddate = None
            if delib:
                delib_date = str(delib.created).split(' ')[0]
                Begindate = datetime.strptime(delib_date, "%Y-%m-%d")
                Enddate = Begindate + timedelta(days=4)

                # DATE DU JOUR
                today_date = datetime.today()
                if today_date > Enddate:
                    check_reclam = True

            if delib and check_reclam == True:
                messages.error(request, 'La date limite de réclamation pour cette UE était : ' + str(Enddate))
            elif motif is None:
                messages.error(request, 'Veuilliez choisir un motif de réclamation svp!')
            else:
                Reclamations.objects.create(
                    etudiant=etudiant,
                    ufr=ufr,
                    annee=annee,
                    niveau=EtudNiv,
                    type_discipline=type_disc,
                    code_discipline=code_disc,
                    motif=motif,
                    detail=detail
                )
                messages.success(request, 'Votre réclamation a bienété envoyée!')
                show_form = 'hide'
        else:
            messages.error(request, 'Verifiez les champs')
    else:
        form = ReclamationForm()

    context = {'user': user, 'form': form, 'show_form': show_form, 'etudiant': etudiant}
    return render(request, 'EspaceEtudiant/reclamation_home.html', context)


@login_required(login_url='BasicData:login')
def reclamation_list(request):
    # ROLE
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    # ON RECUPERE LES RECLAMATIONS DE L'ETUDIANT
    reclamations = Reclamations.objects.filter(etudiant=etudiant).order_by('-id')

    context = {
        'user': user,
        'etudiant': etudiant,
        'reclamations': reclamations,
    }
    return render(request, 'EspaceEtudiant/reclamation_list.html', context)


@login_required(login_url='BasicData:login')
def reclamation_detail(request, id):
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()
    # ON RECUPERE LES RECLAMATIONS
    reclamation = Reclamations.objects.get(id=id)

    context = {
        'user': user,
        'reclamation': reclamation,
        'etudiant': etudiant,
    }
    return render(request, 'EspaceEtudiant/reclamation_detail.html', context)


@login_required(login_url='BasicData:login')
def seance_etudiant(request):
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    # ROLE
    annees = Annee.objects.all().order_by('-id')

    niveauEtudiant = NiveauEtudiant.objects.filter(etudiant=etudiant).last()

    # ON RECUPERE LES SEANCES
    seances =None
    if niveauEtudiant:
        seances = SeanceCours.objects.filter(
            ecue__ue__niveau__id=niveauEtudiant.niveau.id,
            ecue__ue__ufr=etudiant.ufr,
            etudiant_valid=False
        ).order_by('-date')

    form = EtudiantSeanceForm2(request.POST)
    if request.method == 'POST':
        if 'agreeseance' in request.POST:
            form = EtudiantSeanceForm2(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                sean = cd.get('seance')
                debut = cd.get('debut')
                fin = cd.get('fin')
                seance = SeanceCours.objects.get(id=sean)
                seance.etudiant_valid = True
                seance.debut_delegue = debut
                seance.fin_delegue = fin
                seance.save()
                messages.success(request, "Vous avez confimer la séance du "+str(seance.date)+" de l'Ecue: "+str(seance.ecue.code))
                return redirect('/etudiant/seance_etudiant/')
            else:
                messages.error(request, 'Vérifiez les champs svp')

    context = {
        'user': user,
        'etudiant': etudiant,
        'seances': seances,
        'form': form,
    }
    return render(request, 'EspaceEtudiant/seance_etudiant.html', context)


@login_required(login_url='BasicData:login')
def add_photo(request):
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    drh = None
    role = ''
    if not user and Enseignant.objects.filter(email=request.user.email).last():
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()
    elif not user and Personnel.objects.filter(email=request.user.email).last():
        user = drh = Personnel.objects.filter(email=request.user.email).last()
        if drh:
            role = drh.resposabilite.libelle = 'Responsable DRH'

    form = PhotoAddForm(request.POST, request.FILES, instance=user)
    if request.method == 'POST':
        form = PhotoAddForm(request.POST, request.FILES, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, "Photo modifiée")
            return redirect('/etudiant/add_photo/')
        else:
            messages.error(request, 'Erreur! vérifiez les champs svp.')

    context = {
        'user': user,
        'enseignant': enseignant,
        'etudiant': etudiant,
        'drh': drh,
        'form': form,
        'role': role,
    }
    return render(request, 'EspaceEtudiant/add_photo.html', context)


@login_required(login_url='BasicData:login')
def demande_actes_liste(request):
    user = etudiant = Etudiant.objects.filter(email=request.user.email).last()
    enseignant = None
    if not user:
        user = enseignant = Enseignant.objects.filter(email=request.user.email).last()

    demandes = DemandeActes.objects.filter(etudiant=etudiant)

    form = AddDemandesForm()
    if request.method == 'POST':
        form = AddDemandesForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            annee = cd.get('annee')
            tpdem = cd.get('type_demande')
            if_dem = DemandeActes.objects.filter(
                etudiant=etudiant,
                annee=annee,
                type_demande = tpdem,
            )

            if if_dem:
                messages.error(request, 'Vous ne pouvez plus faire de demande de ['+str(tpdem).upper()+'] pour l\'année ['+str(annee)+']')
            else:
                DemandeActes.objects.create(
                    etudiant=etudiant,
                    annee=annee,
                    type_demande = tpdem,
                    ufr=etudiant.ufr
                )
                messages.success(request,'Demande envoyée')
            return redirect('/etudiant/demande_actes_liste/')
        else:
            messages.error(request,'vérifiez les champs svp')

    context = {
        'user':user,
        'etudiant':etudiant,
        'demandes':demandes,
        'form':form,
    }
    return render(request, 'EspaceEtudiant/demande_acte_list.html', context)


def et_inscription_home(request):
    etudiant = Etudiant.objects.get(email=request.user.email)
    annee = Annee.objects.last()
    documents = Document.objects.filter(annee=annee,etudiant=etudiant)

    # ON RECUPERE L'ANNEE PRECEDENTE
    annees = Annee.objects.all().order_by('-id')[:2]
    if annees and len(annees) > 1:
        annee_prec = annees[1]
    elif annees and len(annees) == 1:
        annee_prec = annees[0]
    else:
        annee_prec = None

    # ON RECUPERE LE NIVEAU ACTUEL DE L'ETUDIANT
    qs = NiveauEtudiant.objects.filter(annee=annee_prec, etudiant__id=etudiant.id).last()
    niv_actuel = None
    niv_suivant = None
    if qs:
        niv_actuel = qs.niveau
        # ON RECUPERE LE NIVEAU SUIVANT DE L'ETUDIANT
        niv_suivant = Niveau.objects.filter(id__gt=niv_actuel.id).first()


    # DECISION ANNUELLE
    decision_annuelle = decision_annuelle_etudiant(etudiant)
    if decision_annuelle =='AJOURNE(E)':
        niv_suivant = niv_actuel


    # DOCUMENT ADD
    form = EtDocAddForm(request.POST, request.FILES)
    if request.method == 'POST':
        if 'addoc-btn' in request.POST:
            form = EtDocAddForm(request.POST, request.FILES)
            if form.is_valid():
                cd = form.cleaned_data
                tpdc = cd.get('typedoc')
                doc = cd.get('document')
                Document.objects.create(
                    annee=annee,
                    etudiant=etudiant,
                    typedoc=tpdc,
                    document=doc
                )
                messages.success(request, "Document ajouté avec succès")
                return redirect('/etudiant/et_inscription_home/')
            else:
                messages.error(request, 'Erreur! vérifiez les champs svp.')
                messages.error(request, form.errors)

    # ON VERIFIE SI UNE DEMANDE A DEJA ETE ENVOYEE
    insc_sent = Reinscription.objects.filter(
                annee=annee,
                etudiant = etudiant,
                niveau = niv_suivant
            )

    # DEMANDE D'INSCRIPTION
    if request.method == 'POST':
        if 'demInsc-btn' in request.POST:
            if insc_sent:
                messages.error(request, 'Vous avez déja envoyer une demande')
                return redirect('/etudiant/et_inscription_home/')
            else:
                Reinscription.objects.create(
                    annee=annee,
                    etudiant = etudiant,
                    niveau = niv_suivant
                )
                messages.success(request,'Demande envoyée avec succès')
                return redirect('/etudiant/et_inscription_home/')


    context = {
        'etudiant': etudiant,
        'form': form,
        'documents': documents,
        'niv_suivant': niv_suivant,
        'niv_actuel': niv_actuel,
        'annee': annee,
        'insc_sent': insc_sent,
    }
    return render(request, 'EspaceEtudiant/et_inscription_home.html', context)


@login_required(login_url='BasicData:login')
def etudiant_profile_edit(request):
    ufrs = Ufr.objects.all()

    # ON RECUPERE LES DONNEES DE L'ETUDIANT
    etudiant = Etudiant.objects.get(email=request.user.email)

    form = EtudEditForm(instance=etudiant)
    if request.method == 'POST':
        form = EtudEditForm(request.POST, instance=etudiant)
        if form.is_valid():
            form.save()
            messages.success(request, 'Modifié avec succès!')
            return redirect('/etudiant/etudiant_profile/')
        else:
            messages.error(request, 'vérifiez les champs svp!')

    context = {
        'form': form,
        'ufrs': ufrs,
        'etudiant':etudiant
    }
    return render(request, 'EspaceEtudiant/etudiant_profil_edit.html', context)


@login_required(login_url='BasicData:login')
def download(request,id):
    rep = ReponseDemandeActes.objects.filter(demande__id=id).last()
    filename = rep.document.name.split('/')[-1]
    response = HttpResponse(rep.document, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response


@login_required(login_url='BasicData:login')
def sondage_list(request):
    # ON VERIFIE SI L'UTILISATEUR EST UN ENSEIGNANT OU UN ETUDIANT
    user = None
    enseignant = Enseignant.objects.filter(email=request.user.email).last()
    etudiant = Etudiant.objects.filter(email=request.user.email).last()

    # ON RECUPERE LES INFOS DES ETUDIANTS
    sondage = None
    if etudiant:
        user = etudiant
        ufr = etudiant.ufr.code.upper()
        sondage = Sondage.objects.filter(ufr__in=['Tout', ufr], cible__in=['Tout', 'Etudiant'],published=True).order_by('-id')
    elif enseignant:
        user = enseignant
        ufr = enseignant.ufr.code.upper()
        sondage = Sondage.objects.filter(ufr__in=['Tout', ufr], cible__in=['Tout', 'Enseignant'],published=True).order_by('-id')
    else:
        pass

    context = {
        'user':user,
        'sondage':sondage,
    }
    return render(request, 'EspaceEtudiant/sondage_list.html', context)