Ejemplo n.º 1
0
def search(request, page_number=1):
	if 'search' in request.session:
		login = check_sign_in(request)
		categories = Category.objects.all()
		data = request.session['search']
		args = {'login': login, 'categories': categories, 'tests_category': data.get('category','all'), 'url': '/tests/search/page/'}
		args.update(csrf(request))

		if request.method == 'POST':
			request.session['search']['text'] = request.POST.get('search','')

		#Проверка категории
		if data['category'] == 'all':
			tests = Test.objects.filter(public_access=True, title__icontains=data['text'])
			search_category_test = "Все"
		else:
			search_category_test = get_object_or_404(Category, url=data['category'])
			tests = Test.objects.filter(public_access=True, category=search_category_test, title__icontains=data['text'])
			
		
		args['search'] = {'text': data['text'], 'count': tests.count, 'category': search_category_test}
		current_page = Paginator(tests, 15)
		if int(page_number) > current_page.num_pages or int(page_number) < 1:
			raise Http404('Такой страницы нет')

		args['pages_count'] = get_number_name(current_page.num_pages + 2)
		args['tests'] = current_page.page(page_number)
		return render_to_response('tests.html', args)
	else:
		raise Http404('Что-то пошло не так')
Ejemplo n.º 2
0
def tests(request, category = 'all', page_number = 1):
	login = check_sign_in(request)
	categories = Category.objects.all()
	args = {'login': login, 'categories': categories, 'tests_category': category}
	args.update(csrf(request))

	#удаляем сессию поиска, если присутствует
	if 'search' in request.session:
		del request.session['search']

	if request.method == 'GET':
		#Проверка категории
		if category == 'all':
			tests = Test.objects.filter(public_access=True)
			args['url'] = '/tests/page/'
		else:
			tests = Test.objects.filter(public_access=True, category__url=category)
			args['url'] = '/tests/category/%s/page/' % category
	elif request.method == 'POST':
		title = request.POST.get('search', '')
		request.session['search'] = {'text': title, 'category': category}
		return redirect('/tests/search/')
	#Пагинация
	current_page = Paginator(tests, 15)
	if int(page_number) > current_page.num_pages or int(page_number) < 1:
		raise Http404('Такой страницы нет')

	args['tests'] = current_page.page(page_number)
	args['pages_count'] = get_number_name(current_page.num_pages + 2)
	return render_to_response('tests.html', args)
Ejemplo n.º 3
0
def create_test(request):
    login = check_sign_in(request)
    if login and (login.is_staff or login.is_superuser):
        if request.is_ajax():
            category = get_object_or_404(Category,id=int(request.POST['category']))

            test = Test(
                title = request.POST['title'],
                description = request.POST['description'],
                helps = str_to_bool(request.POST['helps']),
                time_completion = str_to_bool(request.POST['timeCompl']),
                creator = auth.get_user(request),
                category = category,
                two_mark = request.POST['two_mark'],
                three_mark = request.POST['three_mark'],
                four_mark = request.POST['four_mark']
            )
            test.save()

            return JsonResponse({'testID': test.id, 'error': False})
        else:
            categories = Category.objects.all()
            return render_to_response('create_test.html', {'login': login, 'categories': categories})
    else:
        raise Http404('Вы не имете доступа!')
Ejemplo n.º 4
0
def test_access(request, id):
    test = get_object_or_404(Test, id=id)
    login = check_sign_in(request)
    if test.creator == login:
        if request.is_ajax():
            #Формируем данные
            if request.method == 'GET':
                specializations = SpecializationSerializer(Specialization.objects.all(), many=True).data
                groups_access = GroupSerializer(test.group_access.all(), many=True).data
                groups = GroupSerializer(Group.objects.all().order_by('course','name'), many=True).data
                for group in groups:
                    if group in groups_access:
                        group['access'] = True
                    else:
                        group['access'] = False
                courses = list(map(lambda x: {'id': x, 'name': str(x)}, range(1, 5)))
                return JsonResponse({'specs': specializations, 'groups': groups, 'courses': courses})
            elif request.method == 'POST':
                group = get_object_or_404(Group, id=request.POST.get('group', ''))
                if str_to_bool(request.POST.get('append', False)):
                    test.group_access.add(group)
                else:
                    test.group_access.remove(group)
                return JsonResponse({'success': True})
            elif request.method == "DELETE":
                test.group_access.clear()
                return JsonResponse({'success': True})
        else:
            return render_to_response('test_access.html',{'login': login, 'test': test, 'optionName': 'access'})
    else:
        raise Http404('Вы не имете доступа!')
