def researchgroup_teacher_edit(request,
                               code,
                               teacher_rgroup_id,
                               my_offices=None,
                               rgroup=None,
                               teachers=None):
    teacher_rgroup = get_object_or_404(RicercaDocenteGruppo,
                                       pk=teacher_rgroup_id)
    teacher = teacher_rgroup.personale
    teacher_data = (encrypt(teacher.matricola),
                    f'{teacher.cognome} {teacher.nome}')
    form = RicercaGruppoDocenteForm(
        instance=teacher_rgroup, initial={'choosen_teacher': teacher_data[0]})

    if request.POST:
        form = RicercaGruppoDocenteForm(data=request.POST)
        if form.is_valid():
            teacher_code = decrypt(form.cleaned_data['choosen_teacher'])
            new_teacher = get_object_or_404(Personale, matricola=teacher_code)
            teacher_rgroup.user_mod = request.user
            teacher_rgroup.dt_inizio = form.cleaned_data['dt_inizio']
            teacher_rgroup.dt_fine = form.cleaned_data['dt_fine']
            teacher_rgroup.personale = new_teacher
            teacher_rgroup.save()

            log_msg = f'{_("Changed teacher")} {teacher.__str__()}' \
                      if teacher == new_teacher \
                      else f'{teacher} {_("substituted with")} {new_teacher.__str__()}'

            log_action(user=request.user, obj=rgroup, flag=CHANGE, msg=log_msg)

            messages.add_message(request, messages.SUCCESS,
                                 _("Teacher edited successfully"))
            return redirect('ricerca_crud:crud_researchgroup_edit', code=code)
        else:  # pragma: no cover
            for k, v in form.errors.items():
                messages.add_message(request, messages.ERROR,
                                     f"<b>{form.fields[k].label}</b>: {v}")

    breadcrumbs = {
        reverse('ricerca_crud:crud_dashboard'):
        _('Dashboard'),
        reverse('ricerca_crud:crud_researchgroups'):
        _('Research groups'),
        reverse('ricerca_crud:crud_researchgroup_edit', kwargs={'code': code}):
        rgroup.nome,
        '#':
        f'{teacher.cognome} {teacher.nome}'
    }

    return render(
        request, 'researchgroup_teacher.html', {
            'breadcrumbs': breadcrumbs,
            'form': form,
            'rgroup': rgroup,
            'teacher_rgroup_id': teacher_rgroup_id,
            'choosen_teacher': teacher_data[1],
            'url': reverse('ricerca:teacherslist')
        })
def applied_researchline_teacher_new(request,
                                     code,
                                     my_offices=None,
                                     rline=None,
                                     teachers=None):
    breadcrumbs = {
        reverse('ricerca_crud:crud_dashboard'):
        _('Dashboard'),
        reverse('ricerca_crud:crud_applied_researchlines'):
        _('Research lines'),
        reverse('ricerca_crud:crud_applied_researchline_edit',
                kwargs={'code': code}):
        rline.descrizione,
        '#':
        _('New teacher')
    }
    form = RicercaDocenteLineaApplicataForm()
    if request.POST:
        form = RicercaDocenteLineaApplicataForm(data=request.POST)
        if form.is_valid():
            teacher_code = decrypt(form.cleaned_data['choosen_teacher'])
            teacher = get_object_or_404(Personale, matricola=teacher_code)
            RicercaDocenteLineaApplicata.objects.create(
                user_ins=request.user,
                ricerca_linea_applicata=rline,
                dt_inizio=form.cleaned_data['dt_inizio'],
                dt_fine=form.cleaned_data['dt_fine'],
                personale=teacher)

            log_action(user=request.user,
                       obj=rline,
                       flag=CHANGE,
                       msg=f'{_("Added teacher")} {teacher.__str__()}')

            messages.add_message(request, messages.SUCCESS,
                                 _("Teacher added successfully"))
            return redirect('ricerca_crud:crud_applied_researchline_edit',
                            code=code)
        else:  # pragma: no cover
            for k, v in form.errors.items():
                messages.add_message(request, messages.ERROR,
                                     f"<b>{form.fields[k].label}</b>: {v}")

    return render(
        request, 'base_researchline_teacher.html', {
            'breadcrumbs': breadcrumbs,
            'form': form,
            'rgroup': rline,
            'url': reverse('ricerca:teacherslist')
        })
def researchline_new_base(request, my_offices=None):
    breadcrumbs = {
        reverse('ricerca_crud:crud_dashboard'): _('Dashboard'),
        reverse('ricerca_crud:crud_base_researchlines'):
        _('Base Research lines'),
        '#': _('New')
    }
    form = RicercaLineaBaseForm()
    teacher_form = RicercaDocenteLineaBaseForm()

    # already choosen before form fails
    teacher = None
    if request.POST.get('choosen_teacher', ''):
        teacher = get_object_or_404(Personale,
                                    matricola=(decrypt(
                                        request.POST['choosen_teacher'])))

    if request.POST:
        form = RicercaLineaBaseForm(data=request.POST)
        teacher_form = RicercaDocenteLineaBaseForm(data=request.POST)
        if form.is_valid() and teacher_form.is_valid():
            teacher_code = decrypt(
                teacher_form.cleaned_data['choosen_teacher'])
            teacher = get_object_or_404(Personale, matricola=teacher_code)

            # check if user can manage teacher structure
            if not request.user.is_superuser:
                structure_afforg = OrganizationalStructureOfficeEmployee.objects.filter(
                    employee=request.user,
                    office__name=OFFICE_RESEARCHLINES,
                    office__is_active=True,
                    office__organizational_structure__is_active=True,
                    office__organizational_structure__unique_code=teacher.
                    cd_uo_aff_org_id)
                if not structure_afforg:
                    raise Exception(
                        _("Add a teacher belonging to your structure"))

            rline = RicercaLineaBase.objects.create(
                user_ins=request.user,
                descrizione=form.cleaned_data['descrizione'],
                descr_pubblicaz_prog_brevetto=form.
                cleaned_data['descr_pubblicaz_prog_brevetto'],
                anno=form.cleaned_data['anno'],
                ricerca_erc2=form.cleaned_data['ricerca_erc2'])
            RicercaDocenteLineaBase.objects.create(
                user_ins=request.user,
                ricerca_linea_base=rline,
                dt_inizio=teacher_form.cleaned_data['dt_inizio'],
                dt_fine=teacher_form.cleaned_data['dt_fine'],
                personale=teacher)

            log_action(user=request.user,
                       obj=rline,
                       flag=ADDITION,
                       msg=[{
                           'added': {}
                       }])

            messages.add_message(request, messages.SUCCESS,
                                 _("Research line created successfully"))
            return redirect("ricerca_crud:crud_base_researchlines")
        else:  # pragma: no cover
            for k, v in form.errors.items():
                messages.add_message(request, messages.ERROR,
                                     f"<b>{form.fields[k].label}</b>: {v}")
            for k, v in teacher_form.errors.items():
                messages.add_message(
                    request, messages.ERROR,
                    f"<b>{teacher_form.fields[k].label}</b>: {v}")

    return render(
        request, 'researchline_new.html', {
            'breadcrumbs': breadcrumbs,
            'choosen_teacher':
            f'{teacher.cognome} {teacher.nome}' if teacher else '',
            'form': form,
            'teachers_api': reverse('ricerca:teacherslist'),
            'teacher_form': teacher_form
        })