def create_link_student_file(student_data, subject, file_type, import_errors_link, user_create,
                             user_link):
    if file_type == "text/xml":
        data_form = StudentService.get_form_data_xml(student_data)
    else:
        data_form = StudentService.get_form_data_csv(student_data)

    form_student = UserEditForm(data=data_form)

    if form_student.is_valid():
        student = StudentService.create(form_student)
        StudentService.save(student)
        password = id_generator()
        UserService.save_password(student, password)
        user_create[student] = password
        student.asignaturas.add(subject)
    else:
        fullname = form_student.data['last_name'] + ", " + form_student.data['first_name']
        username = form_student.data['user']
        user = UserService.find_by_username(username)
        if user:
            student = Alumno.objects.get(id=user.id)
            if student:
                student.asignaturas.add(subject)
                user_link.append(student)
            else:
                import_errors_link.append(_("Student") + ": " + fullname + " - " + form_student.data['dni'])
        else:
            import_errors_link.append(_("Student") + ": " + fullname + " - " + form_student.data['dni'])
def create_link_student_file(student_data, subject, file_type,
                             import_errors_link, user_create, user_link):
    if file_type == "text/xml":
        data_form = StudentService.get_form_data_xml(student_data)
    else:
        data_form = StudentService.get_form_data_csv(student_data)

    form_student = UserEditForm(data=data_form)

    if form_student.is_valid():
        student = StudentService.create(form_student)
        StudentService.save(student)
        password = id_generator()
        UserService.save_password(student, password)
        user_create[student] = password
        student.asignaturas.add(subject)
    else:
        fullname = form_student.data['last_name'] + ", " + form_student.data[
            'first_name']
        username = form_student.data['user']
        user = UserService.find_by_username(username)
        if user:
            student = Alumno.objects.get(id=user.id)
            if student:
                student.asignaturas.add(subject)
                user_link.append(student)
            else:
                import_errors_link.append(
                    _("Student") + ": " + fullname + " - " +
                    form_student.data['dni'])
        else:
            import_errors_link.append(
                _("Student") + ": " + fullname + " - " +
                form_student.data['dni'])
def import_users(request):

    template_data = {}
    import_errors_create = []
    user_create = {}

    if request.POST:
        form = FileUploadForm(request.POST, request.FILES)

        if form.is_valid():
            file_name = form.cleaned_data["file_upload"]
            data = file_name.read()
            file_name.close()

            try:
                if form.cleaned_data["file_upload"].content_type == "text/xml":
                    # File XML
                    data = xmltodict.parse(data)

                    # Iterate students
                    if data["usuarios"]["alumnos"]:
                        if not isinstance(data["usuarios"]["alumnos"]["alumno"], list):
                            # 1 value
                            student_data = data["usuarios"]["alumnos"]["alumno"]
                            data_form = StudentService.get_form_data_xml(student_data)
                            create_student_file(data_form, import_errors_create, user_create)
                        else:
                            for student_data in data["usuarios"]["alumnos"]["alumno"]:
                                data_form = StudentService.get_form_data_xml(student_data)
                                create_student_file(data_form, import_errors_create, user_create)

                    # Iterate lecturers
                    if data["usuarios"]["profesores"]:
                        if not isinstance(data["usuarios"]["profesores"]["profesor"], list):
                            # 1 value
                            lecturer_data = data["usuarios"]["profesores"]["profesor"]
                            data_form = LecturerService.get_form_data_xml(lecturer_data)
                            create_lecturer_file(data_form, import_errors_create, user_create)
                        else:
                            for lecturer_data in data["usuarios"]["profesores"]["profesor"]:
                                data_form = LecturerService.get_form_data_xml(lecturer_data)
                                create_lecturer_file(data_form, import_errors_create, user_create)

                else:
                    # File CSV
                    for user in csv.reader(data.splitlines()):
                        type_user = user[0]
                        if type_user == "Alumno":
                            data_form = StudentService.get_form_data_csv(user)
                            create_student_file(data_form, import_errors_create, user_create)
                        elif type_user == "Profesor":
                            data_form = LecturerService.get_form_data_csv(user)
                            create_lecturer_file(data_form, import_errors_create, user_create)
                        else:
                            raise KeyError("Alumno o Profesor")

                message = _("Action completed successfully")
                EmailService.send_email_create_user(user_create, request)
                if import_errors_create:
                    messages.warning(request, message)
                    template_data["import_errors_create"] = import_errors_create
                else:
                    messages.success(request, message)

                form = FileUploadForm()

            except KeyError as e:
                message = _("The file structure is wrong. It needs a label called: ") + e.message
                form.add_error("file_upload", message)
                UserService.rollback_users(user_create)
            except AttributeError:
                message = _("Please, check the attributes of the subjects")
                form.add_error("file_upload", message)
                UserService.rollback_users(user_create)
            except TypeError:
                message = _("Please, check the xml syntax and data values")
                form.add_error("file_upload", message)
                UserService.rollback_users(user_create)
            except Exception:
                message = _("Please, check the file")
                form.add_error("file_upload", message)
                UserService.rollback_users(user_create)

    else:
        form = FileUploadForm()

    template_data["form"] = form
    template_name = "user/import_user.html"
    return render_to_response(template_name, template_data, context_instance=RequestContext(request))
