Example #1
0
    def get_children(self, obj: Section) -> typing.List[dict]:
        """ Возвращает потомков сериализованных потомком пункта меню """
        result = []
        if 'sections' in self.context:
            # получение дочерних разделов из контекста сверху
            children_items = list(
                filter(lambda i: i.parent_id == obj.id,
                       self.context['sections']))
            if len(children_items) > 0:
                result = SectionHierarchySerializer(children_items,
                                                    many=True,
                                                    context=self.context).data
        else:
            # получение дочерних разделов запросом в БД
            request = self.context.get('request')
            site = self._get_current_site(request) if request else None
            query = Q(is_deleted=False) & Section.get_filter_query_by_site(
                site if site else None)
            queryset = obj.get_children()\
                .extra(
                    **Section.get_extrafilter_ordering_by_site(site)
                )\
                .filter(query)\
                .prefetch_related('settings')\
                .order_by('ordering', 'order')\
                .distinct()

            # фильтрация отключенных разделов в адмикнке сайта
            if request and site and request.GET.get('is_active') == 'true':
                queryset = queryset.extra(
                    **Section.get_extrafilter_active_by_site(site))
            result = SectionHierarchySerializer(queryset,
                                                many=True,
                                                context=self.context).data
        return result
Example #2
0
    def hierarchy(self, request, *args, **kwargs) -> Response:
        """ Возвращает сериализованное дерево разделов """
        site = self._get_current_site(self.request)

        # получение разделов первого уровня
        query = Q(level=0, is_deleted=False)
        if request.GET.get('code'):
            query = Q(code=request.GET.get('code'))
        items = self.get_queryset().filter(query)
        if request.GET.get('is_active') == 'true' and site:
            # фильтрация отключенных в админке разделов
            items = items.extra(**Section.get_extrafilter_active_by_site(site))

        # получение всех разделов сайта для постороения иерархии
        query = Q(is_deleted=False)
        all_items = self.get_queryset().filter(query)
        if request.GET.get('is_active') == 'true' and site:
            # фильтрация отключенных в админке разделов
            all_items = all_items.extra(
                **Section.get_extrafilter_active_by_site(site))

        serializer_context = self.get_serializer_context()
        serializer_context.update({'sections': list(all_items)})

        return Response(
            SectionHierarchySerializer(items,
                                       many=True,
                                       context=serializer_context).data)
Example #3
0
 def get_settings(self, obj: Section):
     if self.context.get('site'):
         settings = obj.get_settings(self.context.get('site'))
         return SectionSettingsSerializer(
             settings).data if settings else None
     elif self.context.get('request') and self.context.get('request').site:
         settings = obj.get_settings(self.context.get('request').site)
         return SectionSettingsSerializer(
             settings).data if settings else None
     return None
Example #4
0
def AddSection(course_id, instructor_id, quarter, section, instructor_title, ratings):
	try:
		q = quarter[:2].upper()
		y = quarter[2:]
		#print course_id
		#print "%s %s"%(q, y)
		r = AddRating(ratings)
		i = Section(quarter = q, year = y, idinstructor = instructor_id, idcourse = course_id, idrating = r, instructortitle = instructor_title, section = section )
		i.save()
		return i.id
	except Exception, e:
		print "exception: ", e
		return None
Example #5
0
def addSection():
    form = AddSection()
    if form.validate_on_submit():
        if form.img_file.data:
            imgfile = save_picture(form.img_file.data, False)
            sect = Section(name=form.name.data,
                           img_alt=form.img_alt.data,
                           img_file=imgfile)
        else:
            sect = Section(name=form.name.data, img_alt=form.img_alt.data)
        db.session.add(sect)
        db.session.commit()
        flash(f'Section {form.name.data} created', 'success')
    return render_template('admin/addSection.html', form=form)
Example #6
0
def add_section(request):


	name=request.POST.get('section_name')
	title=request.POST.get('section_title')
	language=str(request.LANGUAGE_CODE)
	next_index=int(request.POST.get('section_index'))

	new_section=Section(section_name=name, section_title=title, section_lang=language, section_author=request.user, section_index=next_index)

	new_section.save()
	new_content=Content(section_id=new_section, text="No se ha definido contenido para esta sección")
	new_content.save()

	return HttpResponseRedirect("/")
