def passaLlista(request, pk): credentials = getImpersonateUser(request) (user, l4) = credentials #prefixes: #https://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms formset = [] impartir = Impartir.objects.get(pk=pk) #seg------------------------------- pertany_al_professor = user.pk in [ impartir.horari.professor.pk, \ impartir.professor_guardia.pk if impartir.professor_guardia else -1] if not (l4 or pertany_al_professor): raise Http404() head = '' info = {} info['old'] = unicode(impartir) info['professor'] = unicode(impartir.horari.professor) info['dia_setmana'] = unicode(impartir.horari.dia_de_la_setmana) info['dia_complet'] = impartir.dia_impartir.strftime("%d/%m/%Y") info['hora'] = unicode(impartir.horari.hora) info['assignatura'] = unicode(impartir.horari.assignatura) info['nom_aula'] = unicode(impartir.horari.nom_aula) info['grup'] = unicode(impartir.horari.grup) url_next = '/presencia/mostraImpartir/%d/%d/%d/' % ( impartir.dia_impartir.year, impartir.dia_impartir.month, impartir.dia_impartir.day) #---------------------------------Passar llista ------------------------------- if request.method == "POST": #un formulari per cada alumne de la llista totBe = True quelcomBe = False hiHaRetard = False form0 = forms.Form() formset.append(form0) for control_a in impartir.controlassistencia_set.order_by( 'alumne__grup', 'alumne'): control_a.currentUser = user form = ControlAssistenciaForm(request.POST, prefix=str(control_a.pk), instance=control_a) control_a.professor = User2Professor(user) control_a.credentials = credentials if form.is_valid(): try: control_aux = form.save() hiHaRetard |= control_aux.estat.codi_estat == "R" quelcomBe |= True except ValidationError, e: totBe = False #Com que no és un formulari de model cal tractar a mà les incidències del save: for _, v in e.message_dict.items(): form._errors.setdefault(NON_FIELD_ERRORS, []).extend(v) else: totBe = False #torno a posar el valor que hi havia ( per si el tutor l'ha justificat ) errors_formulari = form._errors form = ControlAssistenciaForm( prefix=str(control_a.pk), instance=ControlAssistencia.objects.get(id=control_a.pk)) form._errors = errors_formulari form.fields['estat'].label = control_a.alumne formset.append(form) if quelcomBe: impartir.dia_passa_llista = datetime.now() impartir.professor_passa_llista = User2Professor(request.user) impartir.currentUser = user try: impartir.save() #si hi ha retards, recordar que un retard provoca una incidència. if hiHaRetard: url_incidencies = reverse("aula__horari__posa_incidencia", kwargs={'pk': pk}) msg = u"""Has posat 'Retard', recorda que els retars provoquen incidències, s'hauran generat automàticament, valora si cal <a href="{url_incidencies}">gestionar les faltes</a>.""".format( url_incidencies=url_incidencies) messages.warning(request, SafeText(msg)) #LOGGING Accio.objects.create( tipus='PL', usuari=user, l4=l4, impersonated_from=request.user if request.user != user else None, text=u"""Passar llista: {0}.""".format(impartir)) impartir_despres_de_passar_llista(impartir) if totBe: return HttpResponseRedirect(url_next) except ValidationError, e: #Com que no és un formulari de model cal tractar a mà les incidències del save: for _, v in e.message_dict.items(): form0._errors.setdefault(NON_FIELD_ERRORS, []).extend(v)
def treemap( data: List[Dict], width: int = 1024, height: int = 768, border_color: str = "#ffffff", title_color: Dict[str, str] = None, font_size: int = 10, font_family: str = "Dejavu Sans", ) -> SafeText: """ Expects a sorted dict containing a str, and a dict with values in it. An example can be: { 'host1': {'high': 12, 'medium': 4, 'low': 0}, 'host2': {'high': 0, 'medium': 4, 'low': 0}, } With that host1 and host2 will be used as a label, high and medium will be used to find the color and values will be summed for the rectangle calculation. Data will be transformed to lists of labels, color_keys and the actual values. The color key within the data must be consistent with title_color. Parameters: data: needs to be an dict containing label, color_key and values. width: width of the svg (default 1024) height: height of the svg (default 768) border_color: color of the rectangle border (default white) title_color: the color_key to color lookup map (default _severity_class_colors) font_family - the font family used within text elements font_size - the font size used within text elements Returns: the treemap in svg as a SafeString. """ if not title_color: title_color = _severity_class_colors sizes, label, color_keys = __transform_to_tree_data(data) max_legend_len = max([len(k) for k in title_color.keys()]) s_width = width - max_legend_len * font_size - font_size sizes = __squarify(sizes, Rect(0, 0, s_width, height)) elements = "" for i, d in enumerate(sizes): label_size_in_px = len(label[i]) * font_size label_x = d.x + 1 # move half of the font size down and add a buffer for different # heights of characters (depends on font) to display the label # on the upper left corner of an rectangle. label_y = d.y + font_size / 2 + 5 max_label_len = m.ceil(d.dx / (label_size_in_px * 0.75) * len(label[i])) if d.dy <= font_size: max_label_len = 0 elements += __ELEMENT_TEMPLATE.format( x=d.x, y=d.y, width=d.dx, height=d.dy, color=title_color.get(color_keys[i]), border_color=border_color, label_x=label_x, label_y=label_y, label=label[i][:max_label_len], font_size=font_size, font_family=font_family, ) legend_start = calculate_legend_start_height(height, title_color, font_size) return SafeText( __TEMPLATE.format( width=width, height=height, rects=elements, legend=build_legend(legend_start, title_color), start_tree=width - s_width, ) )
def h_bar_chart( chart_data: Dict[str, Dict[str, int]], title_color=None, svg_width=800, bar_jump=44, orientation_marker=6, limit=10, font_family="Dejavu Sans", font_size=10, ) -> SafeText: """ Returns a stacked horizontal bar chart in svg. In order to function it needs a dict with label as key containing a dict with color key and amount. An example for valid input is: { "192.168.123.52": { "High": 3, "Medium": 3, "Low": 1 } } parameter: chart_data - The dict containing the values for the chart title_color - A colortable, defaulting to __severity_class_colors svg_width - The overall width of the output chart, default 800 bar_jump - The amount of y pixels to jump from bar element to the next. Default is 44. orientation_marker - if higher than 0 than there will be a vertical line each nth step. limit - limits the data by N first elements font_family - the font family used within text elements font_size - the font size used within text elements """ data = dict(itertools.islice(chart_data.items(), limit)) if not title_color: title_color = _severity_class_colors if not data.values(): return SafeText("") # multiply by 1.25 for kerning max_hostname_len = max(len(k) for k in data.keys()) * font_size * 1.25 max_width = svg_width - max_hostname_len - 100 # key and total placeholder # highest sum of counts max_sum = max([sum(list(counts.values())) for counts in data.values()]) if max_sum == 0: max_sum = 1 orientation_lines = "" orientation_labels = "" orientation_basis = (int(max_sum / orientation_marker) if orientation_marker > 0 else 0) if max_sum > orientation_basis and orientation_basis > 0: overhead = max_sum % orientation_basis # if it's already adjusted we don't need to add anything if overhead == 0: overhead = orientation_basis max_sum = max_sum + orientation_basis - overhead for i in range(int(max_sum / orientation_basis + 1)): x_pos = i * orientation_basis / max_sum * max_width label = str(i * orientation_basis) orientation_lines += __ORIENTATION_LINE_TEMPLATE.format( x=x_pos, height=bar_jump + 10, font_family=font_family, font_size=font_size, ) orientation_labels += __ORIENTATION_LINE_TEXT_TEMPLATE.format( x=x_pos, width=len(label), label=label, font_family=font_family, font_size=font_size, ) bars = "" for i, (key, counts) in enumerate(data.items()): element_x = 0 elements = "" for category, count in counts.items(): color = title_color.get(category) width = count / max_sum * max_width elements += __BAR_ELEMENT_TEMPLATE.format( x=element_x, width=width, color=color, font_family=font_family, font_size=font_size, max_hostname_len=max_hostname_len, ) element_x += width bars += __BAR_TEMPLATE.format( y=i * bar_jump, key=key, bar_elements=elements, orientation_lines=orientation_lines, total=sum(counts.values()), font_family=font_family, font_size=font_size, max_hostname_len=max_hostname_len, begin_total=svg_width - 100, ) svg_element_lengths = len(data.keys()) * bar_jump + 50 legend_start = calculate_legend_start_height(svg_element_lengths, title_color, font_size) svg_chart = __BAR_CHART_TEMPLATE.format( width=svg_width, height=svg_element_lengths, bars=bars, bar_legend=orientation_labels, bar_legend_y=len(data.keys()) * bar_jump + 20, legend=build_legend(legend_start, title_color), font_family=font_family, font_size=font_size, max_hostname_len=max_hostname_len, ) return SafeText(svg_chart)
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_text(self._format_value(value)) t = "<input id='" + name + "-sp' style='position:relative;left: 5px;width: 80px;' maxlength='7' value='" + \ value + "' />" js_script = "<script type='text/javascript'>" js_script = js_script + "document.getElementsByName('" + name + "')[0]" \ ".addEventListener('input', function(e){ " \ "document.getElementById('" + name + "-sp').value = this.value; });" js_script = js_script + "document.getElementById('" + name + "-sp')" \ ".addEventListener('input', function(e){ console.log(this.value); " \ "document.getElementsByName('" + name + "')[0].value = this.value; });</script>" html = format_html('<input{0} style="width:65px;"/>' + t, flatatt(final_attrs)) + SafeText(js_script) return html
def example_render_function(obj): return SafeText(timezone.now())
def detallMassiuFranjaReserves(request, year_inici, year_fi, month_inici, month_fi, day_inici, day_fi, pk): credentials = tools.getImpersonateUser(request) (user, l4) = credentials franja = get_object_or_404(FranjaHoraria, pk=pk) import datetime as t try: year_inici = int(year_inici) month_inici = int(month_inici) day_inici = int(day_inici) year_fi = int(year_fi) month_fi = int(month_fi) day_fi = int(day_fi) except: today = t.date.today() year_inici = today.year month_inici = today.month day_inici = today.day year_fi = today.year month_fi = today.month day_fi = today.day data_inici = t.date(year_inici, month_inici, day_inici) data_fi = t.date(year_fi, month_fi, day_fi) es_reservador = User.objects.filter(pk=user.pk, groups__name__in=['reservador' ]).exists() if not es_reservador: msg = u"No tens permís per reservar un bloc de dies" messages.warning(request, SafeText(msg)) q_hi_ha_docencia_abans = Q(horari__hora__hora_inici__lte=franja.hora_inici) q_hi_ha_docencia_despres = Q(horari__hora__hora_fi__gte=franja.hora_fi) hi_ha_classe_al_centre_aquella_hora = (Impartir.objects.filter( dia_impartir=data_inici).filter(q_hi_ha_docencia_abans | q_hi_ha_docencia_despres).exists()) recursos_lliures = Recurs.objects.none() if hi_ha_classe_al_centre_aquella_hora: # reservables reservable_aquella_hora = (Q(disponibilitat_horaria__isnull=True) | Q(disponibilitat_horaria=franja)) reservable_aquella_hora_ids = ( Recurs.objects.filter(reservable_aquella_hora).values_list( 'id', flat=True).distinct()) # reservats reservat = Q(reservarecurs__dia_reserva__gte=data_inici) & \ Q(reservarecurs__dia_reserva__lte=data_fi) & \ Q(reservarecurs__dia_reserva__week_day=data_inici.weekday()+2) & \ Q(reservarecurs__hora=franja) reservat_ids = (Recurs.objects.filter(reservat).values_list( 'id', flat=True).distinct()) # lliures recursos_lliures = (Recurs.objects.exclude(reservable=False).filter( pk__in=reservable_aquella_hora_ids).exclude( pk__in=reservat_ids).distinct()) if request.method == 'POST': form = RecursosForm( queryset=recursos_lliures, data=request.POST, ) if form.is_valid(): next_url = r"/recursos/tramitarReservaMassivaRecurs/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/" return HttpResponseRedirect( next_url.format(form.cleaned_data['recurs'].pk, franja.pk, year_inici, year_fi, month_inici, month_fi, day_inici, day_fi)) else: form = RecursosForm(queryset=recursos_lliures) for f in form.fields: form.fields[f].widget.attrs[ 'class'] = 'form-control ' + form.fields[f].widget.attrs.get( 'class', "") return render( request, 'form.html', { 'form': form, 'titol_formulari': u"Assistent Reserva Massiva de Material (2/3)", }, )
#TODO: cal posar en mode readonly en cas d'estat tancat el periode de qualitativa. if assignatura.codi_assignatura == assignatura.nom_assignatura: msg = u"""En l'avaluació qualitativa, al canviar el codi de la matèria o optatives (ESO i Batxillerat) o Mòdul Formatiu (Cicles) us demanaríem que escrigueu el nom en forma de Títol (no en majúscules) per unificar la visualització de matèries a l'horari quan el mirin els pares des del Djau.<br><br> Exemples:<br> <ul> <li>Matèria comuna: Nom de la matèria. P.ex. Tecnologia</li> <li>Optatives ESO: OPT Nom de la matèria. Pex, OPT Dibuix Geomètric</li> <li>Modalitat BTX: Nom de la matèria P.ex Biologia</li> <li>Mòduls CFGM: codi Nom del mòdul. P. ex. MP10 Empresa i administració</li> </ul> """ messages.warning(request, SafeText(msg)) return render( request, tipusForm, { "formset": formset, "head": u"Respostes avaluació qualitativa grup {0}".format(grup), "missatge": missatge, "errors": errors }, ) @login_required @group_required(['direcció'])
def render(self): return SafeText(u'<dt>%s</dt><dd>%s</dd>' % (self.name, self.render_value()))
def entraQualitativa(request, qualitativa_pk, assignatura_pk, grup_pk): #FormSet: Una opció seria fer servir formSet, però em sembla que #com ho estic fent ara és més fàcil per l'usuari #https://docs.djangoproject.com/en/dev/topics/forms/formsets (user, l4) = tools.getImpersonateUser(request) professor = User2Professor(user) missatge = '' tipusForm = "formset.html" errors = set() qualitativa_pk = int(qualitativa_pk) qualitativa = get_object_or_404(AvaluacioQualitativa, pk=qualitativa_pk) assignatura_pk = int(assignatura_pk) assignatura = get_object_or_404(Assignatura, pk=assignatura_pk) hi_ha_tipus_assignatura = (assignatura.tipus_assignatura is not None and assignatura.tipus_assignatura.capcelera) assignatura_label = assignatura.tipus_assignatura.capcelera if hi_ha_tipus_assignatura else u"Matèria" grup_pk = int(grup_pk) grup = get_object_or_404(Grup, pk=grup_pk) itemsQualitativa = ItemQualitativa.objects.filter( nivells__in=[grup.curs.nivell]) aquestaQualitativa = Q(qualitativa__pk=qualitativa_pk) and Q( professor=professor) and Q(assignatura=assignatura) # alumneAlta = Q( data_alta__lte = qualitativa.data_tancar_avaluacio ) & ( # Q(data_baixa__isnull = True) | # Q(data_baixa__gte = qualitativa.data_tancar_avaluacio ) # ) # alumnes = Alumne.objects.filter( # controlassistencia__impartir__horari__grup__pk = grup_pk, # controlassistencia__impartir__horari__assignatura__pk = assignatura_pk, # controlassistencia__impartir__horari__professor = professor, # controlassistencia__impartir__dia_impartir__gte = ( qualitativa.data_obrir_avaluacio - timedelta( days = 7 ) ), # controlassistencia__impartir__dia_impartir__lte = qualitativa.data_tancar_avaluacio # ).filter(alumneAlta).distinct().order_by('cognoms') q_mateix_grup = Q(controlassistencia__impartir__horari__grup=grup) q_mateixa_assignatura = Q( controlassistencia__impartir__horari__assignatura=assignatura) q_mateix_professor = Q( controlassistencia__impartir__horari__professor=professor) q_liPassemLlistaDesDe = Q(controlassistencia__impartir__dia_impartir__gte=( qualitativa.data_obrir_avaluacio - timedelta(days=7))) q_liPassemLlistaFinsA = Q( controlassistencia__impartir__dia_impartir__lte=qualitativa. data_tancar_avaluacio) q_alumnes_a_avaluar = q_mateix_grup & q_mateixa_assignatura & q_mateix_professor & q_liPassemLlistaDesDe & q_liPassemLlistaFinsA alumnes = Alumne.objects.filter(q_alumnes_a_avaluar).distinct().order_by( 'cognoms') obertaLaQualitativa = qualitativa.data_obrir_avaluacio <= date.today( ) <= qualitativa.data_tancar_avaluacio formset = [] if request.method == "POST": #un formulari per cada grup totBe = True formF = modelform_factory(Assignatura, fields=['nom_assignatura']) form = formF(request.POST, instance=assignatura, prefix=str(assignatura.pk)) form.fields['nom_assignatura'].label = assignatura_label if form.is_valid(): assignatura = form.save(commit=False) if not bool(assignatura.nom_assignatura): errors.add(u"Cal posar un nom a l'assignatura.") totBe = False else: assignatura = form.save() else: errors.add(u"Error canviant el nom de l'assignatura.") totBe = False for alumne in alumnes: form = qualitativaItemsForm(request.POST, prefix=str(alumne.pk), itemsQualitativa=itemsQualitativa) if form.is_valid(): try: #--- TODO: Begin TX ---------------------------------------------------------------- for resposta in RespostaAvaluacioQualitativa.objects.filter( alumne=alumne).filter(aquestaQualitativa): resposta.credentials = (user, l4) resposta.delete() respostes = set() if form.cleaned_data['q1']: respostes.add(form.cleaned_data['q1']) if form.cleaned_data['q2']: respostes.add(form.cleaned_data['q2']) if form.cleaned_data['q3']: respostes.add(form.cleaned_data['q3']) #if form.cleaned_data['q4']: respostes.add(form.cleaned_data['q4']) for resposta in respostes: try: novaResposta = RespostaAvaluacioQualitativa() novaResposta.alumne = alumne novaResposta.item = resposta novaResposta.professor = professor novaResposta.qualitativa = qualitativa novaResposta.assignatura = assignatura novaResposta.credentials = (user, l4) novaResposta.save() except IntegrityError as e: errors.add( u"Hi ha hagut un error assignant qualitativa a {alumne}. Comprova-ho." .format(alumne)) if form.cleaned_data['qo']: novaResposta = RespostaAvaluacioQualitativa() novaResposta.alumne = alumne novaResposta.frase_oberta = form.cleaned_data['qo'] novaResposta.professor = professor novaResposta.qualitativa = qualitativa novaResposta.assignatura = assignatura novaResposta.credentials = (user, l4) novaResposta.save() #---Fi TX--------------------------------------------------------------- except ValidationError as e: for _, v in e.message_dict.items(): for x in v: errors.add(x) totBe = False else: totBe = False for _, error in form.__errors.items(): errors.add(error) if totBe: missatge = u'Dades actualitzades correctament' else: missatge = u'Hi ha hagut errors actualitzant les dades' for missatge in errors: messages.error(request, missatge) if not bool(errors): messages.success(request, u"Dades actualitzades correctament") if totBe: #redirect url_next = r"/avaluacioQualitativa/entraQualitativa/{}/{}/{}/".format( qualitativa_pk, assignatura_pk, grup_pk) return HttpResponseRedirect(url_next) #--- Això sempre -------------------------------------------------- formF = modelform_factory(Assignatura, fields=['nom_assignatura']) form = formF(instance=assignatura, prefix=str(assignatura.pk)) formset.append(form) form.fields['nom_assignatura'].label = assignatura_label for alumne in alumnes: q1 = q2 = q3 = None qo = "" respostes = list( alumne.respostaavaluacioqualitativa_set.filter( aquestaQualitativa).filter(frase_oberta="")) nRespostes = len(respostes) if nRespostes > 0: q1 = respostes[0].item if nRespostes > 1: q2 = respostes[1].item if nRespostes > 2: q3 = respostes[2].item #if nRespostes > 3: q4 = respostes[3].item respostes = (alumne.respostaavaluacioqualitativa_set.filter( aquestaQualitativa).exclude(frase_oberta="")) if respostes.exists(): qo = respostes[0].frase_oberta form = qualitativaItemsForm(prefix=str(alumne.pk), initial={ 'alumne': alumne, 'q1': q1, 'q2': q2, 'q3': q3, 'qo': qo }, itemsQualitativa=itemsQualitativa) if not obertaLaQualitativa: form.fields['q1'].widget.attrs['disabled'] = "True" form.fields['q2'].widget.attrs['disabled'] = "True" form.fields['q3'].widget.attrs['disabled'] = "True" form.fields['qo'].widget.attrs['disabled'] = "True" tipusForm = "formset.html" #else: form.fields['alumne'].widget.attrs['style'] = "width: 400px" form.fields['q1'].widget.attrs['style'] = "width: 450px" form.fields['q2'].widget.attrs['style'] = "width: 450px" form.fields['q3'].widget.attrs['style'] = "width: 450px" form.fields['qo'].widget.attrs['style'] = "width: 450px" #tipusForm = "formsetgrid.html" formset.append(form) #TODO: cal posar en mode readonly en cas d'estat tancat el periode de qualitativa. if assignatura.codi_assignatura == assignatura.nom_assignatura: msg = u"""En l'avaluació qualitativa, al canviar el codi de la matèria o optatives (ESO i Batxillerat) o Mòdul Formatiu (Cicles) us demanaríem que escrigueu el nom en forma de Títol (no en majúscules) per unificar la visualització de matèries a l'horari quan el mirin els pares des del Djau.<br><br> Exemples:<br> <ul> <li>Matèria comuna: Nom de la matèria. P.ex. Tecnologia</li> <li>Optatives ESO: OPT Nom de la matèria. Pex, OPT Dibuix Geomètric</li> <li>Modalitat BTX: Nom de la matèria P.ex Biologia</li> <li>Mòduls CFGM: codi Nom del mòdul. P. ex. MP10 Empresa i administració</li> </ul> """ messages.warning(request, SafeText(msg)) return render( request, tipusForm, { "formset": formset, "head": u"Respostes avaluació qualitativa grup {0}".format(grup), "missatge": missatge, "errors": errors }, )
def _render_bool(self): if self.value: return SafeText(u'<span class="glyphicon glyphicon-ok"></span>') return SafeText(u'<span class="glyphicon glyphicon-remove"></span>')
def _render_url(self): return SafeText(u'<span class="text-warning">%s</span>' % self.value)
def render(self, context): from django.utils.safestring import SafeText result = self.nodelist.render(context) return SafeText(result)
def get(self,app,self_view,context): request = self_view.request if app.routeid is None: app.routeid = 1 flow = Flow() workflowtype = flow.getWorkFlowTypeFromApp(app) flow.get(workflowtype) context = flow.getAccessRights(request,context,app.routeid,workflowtype) context = flow.getCollapse(context,app.routeid,workflowtype) context = flow.getHiddenAreas(context,app.routeid,workflowtype) context['workflow'] = flow.getAllRouteConf(workflowtype,app.routeid) context['workflow_actions'] = flow.getAllRouteActions(app.routeid,workflowtype) context['formcomponent'] = flow.getFormComponent(app.routeid,workflowtype) context['workflowoptions'] = flow.getWorkflowOptions() try: LocObj = Location.objects.get(application_id=self_view.object.id) context['certificate_of_title_volume'] = LocObj.title_volume context['folio'] = LocObj.folio context['diagram_plan_deposit_number'] = LocObj.dpd_number context['location'] = LocObj.location context['reserve_number'] = LocObj.reserve context['street_number_and_name'] = LocObj.street_number_name context['town_suburb'] = LocObj.suburb context['lot'] = LocObj.lot context['nearest_road_intersection'] = LocObj.intersection except: donothing = '' context['publication_newspaper'] = PublicationNewspaper.objects.filter(application_id=self_view.object) context['publication_website'] = PublicationWebsite.objects.filter(application_id=self_view.object) if self_view.object.river_lease_scan_of_application: context['river_lease_scan_of_application_short'] = SafeText(self_view.object.river_lease_scan_of_application.upload.name)[19:] if self_view.object.document_draft: context['document_draft_short'] = SafeText(self_view.object.document_draft.upload.name)[19:] if self_view.object.document_final: context['document_final_short'] = SafeText(self_view.object.document_final.upload.name)[19:] if self_view.object.deed: context['deed_short'] = SafeText(self_view.object.deed.upload.name)[19:] context['land_owner_consent_list'] = [] landoc = app.land_owner_consent.all() for doc in landoc: fileitem = {} fileitem['fileid'] = doc.id fileitem['path'] = doc.upload.name fileitem['path_short'] = SafeText(doc.upload.name)[19:] context['land_owner_consent_list'].append(fileitem) context['publication_newspaper_list'] = [] pub_news_obj = [] pub_news_mod = PublicationNewspaper.objects.filter(application_id=self_view.object) for pubrow in pub_news_mod: rowitem = {} rowitem['pk'] = pubrow.pk rowitem['id'] = pubrow.id rowitem['date'] = pubrow.date rowitem['newspaper'] = pubrow.newspaper rowitem['application'] = pubrow.application rowitem['records'] = pubrow.records rowitem['documents_short'] = [] records = pubrow.records.all() for doc in records: fileitem = {} fileitem['fileid'] = doc.id fileitem['path'] = doc.upload fileitem['path_short'] = SafeText(doc.upload.name)[19:] rowitem['documents_short'].append(fileitem) context['publication_newspaper_list'].append(rowitem) pub_feed_obj = [] pub_feed_mod = PublicationFeedback.objects.filter(application_id=self_view.object) for pubrow in pub_feed_mod: rowitem = {} rowitem['id'] = pubrow.id rowitem['name'] = pubrow.name rowitem['address'] = pubrow.address rowitem['suburb'] = pubrow.suburb rowitem['state'] = pubrow.state rowitem['postcode'] = pubrow.postcode rowitem['phone'] = pubrow.phone rowitem['email'] = pubrow.email rowitem['comments'] = pubrow.comments rowitem['records'] = pubrow.records rowitem['documents_short'] = [] # needed so we can add documents to list rowitem['status'] = pubrow.status rowitem['application'] = pubrow.application records = pubrow.records.all() for doc in records: fileitem = {} fileitem['fileid'] = doc.id fileitem['path'] = doc.upload fileitem['path_short'] = SafeText(doc.upload.name)[19:] rowitem['documents_short'].append(fileitem) pub_feed_obj.append(rowitem) context['publication_feedback'] = pub_feed_obj new_documents_to_publish = {} pub_web = PublicationWebsite.objects.filter(application_id=self_view.object.id) for pub_doc in pub_web: if pub_doc.published_document_id: doc = Record.objects.get(id=pub_doc.published_document_id) fileitem = {} fileitem['fileid'] = doc.id fileitem['path'] = doc.upload.name new_documents_to_publish[pub_doc.original_document_id] = fileitem orignaldoclist = [] if self_view.object.river_lease_scan_of_application: fileitem = {} fileitem['fileid'] = self_view.object.river_lease_scan_of_application.id fileitem['path'] = self_view.object.river_lease_scan_of_application.upload.name fileitem['path_short'] = SafeText(self_view.object.river_lease_scan_of_application.upload.name)[19:] fileitem['group_name'] = "River Lease Scan of Application" if self_view.object.river_lease_scan_of_application.id in new_documents_to_publish: fileitem['publish_doc'] = new_documents_to_publish[self_view.object.river_lease_scan_of_application.id]['path'] fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[self_view.object.river_lease_scan_of_application.id]['path'])[19:] orignaldoclist.append(fileitem) if self_view.object.deed: fileitem = {} fileitem['fileid'] = self_view.object.deed.id fileitem['path'] = self_view.object.deed.upload.name fileitem['path_short'] = SafeText(self_view.object.deed.upload.name)[19:] fileitem['group_name'] = "Deed" if self_view.object.deed.id in new_documents_to_publish: fileitem['publish_doc'] = new_documents_to_publish[self_view.object.deed.id]['path'] fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[self_view.object.deed.id]['path'])[19:] orignaldoclist.append(fileitem) landoc = app.land_owner_consent.all() for doc in landoc: fileitem = {} fileitem['fileid'] = doc.id fileitem['path'] = doc.upload.name fileitem['path_short'] = SafeText(doc.upload.name)[19:] fileitem['group_name'] = "Land Owner Consent" if doc.id in new_documents_to_publish: fileitem['publish_doc'] = new_documents_to_publish[doc.id]['path'] fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[doc.id]['path'])[19:] else: fileitem['publish_doc'] = "" fileitem['publish_doc_short'] = "" orignaldoclist.append(fileitem) doclist = app.proposed_development_plans.all() for doc in doclist: fileitem = {} fileitem['fileid'] = doc.id fileitem['path'] = doc.upload.name fileitem['path_short'] = SafeText(doc.upload.name)[19:] fileitem['group_name'] = "Proposed Development Plans" if doc.id in new_documents_to_publish: fileitem['publish_doc'] = new_documents_to_publish[doc.id]['path'] fileitem['publish_doc_short'] = SafeText(new_documents_to_publish[doc.id]['path'])[19:] else: fileitem['publish_doc'] = "" fileitem['publish_doc_short'] = "" orignaldoclist.append(fileitem) context['original_document_list'] = orignaldoclist doclist = app.proposed_development_plans.all() context['proposed_development_plans_list'] = [] for doc in doclist: fileitem = {} fileitem['fileid'] = doc.id fileitem['path'] = doc.upload.name fileitem['path_short'] = SafeText(doc.upload.name)[19:] context['proposed_development_plans_list'].append(fileitem) return context
def model_admin_url(obj: Model, name: str = None) -> str: url = resolve_url(admin_urlname(obj._meta, SafeText("change")), obj.pk) return format_html(f'<a href="{url}">{name or str(obj)}</a>')
def detallFranjaReserves(request, year, month, day, pk): credentials = tools.getImpersonateUser(request) (user, l4) = credentials franja = get_object_or_404(FranjaHoraria, pk=pk) import datetime as t try: year = int(year) month = int(month) day = int(day) except: today = t.date.today() year = today.year month = today.month day = today.day data = t.date(year, month, day) tretze_dies = timedelta(days=13) darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta( days=datetime.today().weekday()) es_reservador = User.objects.filter(pk=user.pk, groups__name__in=['reservador' ]).exists() if not es_reservador and (data > darrer_dia_reserva or data < datetime.today().date()): msg = u"Aquesta data no permet fer reserves. Només es pot des d'avui i fins al dia {0}".format( darrer_dia_reserva) messages.warning(request, SafeText(msg)) q_hi_ha_docencia_abans = Q(horari__hora__hora_inici__lte=franja.hora_inici) q_hi_ha_docencia_despres = Q(horari__hora__hora_fi__gte=franja.hora_fi) hi_ha_classe_al_centre_aquella_hora = (Impartir.objects.filter( dia_impartir=data).filter(q_hi_ha_docencia_abans | q_hi_ha_docencia_despres).exists()) recursos_lliures = Recurs.objects.none() if hi_ha_classe_al_centre_aquella_hora: # reservables reservable_aquella_hora = (Q(disponibilitat_horaria__isnull=True) | Q(disponibilitat_horaria=franja)) reservable_aquella_hora_ids = ( Recurs.objects.filter(reservable_aquella_hora).values_list( 'id', flat=True).distinct()) # reservats reservat = Q(reservarecurs__dia_reserva=data) & Q( reservarecurs__hora=franja) reservat_ids = (Recurs.objects.filter(reservat).values_list( 'id', flat=True).distinct()) # lliures recursos_lliures = (Recurs.objects.exclude(reservable=False).filter( pk__in=reservable_aquella_hora_ids).exclude( pk__in=reservat_ids).distinct()) if request.method == 'POST': form = RecursosForm( queryset=recursos_lliures, data=request.POST, ) if form.is_valid(): next_url = r"/recursos/tramitarReservaRecurs/{0}/{1}/{2}/{3}/{4}/" return HttpResponseRedirect( next_url.format(form.cleaned_data['recurs'].pk, franja.pk, year, month, day)) else: form = RecursosForm(queryset=recursos_lliures) for f in form.fields: form.fields[f].widget.attrs[ 'class'] = 'form-control ' + form.fields[f].widget.attrs.get( 'class', "") return render( request, 'form.html', { 'form': form, 'titol_formulari': u"Assistent Reserva de Recurs (2/3)", }, )
def __str__(self): return SafeText(self.author) + ' | ' \ + SafeText(self.experiment.id) + ' | ' \ + SafeText(self.order)
def tramitarReservaRecurs(request, pk_recurs=None, pk_franja=None, year=None, month=None, day=None): credentials = tools.getImpersonateUser(request) (user, l4) = credentials recurs = Recurs.objects.filter(pk=pk_recurs).first() franja = FranjaHoraria.objects.filter(pk=pk_franja).first() import datetime as t try: year = int(year) month = int(month) day = int(day) except: today = t.date.today() year = today.year month = today.month day = today.day data = t.date(year, month, day) tretze_dies = timedelta(days=13) darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta( days=datetime.today().weekday()) es_reservador = User.objects.filter(pk=user.pk, groups__name__in=['reservador' ]).exists() if not es_reservador and (data > darrer_dia_reserva or data < datetime.today().date()): msg = u"Reserva NO realitzada. Només es pot des d'avui i fins al dia {0}".format( darrer_dia_reserva) messages.warning(request, SafeText(msg)) return HttpResponseRedirect(r'/recursos/lesMevesReservesDeRecurs/') novaReserva = ReservaRecurs(recurs=recurs, hora=franja, dia_reserva=data, usuari=user, es_reserva_manual=True) if request.method == 'POST': form = reservaRecursForm(request.POST, instance=novaReserva) if form.is_valid(): try: reserva = form.save() missatge = u"Reserva realitzada correctament" messages.success(request, missatge) return HttpResponseRedirect( r'/recursos/lesMevesReservesDeRecurs/') except ValidationError as e: for _, v in e.message_dict.items(): form._errors.setdefault(NON_FIELD_ERRORS, []).extend(v) else: form = reservaRecursForm(instance=novaReserva) for f in ['recurs', 'dia_reserva', 'hora', 'motiu']: form.fields[f].widget.attrs[ 'class'] = 'form-control ' + form.fields[f].widget.attrs.get( 'class', "") return render( request, 'form.html', { 'form': form, 'head': u'Reservar material', 'titol_formulari': u"Assistent Reserva de Material (3/3)", }, )
def detallAulaReserves(request, year, month, day, pk): credentials = tools.getImpersonateUser(request) (user, l4) = credentials aula = get_object_or_404(Aula, pk=pk) # import datetime as t try: year = int(year) month = int(month) day = int(day) except: today = t.date.today() year = today.year month = today.month day = today.day data = t.date(year, month, day) tretze_dies = timedelta(days=13) darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta( days=datetime.today().weekday()) if data > darrer_dia_reserva or data < datetime.today().date(): msg = u"Aquesta data no permet fer reserves. Només es pot des d'avui i fins al dia {0}".format( darrer_dia_reserva) messages.warning(request, SafeText(msg)) # reserves_dun_dia_un_aula = (ReservaAula.objects.filter(aula=aula).filter( dia_reserva=data)) # franges_del_dia = (FranjaHoraria.objects.filter( horari__impartir__dia_impartir=data).order_by('hora_inici')) primera_franja = franges_del_dia.first() darrera_franja = franges_del_dia.last() # -- si l'aula presenta un horari restringit q_horari_restringit = Q() disponibilitatHoraria = [ franja.pk for franja in aula.disponibilitat_horaria.all() ] if bool(disponibilitatHoraria): franges_reservades = [ reserva.hora.pk for reserva in reserves_dun_dia_un_aula ] q_horari_restringit = Q(pk__in=disponibilitatHoraria + franges_reservades) # franges_reservables = (FranjaHoraria.objects.filter( hora_inici__gte=primera_franja.hora_inici).filter( hora_fi__lte=darrera_franja.hora_fi).filter(q_horari_restringit) ) if primera_franja and darrera_franja else [] horariAula = [] for franja in franges_reservables: reserva = reserves_dun_dia_un_aula.filter( hora=franja).order_by().first() nova_franja = {} nova_franja['franja'] = franja nova_franja['reserva'] = reserva assignatures_list = (reserva.impartir_set.filter( horari__assignatura__nom_assignatura__isnull=False).values_list( 'horari__assignatura__nom_assignatura', flat=True).distinct()) if reserva else [] nova_franja['assignatura'] = u", ".join( assignatures_list) if reserva else u"" grup_list = (reserva.impartir_set.filter( horari__grup__descripcio_grup__isnull=False).values_list( 'horari__grup__descripcio_grup', flat=True).distinct()) if reserva else [] nova_franja['grup'] = u", ".join(grup_list) if reserva else u"" nova_franja['professor'] = u", ".join( [reserva.usuari.first_name + ' ' + reserva.usuari.last_name]) if reserva else u"" nova_franja['reservable'] = not bool(reserva) and aula.reservable nova_franja['eliminable'] = bool( reserva) and reserva.usuari.pk == user.pk nova_franja['aula'] = aula nova_franja['dia'] = data horariAula.append(nova_franja) table = HorariAulaTable(horariAula) table.order_by = 'franja' RequestConfig(request).configure(table) return render( request, 'mostraInfoReservaAula.html', { 'table': table, 'aula': aula, 'dia': data, 'titol_formulari': u"Assistent Reserva d'Aula (2/3)", }, )
def tramitarReservaMassivaRecurs(request, pk_recurs=None, pk_franja=None, year_inici=None, year_fi=None, month_inici=None, month_fi=None, day_inici=None, day_fi=None): credentials = tools.getImpersonateUser(request) (user, l4) = credentials recurs = Recurs.objects.filter(pk=pk_recurs).first() franja = FranjaHoraria.objects.filter(pk=pk_franja).first() import datetime as t try: year_inici = int(year_inici) month_inici = int(month_inici) day_inici = int(day_inici) year_fi = int(year_fi) month_fi = int(month_fi) day_fi = int(day_fi) except: today = t.date.today() year_inici = today.year month_inici = today.month day_inici = today.day year_fi = today.year month_fi = today.month day_fi = today.day data_inici = t.date(year_inici, month_inici, day_inici) data_fi = t.date(year_fi, month_fi, day_fi) es_reservador = User.objects.filter(pk=user.pk, groups__name__in=['reservador' ]).exists() if not es_reservador: msg = u"No tens permís per reservar un bloc de dies" messages.warning(request, SafeText(msg)) return HttpResponseRedirect(r'/recursos/lesMevesReservesDeRecurs/') novaReserva = ReservaRecurs(recurs=recurs, hora=franja, dia_reserva=data_inici, usuari=user, es_reserva_manual=True) infoForm = [ ('Data inici reserva', data_inici), ('Data fi reserva', data_fi), ] if request.method == 'POST': novaReserva = ReservaRecurs(recurs=recurs, hora=franja, dia_reserva=data_inici, usuari=user, es_reserva_manual=False) form = reservaMassivaRecursForm(request.POST, instance=novaReserva) if form.is_valid(): try: reserva = form.save(commit=False) dates = [] numdies = (data_fi - data_inici).days for x in range(0, numdies + 1, 7): dates.append(data_inici + timedelta(days=x)) for data in dates: reserva.pk = None reserva.dia_reserva = data reserva.save() missatge = u"Reserva realitzada correctament" messages.success(request, missatge) # missatge al professor: dies_setmana = { 0: 'dilluns', 1: 'dimarts', 2: 'dimecres', 3: 'dijous', 4: 'divendres' } missatge = PROFESSOR_RESERVA_MASSIVA txt = missatge.format(novaReserva.recurs, dies_setmana[data_inici.weekday()], data_inici, data_fi, novaReserva.hora) tipus_de_missatge = tipusMissatge(missatge) msg = Missatge(remitent=user, text_missatge=txt, tipus_de_missatge=tipus_de_missatge) importancia = 'PI' destinatari = reserva.usuari msg.envia_a_usuari(destinatari, importancia) return HttpResponseRedirect( r'/recursos/lesMevesReservesDeRecurs/') except ValidationError as e: for _, v in e.message_dict.items(): form._errors.setdefault(NON_FIELD_ERRORS, []).extend(v) else: form = reservaMassivaRecursForm(instance=novaReserva) for f in ['recurs', 'dia_reserva', 'hora', 'motiu']: form.fields[f].widget.attrs[ 'class'] = 'form-control ' + form.fields[f].widget.attrs.get( 'class', "") return render( request, 'form.html', { 'form': form, 'infoForm': infoForm, 'head': u'Reservar material', 'titol_formulari': u"Assistent Reserva Massiva de Material (3/3)", }, )
def tramitarReservaAula(request, pk_aula=None, pk_franja=None, year=None, month=None, day=None): credentials = tools.getImpersonateUser(request) (user, l4) = credentials aula = Aula.objects.filter(pk=pk_aula).first() franja = FranjaHoraria.objects.filter(pk=pk_franja).first() # import datetime as t try: year = int(year) month = int(month) day = int(day) except: today = t.date.today() year = today.year month = today.month day = today.day data = t.date(year, month, day) tretze_dies = timedelta(days=13) darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta( days=datetime.today().weekday()) if data > darrer_dia_reserva or data < datetime.today().date(): msg = u"Reserva NO realitzada. Només es pot des d'avui i fins al dia {0}".format( darrer_dia_reserva) messages.warning(request, SafeText(msg)) return HttpResponseRedirect(r'/aules/lesMevesReservesDAula/') # novaReserva = ReservaAula(aula=aula, hora=franja, dia_reserva=data, usuari=user, es_reserva_manual=True) # if request.method == 'POST': form = reservaAulaForm(request.POST, instance=novaReserva) if form.is_valid(): try: es_canvi_aula = (form.cleaned_data['mou_alumnes'] == 'C') if es_canvi_aula: reserva = form.save(commit=False) q_es_meva = Q(horari__professor__pk=user.pk) | Q( professor_guardia__pk=user.pk) q_mateix_dia_i_hora = Q( dia_impartir=reserva.dia_reserva) & Q( horari__hora=reserva.hora) q_te_reserva = Q(reserva__isnull=False) impartir = ( Impartir.objects.filter(q_es_meva & q_mateix_dia_i_hora & q_te_reserva).first()) if bool(impartir): #canvio d'aula l'antiga reserva impartir.reserva.aula = reserva.aula impartir.reserva.motiu = reserva.motiu impartir.reserva.es_reserva_manual = True impartir.reserva.save() missatge = u"Canvi d'aula realitzat correctament" messages.success(request, missatge) else: #creo la nova reserva reserva.save() missatge = u"No s'ha trobat docència a aquella hora, però la reserva queda feta." messages.success(request, missatge) else: reserva = form.save() missatge = u"Reserva realitzada correctament" messages.success(request, missatge) return HttpResponseRedirect(r'/aules/lesMevesReservesDAula/') except ValidationError, e: for _, v in e.message_dict.items(): form._errors.setdefault(NON_FIELD_ERRORS, []).extend(v)
def __str__(self): return SafeText('<img src="{0}" />'.format(self.image.thumbnail.url))
def get_snippet_relation(relationset): """ Get a text snippet for a :class:`annotations.models.RelationSet` instance. """ appellation_type = ContentType.objects.get_for_model(Appellation) tokenizedContent = relationset.occursIn.tokenizedContent annotated_words = [] # We'll use this to label highlighted tokens with their interpretations. annotation_map = {} fields = [ 'source_content_type_id', 'object_content_type_id', 'source_object_id', 'object_object_id', 'predicate__tokenIds', 'predicate__interpretation__label', 'predicate__interpretation_id', ] appellation_ids = set() # Pull out all Appellations that have a specific textual basis. for relation in relationset.constituents.values(*fields): for part in ['source', 'object']: if relation.get('%s_content_type_id' % part, None) == appellation_type.id: appellation_ids.add(relation['%s_object_id' % part]) # Predicates too, since we're interested in evidence for the relation. if relation['predicate__tokenIds']: tokenIds = relation['predicate__tokenIds'].split(',') annotated_words.append(tokenIds) for t in tokenIds: annotation_map[t] = relation['predicate__interpretation__label'] appellation_fields = [ 'tokenIds', 'interpretation__label', 'interpretation_id', 'interpretation__merged_with_id', 'interpretation__merged_with__label', ] for appellation in Appellation.objects.filter(pk__in=appellation_ids).values(*appellation_fields): tokenIds = appellation['tokenIds'].split(',') annotated_words.append(tokenIds) for t in tokenIds: if appellation['interpretation__merged_with_id']: annotation_map[t] = appellation['interpretation__merged_with__label'] else: annotation_map[t] = appellation['interpretation__label'] # Group sequences of tokens from appellations together if they are in close # proximity. grouped_words = [] for tokenSeq in sorted(annotated_words, key=lambda s: min([int(t) for t in s])): tokenSeqI = [int(t) for t in tokenSeq] match = False for i, tokensSeqGrouped in enumerate(grouped_words): tokensSeqGroupedI = [int(t) for t in tokensSeqGrouped] # If the current token sequence is contained within or overlaps with # the token sequence group, then add it to the current group and # exit. if (min(tokenSeqI) >= min(tokensSeqGroupedI) - 10 and max(tokenSeq) <= max(tokensSeqGroupedI) + 10) or \ (min(tokenSeqI) - 10 <= min(tokensSeqGroupedI) <= max(tokenSeqI) + 10) or \ (max(tokenSeqI) + 10 >= max(tokensSeqGroupedI) >= min(tokenSeqI) - 10): grouped_words[i] = tokensSeqGrouped + tokenSeq match = True break if not match: # Sequence belongs to its own group (for now). grouped_words.append(tokenSeq) # Now build the snippet. combined_snippet = u"" for tokenSeq in grouped_words: snippet = u"" start_index = max(0, min([int(t) for t in tokenSeq])) - 5 end_index = max([int(t) for t in tokenSeq]) + 5 for i in range(start_index, end_index): match = re.search(r'<word id="'+str(i)+'">([^<]*)</word>', tokenizedContent, re.M|re.I) if not match: continue word = "" if str(i) in tokenSeq: # Tooltip shows the interpretation (Concept) for this # Appellation. word = u"<strong data-toggle='tooltip' title='%s' class='text-warning text-snippet'>%s</strong>" % (annotation_map[str(i)], match.group(1)) else: word = match.group(1) snippet = u'%s %s' % (snippet, word) combined_snippet += u' ...%s... ' % snippet.strip() return SafeText(combined_snippet)
def sortidaEdit(request, pk=None, clonar=False, origen=False): credentials = tools.getImpersonateUser(request) (user, _) = credentials es_post = (request.method == "POST") professor = User2Professor(user) professors_acompanyen_abans = set() professors_acompanyen_despres = set() professors_organitzen_abans = set() professors_organitzen_despres = set() fEsDireccioOrGrupSortides = request.user.groups.filter( name__in=[u"direcció", u"sortides"]).exists() if bool(pk) and not clonar: instance = get_object_or_404(Sortida, pk=pk) potEntrar = (professor in instance.professors_responsables.all() or professor in instance.altres_professors_acompanyants.all() or fEsDireccioOrGrupSortides) if not potEntrar: raise Http404 professors_acompanyen_abans = set( instance.altres_professors_acompanyants.all()) professors_organitzen_abans = set( instance.professors_responsables.all()) elif bool(pk) and clonar: instance = get_object_or_404(Sortida, pk=pk) instance.pk = None instance.estat = 'E' instance.titol_de_la_sortida = u"**CLONADA** " + instance.titol_de_la_sortida instance.esta_aprovada_pel_consell_escolar = 'P' instance.professor_que_proposa = professor # instance.professors_responsables = None # instance.altres_professors_acompanyants = None # instance.tutors_alumnes_convocats = None # instance.alumnes_convocats = None # instance.alumnes_que_no_vindran = None # instance.alumnes_justificacio = None # instance.professor_que_proposa_id = None else: instance = Sortida() instance.professor_que_proposa = professor instance.credentials = credentials exclude = ( 'alumnes_convocats', 'alumnes_que_no_vindran', 'alumnes_justificacio', ) formIncidenciaF = modelform_factory(Sortida, exclude=exclude) if request.method == "POST": post_mutable = request.POST.copy() if 'esta_aprovada_pel_consell_escolar' not in post_mutable: post_mutable['esta_aprovada_pel_consell_escolar'] = 'P' form = formIncidenciaF(post_mutable, instance=instance) if form.is_valid(): form.save() if origen == "Meves": messages.warning( request, SafeText(u"""RECORDA: Una vegada enviades les dades, has de seleccionar els <a href="{0}">alumnes convocats</a> i els <a href="{1}">alumnes que no hi van</a> des del menú desplegable ACCIONS""".format( "/sortides/alumnesConvocats/{id}".format( id=instance.id), "/sortides/alumnesFallen/{id}".format(id=instance.id), ))) professors_acompanyen_despres = set( instance.altres_professors_acompanyants.all()) professors_organitzen_despres = set( instance.professors_responsables.all()) acompanyen_nous = professors_acompanyen_despres - professors_acompanyen_abans organitzen_nous = professors_organitzen_despres - professors_organitzen_abans #helper missatges: data_inici = u"( data activitat encara no informada )" if instance.data_inici is not None: data_inici = """del dia {dia}""".format( dia=instance.data_inici.strftime('%d/%m/%Y')) #missatge a acompanyants: txt = u"""Has estat afegit com a professor acompanyant a l'activitat {sortida} {dia} """.format(sortida=instance.titol_de_la_sortida, dia=data_inici) enllac = reverse('sortides__sortides__edit_by_pk', kwargs={'pk': instance.id}) msg = Missatge(remitent=user, text_missatge=txt, enllac=enllac) for nou in acompanyen_nous: importancia = 'VI' msg.envia_a_usuari(nou, importancia) #missatge a responsables: txt = u"""Has estat afegit com a professor responsable a l'activitat {sortida} {dia} """.format(sortida=instance.titol_de_la_sortida, dia=data_inici) msg = Missatge(remitent=user, text_missatge=txt) for nou in organitzen_nous: importancia = 'VI' msg.envia_a_usuari(nou, importancia) nexturl = r"/sortides/sortides{origen}".format(origen=origen) return HttpResponseRedirect(nexturl) else: form = formIncidenciaF(instance=instance) form.fields['data_inici'].widget = DateTextImput() form.fields['data_fi'].widget = DateTextImput() #form.fields['estat'].widget = forms.RadioSelect( choices = form.fields['estat'].widget.choices ) widgetBootStrapButtonSelect = bootStrapButtonSelect() widgetBootStrapButtonSelect.choices = form.fields['estat'].widget.choices form.fields['estat'].widget = widgetBootStrapButtonSelect form.fields["alumnes_a_l_aula_amb_professor_titular"].widget.attrs[ 'style'] = u"width: 3%" form.fields["calendari_public"].widget.attrs['style'] = u"width: 3%" for f in form.fields: form.fields[f].widget.attrs[ 'class'] = ' form-control ' + form.fields[f].widget.attrs.get( 'class', "") form.fields['calendari_desde'].widget = DateTimeTextImput() form.fields['calendari_finsa'].widget = DateTimeTextImput() form.fields['termini_pagament'].widget = DateTimeTextImput() if not fEsDireccioOrGrupSortides: form.fields["esta_aprovada_pel_consell_escolar"].widget.attrs[ 'disabled'] = u"disabled" form.fields["codi_de_barres"].widget.attrs['disabled'] = u"disabled" form.fields["informacio_pagament"].widget.attrs[ 'disabled'] = u"disabled" #si no és propietari tot a disabled deshabilitat = (instance.id and not (professor in instance.professors_responsables.all() or fEsDireccioOrGrupSortides)) if deshabilitat: for field in form.fields: form.fields[field].widget.attrs['disabled'] = u"disabled" form.fields['estat'].label += u": {0} ".format( instance.get_estat_display()) return render( request, 'formSortida.html', { 'form': form, 'head': 'Sortides', 'missatge': 'Sortides', 'deshabilitat': '1==1' if deshabilitat else '1==2', }, )
def show_times(self, instance): html = SafeText("<br>".join( str(time) for time in instance.times.all())) if not html: html = "None" return html
def view_link(self): url = f'https://www.openstreetmap.org/#map=19/{self.latitude}/{self.longitude}' return SafeText(f'<a target="_blank" href="{url}">OpenStreetMap</a>')
def event_image(self, instance): image = instance.images.first() if image: return SafeText("""<img src="{}" alt="Event image" />""".format( image.thumb().url))
def settemplate(self, value): self.objInclude.template.filters = [] self.objInclude.template.tocken = value self.objInclude.template.var = SafeText(value)
def detallRecursReserves(request, year, month, day, pk): credentials = tools.getImpersonateUser(request) (user, l4) = credentials recurs = get_object_or_404(Recurs, pk=pk) # import datetime as t try: year = int(year) month = int(month) day = int(day) except: today = t.date.today() year = today.year month = today.month day = today.day data = t.date(year, month, day) tretze_dies = timedelta(days=13) darrer_dia_reserva = datetime.today().date() + tretze_dies - timedelta( days=datetime.today().weekday()) es_reservador = User.objects.filter(pk=user.pk, groups__name__in=['reservador' ]).exists() if not es_reservador and (data > darrer_dia_reserva or data < datetime.today().date()): msg = u"Aquesta data no permet fer reserves. Només es pot des d'avui i fins al dia {0}".format( darrer_dia_reserva) messages.warning(request, SafeText(msg)) reserves_dun_dia_un_recurs = (ReservaRecurs.objects.filter( recurs=recurs).filter(dia_reserva=data)) franges_del_dia = (FranjaHoraria.objects.filter( horari__impartir__dia_impartir=data).order_by('hora_inici')) primera_franja = franges_del_dia.first() darrera_franja = franges_del_dia.last() # -- si el recurs presenta un horari restringit q_horari_restringit = Q() disponibilitatHoraria = [ franja.pk for franja in recurs.disponibilitat_horaria.all() ] if bool(disponibilitatHoraria): franges_reservades = [ reserva.hora.pk for reserva in reserves_dun_dia_un_recurs ] q_horari_restringit = Q(pk__in=disponibilitatHoraria + franges_reservades) franges_reservables = (FranjaHoraria.objects.filter( hora_inici__gte=primera_franja.hora_inici).filter( hora_fi__lte=darrera_franja.hora_fi).filter(q_horari_restringit) ) if primera_franja and darrera_franja else [] horariRecurs = [] for franja in franges_reservables: reserva = reserves_dun_dia_un_recurs.filter( hora=franja).order_by().first() nova_franja = {} nova_franja['franja'] = franja nova_franja['reserva'] = reserva nova_franja['professor'] = u", ".join( [reserva.usuari.first_name + ' ' + reserva.usuari.last_name]) if reserva else u"" nova_franja['reservable'] = not bool(reserva) and recurs.reservable nova_franja['eliminable'] = bool( reserva) and reserva.usuari.pk == user.pk nova_franja['recurs'] = recurs nova_franja['dia'] = data horariRecurs.append(nova_franja) table = HorariRecursTable(horariRecurs) table.order_by = 'franja' RequestConfig(request).configure(table) return render( request, 'mostraInfoReservaRecurs.html', { 'table': table, 'recurs': recurs, 'dia': data, 'titol_formulari': u"Assistent Reserva de Material (2/3)", }, )
def get_identifier(cls, instance): """ Hook to return a description for the current model. """ return SafeText()
def model_admin_url(self, instance: BaseModel, name: str = None) -> str: """ Helper to return a URL to another object """ url = resolve_url(admin_urlname(instance._meta, SafeText("change")), instance.pk) return format_html('<a href="{}">{}</a>', url, name or str(instance))