Ejemplo n.º 5
0
def edit_question(request, t_id, q_id):
    test = get_object_or_404(Test, id=t_id)
    question = get_object_or_404(Query, id=q_id)
    login = check_sign_in(request)

    if test.creator == auth.get_user(request):
        if request.method == 'POST':
            #отправляем model
            return HttpResponse(json.dumps(model_to_dict(question)))
        elif request.method == 'PUT':
            #парсим put запрос
            data = put(request)
            #обновляем данные
            question.help = data.get('help')
            question.point = int(data.get('point'))
            question.text = data.get('text')
            question.save()

            return HttpResponse(json.dumps(data))
        elif request.method == 'GET':
            return render_to_response('add_query.html',
                {
                    'login': login,
                    'test': test,
                    'question': question
                }
            )
    else:
        raise Http404('Вы не являетесь создателем данного теста!')
Ejemplo n.º 6
0
def settings_test(request, id):
	test = get_object_or_404(Test, id=id)
	if test.creator == auth.get_user(request):
		if request.is_ajax():
			category = get_object_or_404(Category,id=int(request.POST['category']))

			test.title = request.POST['title']
			test.description = request.POST['description']
			test.helps = str_to_bool(request.POST['helps'])
			test.time_completion = str_to_bool(request.POST['timeCompl'])
			test.public_access = str_to_bool(request.POST['public_access'])
			test.two_mark = request.POST['two_mark']
			test.three_mark = request.POST['three_mark']
			test.four_mark = request.POST['four_mark']
			test.category = category
			test.questions_count = request.POST['quest_count']
			test.save()

			return JsonResponse({'success': 'Данные сохранены!'})
		else:
			login = check_sign_in(request)
			categories = Category.objects.all()
			return render_to_response('create_test.html', {'login': login, 'test': test, 'categories': categories})
	else:
		return redirect('/')
Ejemplo n.º 7
0
def profile(request, login):
	user = check_sign_in(request)
	if user.username == login:
		tests = Test.objects.filter(creator=user)
		return render_to_response('profile.html', {'login': user, 'tests': tests})
	else:
		raise Http404('Это не ваш профиль : ' + login)
Ejemplo n.º 8
0
def queries_test(request, id):
    sign_in = check_sign_in(request)
    test = get_object_or_404(Test, id=id)
    if test.creator == auth.get_user(request):
        queries = map(get_answers, Query.objects.filter(test = test))
        return render_to_response('test/queries.html', {'login': sign_in, 'test': test, 'queries': queries, 'optionName': 'questions'})
    else:
        raise Http404('Вы не являетесь создателем данного теста!')
Ejemplo n.º 9
0
def test_results(request, login, id):
	user = check_sign_in(request)
	test = get_object_or_404(Test,id=id, creator=user)
	if request.is_ajax():
		probationers = models_to_dict(Probationer.objects.filter(test=test).order_by('-date'))
		return HttpResponse(json.dumps(probationers))
	else:
		return render_to_response('test_results.html', {'login': user, 'test': test})
Ejemplo n.º 10
0
def set_name(request):
	if request.is_ajax() and 'test' in request.session:
		request.session.modified = True
		request.session['test']['user'] = request.POST['user']

		#если пользователь зареган, то сохраняем фамилию
		user = check_sign_in(request)
		if user.is_authenticated():
			user.last_name = request.POST['user']
			user.save()
		return JsonResponse({'success': True})
	else:
		raise Http404('Такая страница не существует')