Example #7
0
 def get_can_view(self, obj: Section) -> bool:
     """ Сериализует флаг возможности просмотра """
     if self.context.get('request'):
         site = self.context['request'].site
         return obj.is_active(site) if site else False
     else:
         return False
Example #8
0
    def get_queryset(self):
        site = self._get_current_site(self.request)

        query = Section.get_deleted_query(self.request.user)
        if site:
            query &= Section.get_filter_query_by_site(site)
        else:
            if not self.request.user.is_staff:
                query &= Q(id__isnull=True)
        return super(SectionView, self).get_queryset().filter(query)\
            .extra(
                **Section.get_extrafilter_ordering_by_site(site)
            )\
            .prefetch_related('settings')\
            .order_by('ordering', 'order')\
            .distinct()
Example #9
0
 def save_ordering(self, request, *args, **kwargs):
     """ Сохранение порядка сортировки элементов """
     if request.user.has_perm('main.change_site', request.site):
         try:
             result = []
             for item in request.data:
                 section = Section.objects.filter(
                     Section.get_filter_query_by_site(request.site)
                     & Q(id=item['id'])).first()
                 if section:
                     if item['order'] or item['order'] == 0:
                         settings = section.get_settings(request.site,
                                                         cache=False)
                         if not settings:
                             settings = SectionSettings.objects.create(
                                 site=request.site,
                                 section=section,
                             )
                         settings.order = item['order']
                         settings.save()
                     result.append(section)
             return Response(
                 SectionSerializer(
                     result,
                     many=True,
                     context=self.get_serializer_context()).data)
         except:
             logger.error('Ошибка в отправляемых данных сортировки')
             logger.error(traceback.format_exc())
             raise serializers.ValidationError(
                 'Ошибка в отправляемых данных сортировки')
     else:
         raise PermissionDenied()
Example #10
0
def frontend_urls(request):
    """
        Our javascript needs a global dictionary of url templates like:

            FRONTEND_URLS = {
                'reorder_section_node': '/casebooks/_CASEBOOK_ID/sections/_SECTION_ORDINALS/reorder/_CHILD_ORDINALS/'
            }

        These can't be generated directly from reverse() because reverse('reorder_section_node', args=['_CASEBOOK_ID', ...])
        doesn't resolve -- we need to pass in args as ints or ordinals or Casebook instances or whatever.

        This function calls reverse() with valid inputs for each url template we need, and then replaces the strings
        in the resulting url with the desired placeholders.
    """
    global _frontend_urls
    if not _frontend_urls:
        urls_in = {
            # key: [url_name, reverse_args, strings, placeholders]
            'reorder_section_node': [
                'reorder_node', [1, "2", "3"], ["1", "2", "3"],
                ['_CASEBOOK_ID', '_SECTION_ORDINALS', '_CHILD_ORDINALS']
            ],
            'reorder_casebook_node': [
                'reorder_node', [1, "2"], ["1", "2"],
                ['_CASEBOOK_ID', '_CHILD_ORDINALS']
            ],
            'new_section_or_resource':
            ['new_section_or_resource', [1], ["1"], ['$CASEBOOK_ID']],
            'search': ['search', [], [], []],
            'new_casebook': ['new_casebook', [], [], []],
            'section':
            ['section', [1, "2"], ["1", "2"], ['CASEBOOK_ID', 'SECTION_ID']],
            'casebook': ['casebook', [1], ["1"], ['_ID']],
            'export_casebook': [
                'export', [Casebook(id=1), "docx"], ["1", "docx"],
                ['_ID', '_FORMAT']
            ],
            'export_section': [
                'export', [Section(id=1), "docx"], ["1", "docx"],
                ['_ID', '_FORMAT']
            ],
            'export_resource': [
                'export', [Resource(id=1), "docx"], ["1", "docx"],
                ['_ID', '_FORMAT']
            ],
        }
        urls_out = {}
        for key, [url_name, reverse_args, strings,
                  placeholders] in urls_in.items():
            url = reverse(url_name, args=reverse_args)
            for string, placeholder in zip(strings, placeholders):
                url = url.replace(str(string), placeholder, 1)
            urls_out[key] = url
        _frontend_urls = mark_safe(json.dumps(urls_out))
    return {'frontend_urls': _frontend_urls}