def import_users(request):

    template_data = {}
    import_errors_create = []
    user_create = {}

    if request.POST:
        form = FileUploadForm(request.POST, request.FILES)

        if form.is_valid():
            file_name = form.cleaned_data['file_upload']
            data = file_name.read()
            file_name.close()

            try:
                if form.cleaned_data['file_upload'].content_type == "text/xml":
                    # File XML
                    data = xmltodict.parse(data)

                    # Iterate students
                    if data['usuarios']['alumnos']:
                        if not isinstance(
                                data['usuarios']['alumnos']['alumno'], list):
                            # 1 value
                            student_data = data['usuarios']['alumnos'][
                                'alumno']
                            data_form = StudentService.get_form_data_xml(
                                student_data)
                            create_student_file(data_form,
                                                import_errors_create,
                                                user_create)
                        else:
                            for student_data in data['usuarios']['alumnos'][
                                    'alumno']:
                                data_form = StudentService.get_form_data_xml(
                                    student_data)
                                create_student_file(data_form,
                                                    import_errors_create,
                                                    user_create)

                    # Iterate lecturers
                    if data['usuarios']['profesores']:
                        if not isinstance(
                                data['usuarios']['profesores']['profesor'],
                                list):
                            # 1 value
                            lecturer_data = data['usuarios']['profesores'][
                                'profesor']
                            data_form = LecturerService.get_form_data_xml(
                                lecturer_data)
                            create_lecturer_file(data_form,
                                                 import_errors_create,
                                                 user_create)
                        else:
                            for lecturer_data in data['usuarios'][
                                    'profesores']['profesor']:
                                data_form = LecturerService.get_form_data_xml(
                                    lecturer_data)
                                create_lecturer_file(data_form,
                                                     import_errors_create,
                                                     user_create)

                else:
                    # File CSV
                    for user in csv.reader(data.splitlines()):
                        type_user = user[0]
                        if type_user == 'Alumno':
                            data_form = StudentService.get_form_data_csv(user)
                            create_student_file(data_form,
                                                import_errors_create,
                                                user_create)
                        elif type_user == 'Profesor':
                            data_form = LecturerService.get_form_data_csv(user)
                            create_lecturer_file(data_form,
                                                 import_errors_create,
                                                 user_create)
                        else:
                            raise KeyError('Alumno o Profesor')

                message = _('Action completed successfully')
                EmailService.send_email_create_user(user_create, request)
                if import_errors_create:
                    messages.warning(request, message)
                    template_data[
                        'import_errors_create'] = import_errors_create
                else:
                    messages.success(request, message)

                form = FileUploadForm()

            except KeyError as e:
                message = _(
                    "The file structure is wrong. It needs a label called: "
                ) + e.message
                form.add_error('file_upload', message)
                UserService.rollback_users(user_create)
            except AttributeError:
                message = _("Please, check the attributes of the subjects")
                form.add_error('file_upload', message)
                UserService.rollback_users(user_create)
            except TypeError:
                message = _("Please, check the xml syntax and data values")
                form.add_error('file_upload', message)
                UserService.rollback_users(user_create)
            except Exception:
                message = _("Please, check the file")
                form.add_error('file_upload', message)
                UserService.rollback_users(user_create)

    else:
        form = FileUploadForm()

    template_data['form'] = form
    template_name = 'user/import_user.html'
    return render_to_response(template_name,
                              template_data,
                              context_instance=RequestContext(request))