Ejemplo n.º 11
0
def test(request, id):
	login = check_sign_in(request)
	test = get_object_or_404(Test, id=id, public_access=True)
	if request.is_ajax():
		#Если не существует сессии с данным тестом , мы ее создаем
		if 'test' not in request.session or request.session['test']['id'] != test.id:
			questions = models_to_dict(Query.objects.filter(test=test).order_by('?')[:test.questions_count])
			random.shuffle(questions)

			request.session['test'] = {
				'id': test.id,
				'questions' : list(map(lambda quest: quest['id'], questions)),
				'answers' : [],
				'current_quset': 0,
				'user': ''
			}

		quest = Query.objects.get(id=request.session['test']['questions'][request.session['test']['current_quset']])
		answers = models_to_dict(Answer.objects.filter(query=quest))
		random.shuffle(answers)
		#проверяем включены ли подсказки и время сдачи
		test = model_to_dict(test)
		quest = model_to_dict(quest)
		if not test['time_completion']:
			quest['time'] = False
		if not test['helps']:
			quest['help'] = False

		#проверяем авторизирован ли пользователь и присутствие имении в сессии
		#Включаем возможность модификации сесии
		request.session.modified = True

		if login.is_authenticated() and len(login.get_full_name()) != 0:
			request.session['test']['user'] = login.get_full_name()
			name = True
		elif len(request.session['test']['user']) == 0:
			name = False

		return HttpResponse(json.dumps({'quest': quest, 'answers': answers, 'name': name}))
	else:
		return render_to_response('test.html', {'login': login, 'test': test})
Ejemplo n.º 12
0
def test_next_quest(request):
	if request.is_ajax():
		if 'test' in request.session:
			#Включаем возможность модификации сесии
			request.session.modified = True
			#сохраняем ответы
			answers = list(map(lambda answer: {'id': answer['id'], 'selection': answer['selection']},json.loads(request.POST['answers'])))
			request.session['test']['answers'].append(answers)
			#отдаем следующий вопрос или завершаем тест
			next_question = request.session['test']['current_quset'] + 1
			if next_question <= len(request.session['test']['questions']) - 1:
				#увеличиваем индекс текущего вопроса
				request.session['test']['current_quset'] = next_question
				#находим данные
				test = Test.objects.get(id=request.session['test']['id'])
				quest = Query.objects.get(id=request.session['test']['questions'][next_question], test=test)
				answers = models_to_dict(Answer.objects.filter(query=quest))
				random.shuffle(answers)
				#проверяем включены ли подсказки и время сдачи
				test = model_to_dict(test)
				quest = model_to_dict(quest)
				if not test['time_completion']:
					quest['time'] = False
				if not test['helps']:
					quest['help'] = False

				return HttpResponse(json.dumps({'quest': quest, 'answers': answers}))
			else:
				#расчитываем результаты
				test_data = request.session['test']
				test = Test.objects.get(id=test_data['id'])
				max_points = 0
				user_points = 0
				#начинаем обработку вопросов и ответов
				for num in range(len(test_data['questions'])):
					question = Query.objects.get(id=test_data['questions'][num])
					test_data['questions'][num] = model_to_dict(question)
					max_points += test_data['questions'][num]['point']
					check_question = True
					#перебираем ответы и формируем ответ, так же полученный бал и максимально возможный балл
					for answer in test_data['answers'][num]:
						answer_data = model_to_dict(Answer.objects.get(id=answer['id'],query=question))
						if answer_data['correct'] != answer['selection']:
							check_question = False
							answer['error'] = True
						else:
							answer['error'] = False
						answer['correct'] = answer_data['correct']
						answer['text'] =  answer_data['text']
					if check_question:
						user_points += test_data['questions'][num]['point']

					test_data['questions'][num]['answers'] = test_data['answers'][num]

				#получаем процент
				user_percent = user_points * 100 / max_points
				test = model_to_dict(test)

				if user_percent >= 0 and user_percent < test['two_mark']:
					color = 'red'
					result = 2
				elif user_percent >= test['two_mark'] and user_percent < test['three_mark']:
					color = 'yellow'
					result = 3
				elif user_percent >= test['three_mark'] and user_percent < test['four_mark']:
					color = 'blue'
					result = 4
				else:
					color = 'green'
					result = 5

				#создаем объект тестируемого
				user = check_sign_in(request)
				if user.is_authenticated():
					probationer = Probationer(
						test = Test.objects.get(id=test['id']),
						user = user,
						name = test_data['user'],
						precent = round(user_percent, 1),
						mark = result,
						date = datetime.datetime.now()
					)
				else:
					probationer = Probationer(
						test = Test.objects.get(id=test['id']),
						name = test_data['user'],
						precent = round(user_percent, 1),
						mark = result,
						date = datetime.datetime.now()
					)
				probationer.save()
				#удаляем сессию
				questions = test_data['questions']
				del request.session['test']

				return HttpResponse(json.dumps({'test_result': result, 'color': color, 'questions': questions}))
		else:
			raise Http404('Отсутствует сессия')
	else:
		raise Http404('Такая страница не существует!')