Example #11
0
def AddSection(course_id, instructor_id, quarter, section, instructor_title,
               ratings):
    try:
        q = quarter[:2].upper()
        y = quarter[2:]
        #print course_id
        #print "%s %s"%(q, y)
        r = AddRating(ratings)
        i = Section(quarter=q,
                    year=y,
                    idinstructor=instructor_id,
                    idcourse=course_id,
                    idrating=r,
                    instructortitle=instructor_title,
                    section=section)
        i.save()
        return i.id
    except Exception, e:
        print "exception: ", e
        return None
Example #12
0
    def get_queryset(self):
        site = None
        query = Q()
        if self.request.GET.get('site'):
            try:
                site = Site.objects.get(id=self.request.GET.get('site'))
            except ObjectDoesNotExist:
                pass
        if site:
            query &= Section.get_filter_query_by_site(site)

        return super(SectionStaffView, self).get_queryset()\
            .filter(query)\
            .select_related('template')\
            .prefetch_related('sites')
Example #13
0
 def sections(self):
     for section in self.field_sections:
         yield Section(section, self)
Example #14
0
 def get_parents(self, obj: Section) -> typing.List[dict]:
     return SectionParentSerializer(obj.get_ancestors(ascending=False),
                                    many=True,
                                    context=self.context).data
Example #15
0
def add_section(exam_in_db, section_dict):
    # add simple properties
    properties_to_add = [
        "name", "info", "comment", "postinfo", "allowed_attempts",
        "show_correct_answer", "show_solution", "max_questions_to_attempt"
    ]
    section = Section()
    for key in properties_to_add:
        if key in section_dict and hasattr(section, key):
            setattr(section, key, section_dict[key])
    section.exam = exam_in_db

    # add compound properties
    if "marking_scheme" in section_dict:
        subdict = section_dict["marking_scheme"]
        if "correct" in subdict:
            section.correct_marks = subdict["correct"]
        if "wrong" in subdict:
            section.wrong_marks = subdict["wrong"]
        if "na" in subdict:
            section.na_marks = subdict["na"]
        if "hint_deduction" in subdict:
            section.hint_deduction = subdict["hint_deduction"]
    if "unlock" in section_dict:
        subdict = section_dict["unlock"]
        if "marks" in subdict:
            section.unlock_marks = subdict["marks"]
        if "questions" in subdict:
            section.unlock_questions = subdict["questions"]
        if "both_needed" in subdict:
            section.unlock_both_needed = subdict["both_needed"]
    if "shuffle" in section_dict:
        subdict = section_dict["shuffle"]
        if "questions" in subdict:
            section.shuffle_questions = subdict["questions"]
        if "options" in subdict:
            section.shuffle_options = subdict["options"]
    section.save()

    # add tags
    if "tags" in section_dict:
        for tagname in section_dict["tags"]:
            section.add_tag(tagname)

    # add questions
    for question_dict in section_dict["questions"]:
        add_question(section, question_dict)
Example #16
0
def add_section(exam_in_db,section_dict):
	# add simple properties
	properties_to_add=["name","info","comment","postinfo",
		"allowed_attempts",
		"show_correct_answer",
		"show_solution",
		"max_questions_to_attempt"]
	section = Section()
	for key in properties_to_add:
		if key in section_dict and hasattr(section,key):
			setattr(section,key,section_dict[key])
	section.exam = exam_in_db

	# add compound properties
	if "marking_scheme" in section_dict:
		subdict = section_dict["marking_scheme"]
		if "correct" in subdict:
			section.correct_marks = subdict["correct"]
		if "wrong" in subdict:
			section.wrong_marks = subdict["wrong"]
		if "na" in subdict:
			section.na_marks = subdict["na"]
		if "hint_deduction" in subdict:
			section.hint_deduction = subdict["hint_deduction"]
	if "unlock" in section_dict:
		subdict = section_dict["unlock"]
		if "marks" in subdict:
			section.unlock_marks = subdict["marks"]
		if "questions" in subdict:
			section.unlock_questions = subdict["questions"]
		if "both_needed" in subdict:
			section.unlock_both_needed = subdict["both_needed"]
	if "shuffle" in section_dict:
		subdict = section_dict["shuffle"]
		if "questions" in subdict:
			section.shuffle_questions = subdict["questions"]
		if "options" in subdict:
			section.shuffle_options = subdict["options"]
	section.save()

	# add tags
	if "tags" in section_dict:
		for tagname in section_dict["tags"]:
			section.add_tag(tagname)

	# add questions
	for question_dict in section_dict["questions"]:
		add_question(section,question_dict)