Ejemplo n.º 13
0
def home(request):
    sign_in = check_sign_in(request)
    return render_to_response("home.html", {"login": sign_in})
Ejemplo n.º 14
0
def test_options(request, id):
    test = get_object_or_404(Test, id=id)
    user = check_sign_in(request)
    if test.creator == user:
        if request.is_ajax():
            if request.method == 'GET':
                questions = QuestionSerializer(Query.objects.filter(test=test), many=True).data
                options = OptionSerializer(Option.objects.filter(test=test).order_by('number'), many=True).data
                return JsonResponse({'questions': questions, 'options': options})
            elif request.method == 'POST':
                data = json.loads(request.body.decode("utf-8"))
                action = data.get('action', '')
                #добавление варианта
                if action == "addOption":
                    option = Option(
                        test = test,
                        number = data.get('number', 1)
                    )
                    option.save()
                    return JsonResponse({'id': option.id})
                elif action == "deleteOption":
                    option = get_object_or_404(Option, id=data.get('option', ''))
                    #Изменяем номера вариантов теста, которые находятся после удаляемого
                    options = Option.objects.filter(test=test, number__gt=option.number)
                    options.update(number=F('number') - 1)
                    #Удаление варианта
                    option.delete()
                    return JsonResponse({'success': True})
                elif action == "addQuestion":
                    option = get_object_or_404(Option, id=data.get('option', ''))
                    question = get_object_or_404(Query, id=data.get('question', ''))
                    option.questions.add(question)
                    return JsonResponse({'success': True})
                elif action == "deleteQuestion":
                    option = get_object_or_404(Option, id=data.get('option', ''))
                    question = get_object_or_404(Query, id=data.get('question', ''))
                    option.questions.remove(question)
                    return JsonResponse({'success': True})
                elif action == "deleteAllQuestions":
                    option = get_object_or_404(Option, id=data.get('option', ''))
                    option.questions.clear()
                    return JsonResponse({'success': True})
                elif action == "addAllQuestions":
                    option = get_object_or_404(Option, id=data.get('option', ''))
                    option.questions.clear()
                    for question in data.get('questions', ''):
                        question = get_object_or_404(Query, id=question['id'])
                        option.questions.add(question)
                    return JsonResponse({'success': True})
                elif action == "editOptionTime":
                    option = get_object_or_404(Option, id=data.get('option', ''))
                    option.time = data.get('time', 0)
                    option.save()
                    return JsonResponse({'success': True})
                elif action == "editOptionAccess":
                    option = get_object_or_404(Option, id=data.get('option', ''))
                    option.public_access = data.get('access', False)
                    option.save()
                    return JsonResponse({'success': True})
                #действие не инициализированно
                else:
                    return JsonResponse({'error': 'Action Does Not Exist'}, status=status.HTTP_404_NOT_FOUND)
        else:
            data = {'test': test, 'login': user, 'optionName': 'options'}
            data.update(csrf(request))
            return render_to_response('test_options.html', data)
    else:
        raise Http404('Вы не имете доступа!')
Ejemplo n.º 15
0
def home(request):
    sign_in = check_sign_in(request)
    return redirect('/profile/')