def test_escapejs_does_not_break_on_empty_picture(self):
     """A Picture object can be passed to Django's escapejs"""
     pic = Picture()
     try:
         escapejs(pic)
     except TypeError:
         self.fail("escapejs() raised TypeError on empty picture!")
Пример #2
0
 def render(self, name, value, attrs=None):
     if attrs is not None:
         attrs = dict(self.attrs.items() + attrs.items())
     if value is not None and not isinstance(value, basestring):
         value = [edit_string_for_tags([o.tag]) for o in value.select_related("tag")]
     else:
         if value is not None:
             value = value.split(",")
         else:
             value = []
     html = super(TagAutocomplete, self).render("%s_dummy" % name, ",".join(value), attrs)
     allow_add = "false"
     if "allow_add" in attrs and attrs["allow_add"]:
         allow_add = "true"
     js_config = u"""{startText: "%s", \
         preFill: prefill, \
         allowAdd: %s, \
         allowAddMessage: "%s"}""" % (
         escapejs(_("Enter Tag Here")),
         allow_add,
         escapejs(_("Please choose an existing tag")),
     )
     js = u"""<script type="text/javascript">jQuery = django.jQuery; \
         jQuery().ready(function() { \
         var prefill = [];
         jQuery.each(jQuery('input[name="%s_dummy"]').val().split(','),function(i,v){prefill.push({'value': v})});
         jQuery("#%s").autoSuggest("%s", \
         %s); });</script>""" % (
         name,
         attrs["id"],
         reverse("taggit-list"),
         js_config,
     )
     return mark_safe("\n".join([html, js]))
Пример #3
0
 def insert_stack(self, request, placeholder_id):
     placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
     form = StackInsertionForm(initial={"language_code": request.GET.get("language_code", "")})
     if request.method == "POST":
         form = StackInsertionForm(data=request.POST)
         if form.is_valid():
             context = {"CMS_MEDIA_URL": get_cms_setting("MEDIA_URL"), "is_popup": True, "cancel": False}
             if form.cleaned_data["insertion_type"] == StackInsertionForm.INSERT_LINK:
                 cms_plugin = add_plugin(
                     placeholder, StackPlugin, form.cleaned_data["language_code"], stack=form.cleaned_data["stack"]
                 )
                 context.update(
                     {
                         "plugin": cms_plugin,
                         "type": cms_plugin.get_plugin_name(),
                         "plugin_id": cms_plugin.pk,
                         "icon": force_escape(escapejs(cms_plugin.get_instance_icon_src())),
                         "alt": force_escape(escapejs(cms_plugin.get_instance_icon_alt())),
                     }
                 )
             else:
                 plugin_ziplist = copy_plugins_to(
                     list(form.cleaned_data["stack"].content.get_plugins()), placeholder
                 )
                 # TODO: once we actually use the plugin context in the frontend, we have to support multiple plugins
             return TemplateResponse(request, "admin/cms/page/plugin/confirm_form.html", context)
     return TemplateResponse(request, "admin/stacks/insert_stack.html", {"form": form})
Пример #4
0
 def render(self, name, value, attrs=None):
     if attrs is not None:
         attrs = dict(self.attrs.items() + attrs.items())
 
     list_view = reverse('taggit-list')
     if value is not None and not isinstance(value, basestring):
         value = edit_string_for_tags(
           [o.tag for o in value.select_related("tag")]
         )
     html = super(TagAutocomplete, self).render(
         name+"_dummy",
         u'',
         attrs
     )
     allow_add = "false"
     if 'allow_add' in attrs and attrs['allow_add']:
         allow_add = "true"
     js_config = u"{startText: \"%s\", \
         preFill: \"%s\", \
         allowAdd: %s, \
         allowAddMessage: \"%s\"}" % (
             escapejs(_("Enter Tag Here")),
             escapejs(value) if value else u'',
             allow_add,
             escapejs(_("Please choose an existing tag")),
         )
     js = u"<script type=\"text/javascript\">jQuery = django.jQuery; \
         jQuery().ready(function() { jQuery(\"#%s\").autoSuggest(\"%s\", \
         %s); });</script>" % (
             attrs['id'],
             list_view,
             js_config
         )
     return mark_safe("\n".join([html, js]))
Пример #5
0
 def render(self, name, value, attrs=None):
     if attrs is not None:
         attrs = dict(self.attrs.items() + attrs.items())
     list_view = reverse("taggit-list")
     if value is not None and not isinstance(value, basestring):
         value = simplejson.dumps(
             [{"value": u"%s" % edit_string_for_tags([o.tag])} for o in value.select_related("tag")]
         )
     else:
         value = []
     html = super(TagAutocomplete, self).render(name + "_dummy", u"", attrs)
     allow_add = "false"
     if "allow_add" in attrs and attrs["allow_add"]:
         allow_add = "true"
     js_config = (
         u'{startText: "%s", \
         preFill: %s, \
         allowAdd: %s, \
         allowAddMessage: "%s"}'
         % (escapejs(_("Enter Tag Here")), value, allow_add, escapejs(_("Please choose an existing tag")))
     )
     js = (
         u'<script type="text/javascript">jQuery = django.jQuery; \
         jQuery().ready(function() { jQuery("#%s").autoSuggest("%s", \
         %s); });</script>'
         % (attrs["id"], list_view, js_config)
     )
     return mark_safe("\n".join([html, js]))
Пример #6
0
def gtag_track_event(category, action, label):
    """
    This is the most recent style. the gtag snippet replaced the universal track event
    """
    return mark_safe("onClick=\"gtag('event', '{action}', {{'event_category': '{category}', 'event_label': '{label}'}});\"".format(  # noqa: E501
        category=escapejs(category),
        action=escapejs(action),
        label=escapejs(label).replace("\\u002D", "-"),
    ))
Пример #7
0
 def response_add(self, request, obj, post_url_continue='../%s/'):
     if '_popup' in request.REQUEST:
         if '_subclass' in request.REQUEST:
             pk_value = obj._get_pk_val()
             class_name = obj.__class__.__name__.lower()
             return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s", "%s");</script>' % \
                 # escape() calls force_unicode.
                 (escape(pk_value), escapejs(obj), escapejs(class_name)))
     return super(SchemaModelAdmin, self).response_add(request, obj, post_url_continue)
Пример #8
0
	def response_change(self, request, obj):
		print "General.widgets:response_change"
		if '_popup' in request.REQUEST:
			pk_value = obj._get_pk_val()
			print "This is pop redirect to" + '<script type="text/javascript">opener.dismissEditRelatedPopup(window, "%s", "%s");</script>' % \
			(escape(pk_value), escapejs(obj))
			return HttpResponse('<script type="text/javascript">opener.dismissEditRelatedPopup(window, "%s", "%s");</script>' % \
			# escape() calls force_unicode.
			(escape(pk_value), escapejs(obj)))
		else:
			return super(ForeignKeyRawIdWidgetWrapperAdmin, self).response_change(request, obj)
Пример #9
0
 def get_login_url(self, request, **kwargs):
     method = kwargs.pop("method", self.get_method())
     if method == "js_sdk":
         next = "'%s'" % escapejs(kwargs.get("next") or "")
         process = "'%s'" % escapejs(kwargs.get("process") or AuthProcess.LOGIN)
         action = "'%s'" % escapejs(kwargs.get("action") or AuthAction.AUTHENTICATE)
         ret = "javascript:allauth.facebook.login(%s, %s, %s)" % (next, action, process)
     else:
         assert method == "oauth2"
         ret = super(FacebookProvider, self).get_login_url(request, **kwargs)
     return ret
Пример #10
0
def gmap_map_url(loc_obj, **kwargs):
    loc_obj.street = escapejs(loc_obj.street)
    url = str('http://maps.google.com/maps?oe=utf-8&channel=fs'
              '&q={0.street}+{0.city}+{0.state}+{0.postal_code}'
              '&um=1&ie=UTF-8&hq=&hnear=0x88569e570df5e7b5:0x388208bd6f2fdcba,'
              '{0.street}+{0.city}+{0.state}+{0.postal_code}&gl=us'
              '&ei=ypq-T873B8Tdggf2rIG0CQ&sa=X&oi=geocode_result&ct=title'
              .format(loc_obj))
    if kwargs.get('js', False):
        return escapejs(url).replace("'", "\'")
    else:
        return url
Пример #11
0
def gen_protocol_data(request):

    personfield = ekeutils.get_eke_list("person")
    publicationfield = ekeutils.get_eke_list("publication")
    organfield = ekeutils.get_eke_list("organ")
    fundedsitefield = ekeutils.get_eke_list("fundedsite")
    programfield = ekeutils.get_eke_list("program")
    data = {"action" : "New" ,
                    "pis" : personfield ,
                    "cis" : personfield ,
                    "custodians" : personfield ,
                    "publications" : publicationfield ,
                    "organs" : organfield ,
                    "fundedsites" : fundedsitefield,
                    "programs" : programfield
            }
    if request.method == 'GET':
        protocolid = request.GET.get('id')
        if protocolid:
            #generate protocol info from db
            obj = protocol.objects.get(pk=int(protocolid))
            data = { "action" : "Edit",
                    "id" : obj.id,
                    "pis" : personfield ,
                    "custodians" : personfield ,
                    "publications" : publicationfield ,
                    "cis" : personfield ,
                    "organs" : organfield ,
                    "fundedsites" : fundedsitefield ,
                    "programs" : programfield ,
                    "title" : obj.title,
                    "shortname" : obj.shortname,
                    "organ_link_id" : [ opl.organid for opl in list(organ_protocol_link.objects.filter(protocolid=int(protocolid))) ],
                    "pi_link_id" : ",".join([ str(ppl.personid)+":"+person.objects.filter(id=ppl.personid)[0].firstname+" "+person.objects.filter(id=ppl.personid)[0].lastname for ppl in list(pi_protocol_link.objects.filter(protocolid=int(protocolid))) ]),
                    "ci_link_id" : ",".join([ str(ppl.personid)+":"+person.objects.filter(id=ppl.personid)[0].firstname+" "+person.objects.filter(id=ppl.personid)[0].lastname for ppl in list(ci_protocol_link.objects.filter(protocolid=int(protocolid))) ]),
                    "cus_link_id" : ",".join([ str(ppl.personid)+":"+person.objects.filter(id=ppl.personid)[0].firstname+" "+person.objects.filter(id=ppl.personid)[0].lastname for ppl in list(protocol_custodian_link.objects.filter(protocolid=int(protocolid))) ]),
                    "fundedsite_link_id" : [ fun.fundedsiteid for fun in list(fundedsite_protocol_link.objects.filter(protocolid=int(protocolid))) ],
                    "program_link_id" : [ fun.programid for fun in list(protocol_program_link.objects.filter(protocolid=int(protocolid))) ],
                    "pub_link_id" : [ ppl.publicationid for ppl in list(protocol_publication_link.objects.filter(protocolid=int(protocolid))) ],
                    "start_date" : str(obj.start_date),
                    "end_date" : str(obj.end_date),
                    "irb_approval" : obj.irb_approval,
                    "irb_contact" : obj.irb_contact ,
                    "site_contact" : obj.site_contact ,
                    "irb_contact_email" : obj.irb_contact_email ,
                    "site_contact_email" : obj.site_contact_email ,
                    "irb_approval_num" : obj.irb_approval_num,
                    "hum_sub_train" : obj.hum_sub_train,
                    "abstract" : escapejs(obj.abstract),
                    "aims" : escapejs(obj.aims)
                   }
    return data
Пример #12
0
 def get_login_url(self, request, **kwargs):
     method = kwargs.get('method', self.get_method())
     if method == 'js_sdk':
         next = "'%s'" % escapejs(kwargs.get('next') or '')
         process = "'%s'" % escapejs(kwargs.get('process') or AuthProcess.LOGIN)
         action = "'%s'" % escapejs(kwargs.get('action') or AuthAction.AUTHENTICATE)
         ret = "javascript:allauth.facebook.login(%s, %s, %s)" \
             % (next, action, process)
     else:
         assert method == 'oauth2'
         ret = super(FacebookProvider, self).get_login_url(request,
                                                           **kwargs)
     return ret
Пример #13
0
 def save_and_continue_in_popup(self, obj, request):
     '''
     For related popups, send the javascript that triggers
     (a) reloading the popup, and
     (b) updating the parent field with the ID of the object we just edited.
     '''
     pk_value = obj._get_pk_val()
     msg = _('The %(name)s "%(obj)s" was saved successfully. You may edit ' \
         'it again below.') % {'name': obj._meta.verbose_name, 'obj': obj} 
     self.message_user(request, msg)
     post_url_continue = '../%s/?_popup=1'
     return HttpResponse('<script type="text/javascript">opener.saveAndContinuePopup(window, "%s", "%s", "%s");</script>' % \
         # escape() calls force_unicode.
         (escape(pk_value), escapejs(obj), escapejs(post_url_continue % pk_value)))
Пример #14
0
    def response_add(self, request, obj, post_url_continue=None):
        pk_value = obj._get_pk_val()

        if IS_POPUP_VAR in request.POST:
            to_field = request.GET.get(TO_FIELD_VAR)
            if to_field:
                attr = str(to_field)
            else:
                attr = obj._meta.pk.attname
            value = obj.serializable_value(attr)
            custom_crop = reverse(
                'admin:%s_%s_add'
                % (self.model._meta.app_label, CustomCrop._meta.model_name), current_app=admin.site.name
            )
            parametros = {
                'pk_value': escape(pk_value), # for possible backwards-compatibility
                'value': escape(value),
                'obj': escapejs(obj),
                'is_photo': True,
                'imagesize': '',
            }
            if request.GET.get('photosize'):
                IMAGE_SIZES = getattr(settings, 'PHOTOLOGUE_IMAGE_SIZES', {})
                im = IMAGE_SIZES.get(request.GET.get('photosize'), ())
                obj._get_SIZE_url(request.GET.get('photosize'));
                if len(im) > 2:
                    for ims in im[2]:
                        obj._get_SIZE_url(ims);
                parametros.update({
                    'photo_url': escape(obj._get_SIZE_url('admin_thumbnail')),
                    'crop_url': ''.join([custom_crop, '?_to_field=id&_popup=1&photo_id=', escape(value), '&photosize_id=', str(PhotoSize.objects.get(name=request.GET.get('photosize')).id)]),
                })
            return SimpleTemplateResponse('admin/photopicker_popup_response.html', parametros)
        return super(PhotoAdmin, self).response_add(request, obj, post_url_continue)
Пример #15
0
 def response_post_save_change(self, request, obj):
     if "_popup" in request.REQUEST:
         return SimpleTemplateResponse('admin/popup_response.html', {
             'pk_value': escape(obj.pk),
             'obj': escapejs(obj)
         })
     return super(TranslationAdmin, self).response_post_save_change(request, obj)
Пример #16
0
 def render_tag(self, context, **kwargs):
     try:
         from django.utils.html import escapejs
     except ImportError:
         from django.utils.text import javascript_quote as escapejs
     rendered = self.nodelist.render(context)
     return u"'%s'" % escapejs(rendered.strip())
Пример #17
0
    def response_add(self, request, obj, post_url_continue='../%s/'):
        """
        Determines the HttpResponse for the add_view stage.
        Adapted from "django/contrib/admin/optons.py"
        """
        opts = obj._meta
        pk_value = obj._get_pk_val()

        msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
        # Here, we distinguish between different save types by checking for
        # the presence of keys in request.POST.
        if "_continue" in request.POST:
            self.message_user(request, msg + ' ' + _("You may edit it again below."))
            if "_popup" in request.POST:
                post_url_continue += "?_popup=1"
            return HttpResponseRedirect(post_url_continue % pk_value)

        if "_popup" in request.POST:
            return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                # escape() calls force_unicode.
                (escape(pk_value), escapejs(obj)))
        elif "_addanother" in request.POST:
            self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
            return HttpResponseRedirect(request.path)
        else:
            self.message_user(request, msg)
            # Redirect to in-page editing view
            post_url = obj.get_absolute_url()
            return HttpResponseRedirect(post_url)
Пример #18
0
 def response_change(self, request, obj):
     response = super(LegislaturaAdmin, self).response_change(request, obj)
     if "_popup" in request.POST:
         response = HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' %
                                 # escape() calls force_unicode.
                                 (escape(obj.pk), escapejs(obj)))
     return response
Пример #19
0
def content_stylesheets(stylesheets):
    output = ""
    for stylesheet in stylesheets:
        output += 'jQuery.loadStyleSheet("%s", "%s");\n' % (html.escapejs(stylesheet['href']), html.escapejs(stylesheet.get('type', 'text/css')))
    if output:
        output = '<script type="text/javascript">\n' + output + '</script>\n'
    return safestring.mark_safe(output)
Пример #20
0
    def __init__(self, filter_tag=None):
        nodes = set()
        ## fill in edges
        self.dataEdges = []
        if not filter_tag:
            proxies = Proxy.objects.all()
        else:
            #might be slow
            #select edges with the correct tag
            proxies = Proxy.objects.filter(tags__pk = filter_tag.pk).filter(isdefault=False)
            #select default edges from delegating people not in the previous set
            proxies = proxies | (Proxy.objects.filter(isdefault=True).exclude(delegating__in = proxies.values('delegating')))

        for proxy in proxies:
            if proxy.delegating.isActive():
                nodes.add(proxy.delegating.display_name)
                for delegate in proxy.delegates.all():
                    if delegate.isActive():
                        nodes.add(delegate.display_name)
                        if proxy.tags.count():
                            self.dataEdges.append(r"['{}', '{}', {{color: '{}', label: '{}'}}]".format(
                                proxy.delegating.display_name,
                                delegate.display_name,
                                '#0C3',
                                ', '.join([escapejs(tag.name) for tag in proxy.tags.all()]),
                            ))
                        else:
                            self.dataEdges.append(r"['{}', '{}', {{color: '{}'}}]".format(
                                proxy.delegating.display_name,
                                delegate.display_name,
                                '#000'
                            ))
        ## fill in nodes
        self.dataNodes = list(nodes)
Пример #21
0
    def render(self, context):
        try:
            poll = self.poll.resolve(context)
        except template.VariableDoesNotExist:
            return '%s does not exist' % str(self.poll)

        #Every poll get an id so that we can apply js/css to it.
        #This is where we can actually store our custom variables...
        #From: http://stackoverflow.com/questions/2566265/is-there-a-django-template-tag-that-lets-me-set-a-context-variable
        POLLCOUNTKEY = "pollcount"
        c = context.dicts[0] 
        pollcount = c[POLLCOUNTKEY] if POLLCOUNTKEY in c else 0
        c[POLLCOUNTKEY] = pollcount + 1

        choices = "\n".join([
            '<input type="submit" value="' + choice.choice + '" name="choice" />'
            for choice in poll.choice_set.all()])

        data = ','.join([ "['%s',%d]" % (escapejs(str(choice)), votes) for (choice, votes) in poll.results()])
        choiceIds = ','.join([ str(c.id) for c in poll.choice_set.all() ])

        return poll_html % {
            "image_URL": poll.get_image_url(),
            "vote_URL": poll.get_vote_url(),
            "choices":choices,
            "csrf": context.get('csrf_token', None),
            "id":pollcount,
            "data":data,
            "choiceIds": choiceIds
        }
Пример #22
0
    def response_add(self, request, obj, post_url_continue='../%s/'):
        """
        Determines the HttpResponse for the add_view stage.
        """
        opts = obj._meta
        pk_value = obj._get_pk_val()

        msg = "Item(s) were added successfully" 
        # Here, we distinguish between different save types by checking for
        # the presence of keys in request.POST.
        if "_continue" in request.POST:
            self.message_user(request, msg + ' ' + _("You may edit it again below."))
            if "_popup" in request.POST:
                post_url_continue += "?_popup=1"
            return HttpResponseRedirect(post_url_continue % pk_value)

        if "_popup" in request.POST:
            return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                # escape() calls force_unicode.
                (escape(pk_value), escapejs(obj)))
        elif "_addanother" in request.POST:
            self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
            return HttpResponseRedirect(request.path)
        else:
            self.message_user(request, msg)
            for item in Item.objects.filter(created = obj):
                if not item.user:
                	item.user = request.user
                	item.save()
            # Figure out where to redirect. If the user has change permission,
            # redirect to the change-list page for this object. Otherwise,
            # redirect to the admin index.
            return HttpResponseRedirect(reverse("admin:todo_item_changelist"))
Пример #23
0
 def response_change(self, request, obj):
     if "_popup" in request.POST:
         pk_value = obj._get_pk_val()
         return HttpResponse('<script type="text/javascript">opener.dismissEditPopup(window, "%s", "%s", %s);</script>' % \
             # escape() calls force_unicode.
             (escape(pk_value), escapejs(obj), json.dumps(self.popup_attrs(obj))))
     return super(RelatedToolsAdmin, self).response_change(request, obj)
Пример #24
0
def js_escaped_string(string_for_js):
    """
    Mako filter that escapes text for use in a JavaScript string.

    If None is provided, returns an empty string.

    Usage:
        Used as follows in a Mako template inside a <SCRIPT> tag::

            var my_string_for_js = "${my_string_for_js | n, js_escaped_string}"

        The surrounding quotes for the string must be included.

        Use the "n" Mako filter above.  It is possible that the default filter
        may include html escaping in the future, and this ensures proper
        escaping.

        Mako's default filter decode.utf8 is applied here since this default
        filter is skipped in the Mako template with "n".

    Arguments:
        string_for_js (string): Text to be properly escaped for use in a
            JavaScript string.

    Returns:
        (string) Text properly escaped for use in a JavaScript string as
        unicode.  Returns empty string if argument is None.

    """
    if string_for_js is None:
        string_for_js = ""
    string_for_js = decode.utf8(string_for_js)
    string_for_js = escapejs(string_for_js)
    return string_for_js
Пример #25
0
def admin_thumbnail(request):
    content = u""
    if request.method == "POST" and request.is_ajax():
        form = ThumbnailForm(request.POST)
        if not form.is_valid():
            return HttpResponseBadRequest(form.errors)
        data = form.cleaned_data

        obj = data["id"]
        dimensions = "%sx%s" % (data["width"], data["height"])

        if obj.type == "image":
            image = None
            try:
                image = feincms_thumbnail.thumbnail(obj.file.name, dimensions)
            except:
                pass

            if image:
                try:
                    caption = obj.translation.caption
                except AttributeError:
                    caption = _(u"untitled").encode("utf-8")
                content = json.dumps({"url": image.url, "name": escapejs(caption)})
        return HttpResponse(content, mimetype="application/json")
    else:
        return HttpResponseForbidden()
Пример #26
0
	def response_add(self, request, obj, post_url_continue='../%s/'):
		"""
		Determines the HttpResponse for the add_view stage.
		"""
		opts = obj._meta
		pk_value = obj._get_pk_val()

		msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
		# Here, we distinguish between different save types by checking for
		# the presence of keys in request.POST.
		if "_continue" in request.POST:
			self.message_user(request, msg + ' ' + _("You may edit it again below."))
			if "_popup" in request.POST:
				post_url_continue += "?_popup=1"
			return HttpResponseRedirect(post_url_continue % pk_value)

		if "_popup" in request.POST:
			return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
				# escape() calls force_unicode.
				(escape(pk_value), escapejs(obj)))
		elif "_addanother" in request.POST:
			self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
			return HttpResponseRedirect(request.path)
		else:
			self.message_user(request, msg)

			# Figure out where to redirect. If the user has change permission,
			# redirect to the change-list page for this object. Otherwise,
			# redirect to the admin index.
			if self.has_change_permission(request, None):
				post_url = '../'
			else:
				post_url = '../../../'
			return HttpResponseRedirect(post_url)
Пример #27
0
def admin_thumbnail(request):
    content = u''
    if request.method == 'POST' and request.is_ajax():
        form = ThumbnailForm(request.POST)
        if not form.is_valid():
            return HttpResponseBadRequest(form.errors)
        data = form.cleaned_data

        obj = data['id']
        dimensions = '%sx%s' % (data['width'], data['height'])

        if obj.type == 'image':
            image = None
            try:
                image = feincms_thumbnail.thumbnail(obj.file.name, dimensions)
            except:
                pass

            if image:
                content = json.dumps({
                    'url': image.url,
                    'name': escapejs(obj.translation.caption)
                    })
        return HttpResponse(content, mimetype='application/json')
    else:
        return HttpResponseForbidden()
Пример #28
0
 def response_change(self, request, obj):
     if "_popup" in request.POST:
         pk_value = obj._get_pk_val()
         return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
             # escape() calls force_unicode.
             (escape(pk_value), escapejs(obj)))
     return super(RuleAdmin, self).response_change(request, obj)
Пример #29
0
def gen_committee_data(request):
    programfield = [ [str(obj.id), str(obj.title)] for obj in list(program.objects.all()) ]
    programfield.sort(key=lambda x: x[1].lower())
    personfield = ekeutils.get_eke_list("person")
    data = {"action" : "New" ,
        "members" : personfield ,
        "chairs" : personfield ,
        "cochairs" : personfield ,
        "programs" : programfield ,
       }
    if request.method == 'GET':
        committeeid = request.GET.get('id')
        if committeeid:
            obj = committee.objects.get(pk=int(committeeid))
            data = { "action" : "Edit",
                    "id" : obj.id,
                    "description" : escapejs(obj.description),
                    "abbreviation" : obj.abbreviation,
                    "member_link_id" : ",".join([ str(ppl.personid)+":"+person.objects.filter(id=ppl.personid)[0].firstname+" "+person.objects.filter(id=ppl.personid)[0].lastname for ppl in list(committee_member_link.objects.filter(committeeid=int(committeeid))) ]),
                    "chair_link_id" : ",".join([ str(ppl.personid)+":"+person.objects.filter(id=ppl.personid)[0].firstname+" "+person.objects.filter(id=ppl.personid)[0].lastname for ppl in list(committee_chair_link.objects.filter(committeeid=int(committeeid))) ]),
                    "cochair_link_id" : ",".join([ str(ppl.personid)+":"+person.objects.filter(id=ppl.personid)[0].firstname+" "+person.objects.filter(id=ppl.personid)[0].lastname for ppl in list(committee_cochair_link.objects.filter(committeeid=int(committeeid))) ]),
                    "program_link_id" : [ fpl.programid for fpl in list(committee_program_link.objects.filter(committeeid=int(committeeid))) ],
                    "members" : personfield ,
                    "chairs" : personfield ,
                    "cochairs" : personfield ,
                    "programs" : programfield ,
                    "title" : obj.title ,
                   }
    return data
Пример #30
0
  def response_change(self, request, obj):
    """
    Determines the HttpResponse for the change_view stage.
    """
    if '_popup' in request.POST:
      to_field = request.POST.get('_to_field')
      attr = str(to_field) if to_field else obj._meta.pk.attname
      # Retrieve the `object_id` from the resolved pattern arguments.
      value = request.resolver_match.args[0]
      new_value = obj.serializable_value(attr)
      return SimpleTemplateResponse('admin/popup_response.html', {
        'action': 'change',
        'value': escape(value),
        'obj': escapejs(obj),
        'new_value': escape(new_value),
      })

    opts = self.model._meta
    pk_value = obj._get_pk_val()
    preserved_filters = self.get_preserved_filters(request)

    msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
    if "_continue" in request.POST:
      # Translators: Translation included with Django
      msg = _('The %(name)s "%(obj)s" was changed successfully. You may edit it again below.') % msg_dict
      self.message_user(request, msg, messages.SUCCESS)
      redirect_url = request.prefix + request.path
      redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
      return HttpResponseRedirect(redirect_url)

    elif "_saveasnew" in request.POST:
      # Translators: Translation included with Django
      msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict
      self.message_user(request, msg, messages.SUCCESS)
      redirect_url = request.prefix + reverse(
        'admin:%s_%s_change' % (opts.app_label, opts.model_name),
        args=(pk_value,),
        current_app=self.admin_site.name
        )
      redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
      return HttpResponseRedirect(redirect_url)

    elif "_addanother" in request.POST:
      # Translators: Translation included with Django
      msg = _('The %(name)s "%(obj)s" was added successfully. You may add another %(name)s below.') % msg_dict
      self.message_user(request, msg, messages.SUCCESS)
      redirect_url = request.prefix + reverse(
        'admin:%s_%s_add' % (opts.app_label, opts.model_name),
        current_app=self.admin_site.name
        )
      redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
      return HttpResponseRedirect(redirect_url)

    else:
      # Translators: Translation included with Django
      msg = _('The %(name)s "%(obj)s" was changed successfully.') % msg_dict
      self.message_user(request, msg, messages.SUCCESS)
      # Redirect to previous url
      return HttpResponseRedirect("%s%s" % (request.prefix, request.session['crumbs'][request.prefix][-2][2]))
Пример #31
0
def mptt_items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """
    first = True
    pk = cl.lookup_opts.pk.attname

    # #### MPTT ADDITION START
    # figure out which field to indent
    mptt_indent_field = getattr(cl.model_admin, 'mptt_indent_field', None)
    if not mptt_indent_field:
        for field_name in cl.list_display:
            try:
                f = cl.lookup_opts.get_field(field_name)
            except models.FieldDoesNotExist:
                if (mptt_indent_field is None
                        and field_name != 'action_checkbox'):
                    mptt_indent_field = field_name
            else:
                # first model field, use this one
                mptt_indent_field = field_name
                break
    # #### MPTT ADDITION END

    # figure out how much to indent
    mptt_level_indent = getattr(cl.model_admin, 'mptt_level_indent',
                                MPTT_ADMIN_LEVEL_INDENT)

    for field_name in cl.list_display:
        row_class = ''
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except (AttributeError, ObjectDoesNotExist):
            result_repr = get_empty_value_display(cl)
        else:
            if f is None:
                if field_name == 'action_checkbox':
                    row_class = ' class="action-checkbox"'
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    result_repr = _boolean_icon(value)
                else:
                    result_repr = smart_text(value)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if not allow_tags:
                    result_repr = conditional_escape(result_repr)
                else:
                    result_repr = mark_safe(result_repr)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = get_empty_value_display(cl)
                    else:
                        result_repr = escape(field_val)
                else:
                    try:
                        result_repr = display_for_field(value, f)
                    except TypeError:
                        # Changed in Django 1.9, now takes 3 arguments
                        result_repr = display_for_field(
                            value, f, get_empty_value_display(cl))

                if isinstance(f, models.DateField)\
                        or isinstance(f, models.TimeField)\
                        or isinstance(f, models.ForeignKey):
                    row_class = ' class="nowrap"'
        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')

        # #### MPTT ADDITION START
        if field_name == mptt_indent_field:
            level = getattr(result, result._mptt_meta.level_attr)
            padding_attr = ' style="padding-%s:%spx"' % (
                'right' if get_language_bidi() else 'left',
                8 + mptt_level_indent * level)
        else:
            padding_attr = ''
        # #### MPTT ADDITION END

        # If list_display_links not defined, add the link tag to the first field
        if (first and not cl.list_display_links
            ) or field_name in cl.list_display_links:
            table_tag = {True: 'th', False: 'td'}[first]
            first = False
            url = cl.url_for_result(result)
            # Convert the pk to something that can be used in Javascript.
            # Problem cases are long ints (23L) and non-ASCII strings.
            if cl.to_field:
                attr = str(cl.to_field)
            else:
                attr = pk
            value = result.serializable_value(attr)
            result_id = escapejs(value)
            # #### MPTT SUBSTITUTION START
            yield mark_safe('<%s%s%s><a href="%s"%s>%s</a></%s>' % (
                table_tag,
                row_class,
                padding_attr,
                url,
                (cl.is_popup and
                 ' onclick="opener.dismissRelatedLookupPopup(window, &#39;%s&#39;); return false;"'
                 % result_id or ''),  # noqa
                conditional_escape(result_repr),
                table_tag))
            # #### MPTT SUBSTITUTION END
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if (form and field_name in form.fields
                    and not (field_name == cl.model._meta.pk.name
                             and form[cl.model._meta.pk.name].is_hidden)):
                bf = form[field_name]
                result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
            else:
                result_repr = conditional_escape(result_repr)
            # #### MPTT SUBSTITUTION START
            yield mark_safe('<td%s%s>%s</td>' %
                            (row_class, padding_attr, result_repr))
            # #### MPTT SUBSTITUTION END
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield mark_safe('<td>%s</td>' %
                        force_text(form[cl.model._meta.pk.name]))
Пример #32
0
def escapejs_filter(value):
    """Hex encodes characters for use in JavaScript strings."""
    return escapejs(value)
Пример #33
0
    def test_widget_with_default_settings(self):
        """
            Test the widget with default settings which is defined in django settings file
        """
        zoom = 15
        default_map_center = [51.5073509, -0.12775829999]
        widget_settings = {
            "GooglePointFieldWidget": (
                ("zoom", zoom),
                ("mapCenterLocation", default_map_center),
            )
        }

        with override_settings(MAP_WIDGETS=widget_settings):
            reload_module(mw_widgets)
            widget = mw_widgets.GooglePointFieldInlineWidget()
            self.assertEqual(hasattr(widget, "settings"), True)
            self.assertEqual(hasattr(widget, "settings_namespace"), True)
            self.assertEqual(isinstance(widget.media, django_forms.Media),
                             True)

            # test `map_options` method
            options_str = widget.map_options()
            options = json.loads(options_str)
            self.assertEqual(options.get("zoom"), zoom)
            self.assertEqual(options.get("mapCenterLocation"),
                             default_map_center)

            # test render with Point object value
            point = Point(-104.9903, 39.7392)
            widget_html_elem_id = "id_location"
            widget_html_elem_name = "location"
            result = widget.render(name=widget_html_elem_name,
                                   value=point,
                                   attrs={'id': widget_html_elem_id})
            self.assertIn(widget.serialize(point), result)
            self.assertIn(
                get_textarea_html(widget_html_elem_id, widget_html_elem_name,
                                  point), result)

            # test render with serialized data value
            result = widget.render(name=widget_html_elem_name,
                                   value=widget.serialize(point))
            self.assertIn(widget.serialize(point), result)

            # test widget as a formset empty form
            result = widget.render(name=widget_html_elem_name,
                                   value=point,
                                   attrs={'id': widget_html_elem_id})
            self.assertIn(widget.serialize(point), result)
            inline_widget_data = widget.get_js_widget_data(
                widget_html_elem_name, widget_html_elem_id)
            self.assertIn(escapejs(json.dumps(inline_widget_data)), result)

            # test widget `attrs` param
            w = mw_widgets.GooglePointFieldInlineWidget(
                attrs={"max-height": 600})
            self.assertIn("max-height", w.attrs)

            # test widget render `attrs` param with `None` value
            self.assertIn(
                widget_html_elem_name,
                w.render(name=widget_html_elem_name, value=None, attrs=None))
Пример #34
0
def escapejs(value):
    """Hex encodes characters for use in JavaScript strings."""
    from django.utils.html import escapejs
    return escapejs(value)
Пример #35
0
    def post(self, request, id=None):
        print "id is: %s" % id
        if '_popup' in request.GET:
            template = 'create_organization_popup.html'
        else:
            template = 'create_organization.html'
        organization = None

        if id:
            organization = get_object_or_404(
                Organization, id=id, user=request.user)
        form = OrganizationForm(
            request.POST, request.FILES, instance=organization)
        if form.is_valid():
            pending = form.save(commit=False)
            pending.user = request.user
            pending.save()
            if '_popup' in request.GET:
                return HttpResponse('<html><body><script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script></body></html>' % (escape(pending.pk), escapejs(pending)))
            return HttpResponseRedirect(reverse('applicants_organization'))
        else:
            return render(request, template, {'title': 'edit organization', 'form': form})
Пример #36
0
    def render(self, name, value, attrs=None, choices=()):
        if not self.autofill_url:
            raise IOError("autofill_url not defined")
        # Initialization
        controller = self.attrs.get('ng-controller', None)
        disabled = self.attrs.get('ng-disabled', None)
        required = self.attrs.get('ng-required', 'false')
        change = self.attrs.get('ng-change',
                                'undefined').replace('"',
                                                     "'").replace("'", "\\'")
        if change != "undefined":
            change = "'{}'".format(change)
        vmodel = self.field_name
        vid = attrs.get('id', 'id_{0}'.format(name))
        vstyle = attrs.get('style', '')
        vform = smart_text(self.form_name)
        vurl = reverse(self.autofill_url, kwargs={'search': 'a'})[:-1]
        # Get access to the get_label() method and request for the label of the bound input
        if value:
            func = resolve(vurl + '*').func
            clss = get_class(func)
            if self.language:
                clss.language = self.language
            label = clss().get_label(value)

        # Prepare placeholder
        placeholder = self.attrs.get('placeholder',
                                     _('Press * or start typing'))
        ngplaceholder = self.attrs.get(
            'ng-placeholder', "'{}'".format(_('Press * or start typing')))

        # Detect parent node
        vmodelsp = vmodel.split(".")
        if len(vmodelsp) > 1:
            vparent = ".".join(vmodelsp[:-1])
        else:
            vparent = "$parent"

        # Render
        html = u"<input name='{0}' ng-required='{1}' ng-model='{0}' id='{0}' type='hidden'".format(
            vmodel, required)
        if controller:
            html += " ng-controller='{}' ".format(controller)
        if disabled:
            html += " ng-disabled='{}' ".format(disabled)
        # Set initial value
        if value:
            html += u" ng-init=\"{0}='{1}'\"".format(vmodel, value, vform)
        html += ">"
        html += '<ui-select'
        if controller:
            html += " ng-controller='{}' ".format(controller)
        if disabled:
            html += " ng-disabled='{}' ".format(disabled)
        if hasattr(self, "multiple") and self.multiple:
            html += ' multiple '
        if value:
            html += u" ng-init=\"options.{0}=[{{'id':null,'label':{3}}},{{'id':'{1}','label':'{2}'}}]; $select.selected=options.{0}[1];".format(
                vmodel, value, escapejs(label), ngplaceholder)
            html += u" option_default={}; options.{}=option_default['rows']".format(
                self.get_foreign(vurl, vform, vmodel, "'*'", 'getForeignKeys'),
                vmodel)
        else:
            # init options for form modal
            html += u" ng-init=\"options.{0}=[{{'id':null,'label':{1}}}]; \"".format(
                vmodel, ngplaceholder)
        html += u" ng-click=\"option_default={}; options.{}=option_default['rows']".format(
            self.get_foreign(vurl, vform, vmodel, "'*'", 'getForeignKeys'),
            vmodel)

        html += u" id=\"{0}\"".format(vid)
        html += u" ng-model=\"{0}.{1}\"".format(vparent, vmodel)
        html += u" on-select=\"selectedOptionSelect({0}.{1},'{2}',{3}, $parent)\"".format(
            vform, vmodel, value, change)
        html += ' theme="bootstrap"'
        html += ' ng-disabled="disabled"'
        html += ' reset-search-input="false"'
        html += '>'
        html += u' <ui-select-match placeholder=\'{}\'>'.format(placeholder)
        html += ' <div ng-bind-html="$select.selected.label"></div>'
        html += ' </ui-select-match>'
        html += ' <ui-select-choices'
        html += u"     style=\"{0}\"".format(vstyle)
        html += u"     repeat=\"value.id as value in options.{0}\"".format(
            vmodel)
        html += u"     refresh=\"{}\"".format(
            self.get_foreign(vurl, vform, vmodel, "$select.search",
                             'getForeignKeys'))
        html += '     refresh-delay="0">'
        html += '     <div ng-bind-html="value.label| highlightSelect: $select.search"></div>'
        html += ' </ui-select-choices>'
        html += '</ui-select>'
        return html
 def _escape_json(self, value):
     """
     Escapes js for now. Additional escaping can be done here.
     """
     return escapejs(value)
Пример #38
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        html = """
            <div id="%(id)sepiceditor"></div>
            <textarea%(attrs)s>%(body)s</textarea>
            <script type="text/javascript">
                var ee = {
                    'jQuery': (typeof window.django != 'undefined') ? django.jQuery : jQuery.noConflict(true)
                };

                (function($) {
                  $(document).ready(function() {
                    var opts = {
                        container: '%(id)sepiceditor',
                        basePath: '%(basePath)s',
                        theme: {
                          base:'%(theme_base)s',
                          preview:'%(theme_preview)s',
                          editor:'%(theme_editor)s'
                        },
                        file:{
                          defaultContent: "%(defaultContent)s",
                        },
                        clientSideStorage: false,
                        useNativeFullsreen: true,
                        parser: marked,
                        focusOnLoad: false,
                        shortcut: {
                            modifier: 18,
                            fullscreen: 70,
                            preview: 80
                        }
                    }
                    var editor = new EpicEditor(opts);

                    // get textarea and hide it
                    %(textarea)s = $('#%(id)s');
                    %(textarea)s.hide();
                    // then be sure to populate the textarea
                    editor.on('update', function () {
                      %(textarea)s.val(editor.exportFile());
                    });

                    // Everything is all setup, so load!
                    editor.load();
                  });
                })(ee.jQuery);
            </script>
            """ % {
            'basePath':
            (settings.STATIC_URL or settings.MEDIA_URL) + 'epiceditor',
            'defaultContent': escapejs(force_text(value)),
            'theme_base': self.themes['base'],
            'theme_preview': self.themes['preview'],
            'theme_editor': self.themes['editor'],
            'attrs': flatatt(final_attrs),
            'body': conditional_escape(force_text(value)),
            'id': attrs['id'],
            'textarea': "$textarea_" + attrs['id'].replace('-', '_'),
        }
        return mark_safe(html)
Пример #39
0
 def render_base_config(self):
     if self.value:
         self.value = escapejs(self.value)
     super(ExtTextArea, self).render_base_config()
     self._put_config_value('maskRe', self.t_render_mask_re, self.mask_re)
Пример #40
0
 def make_feedback_func(feedback):
     return "'$(\"#{id}\").val(\"{feedback}\")'".format(
         id=id, feedback=escapejs(feedback))
Пример #41
0
 def get_login_url(self, request, **kwargs):
     next_url = "'%s'" % escapejs(kwargs.get('next') or '')
     process = "'%s'" % escapejs(kwargs.get('process') or 'login')
     return 'javascript:allauth.persona.login(%s, %s)' % (next_url, process)
Пример #42
0
    def _action_builder(
        self,
        name,
        label=None,
        url=None,
        func="editObject",
        icon=None,
        show=None,
        fstype="ZFS",
        decrypted=True,
        has_enc=False,
        enc_level=None,
        hide_unknown=True,
    ):

        if url is None:
            url = "_%s_url" % (name, )

        if icon is None:
            icon = name

        if show == "ALL":
            hide_cond = "false"
        elif show == "+DATASET":
            hide_cond = (
                "row.data.type != 'dataset' && row.data.type !== undefined")
        elif show == "DATASET":
            hide_cond = "row.data.type != 'dataset'"
        elif show == "ZVOL":
            hide_cond = "row.data.type != 'zvol'"
        else:
            hide_cond = "row.data.type !== undefined"

        if fstype == "ZFS":
            hide_fs = ("row.data.vol_fstype !== undefined && "
                       "row.data.vol_fstype != 'ZFS'")
        else:
            hide_fs = "false"

        if name == "upgrade":
            hide_cond = "row.data.is_upgraded !== false"

        if decrypted is True:
            hide_enc = ("row.data.vol_fstype !== undefined && "
                        "row.data.is_decrypted == false")
        elif decrypted is False:
            hide_enc = "row.data.is_decrypted == true"
        elif decrypted is None:
            hide_enc = "false"

        if has_enc is True:
            if enc_level is not None:
                hide_hasenc = "row.data.vol_encrypt != %d" % (enc_level, )
            else:
                hide_hasenc = "row.data.vol_encrypt == 0"
        else:
            hide_hasenc = "false"

        if hide_unknown is True:
            hide_unknown = "row.data.status == 'UNKNOWN'"
        else:
            hide_unknown = "false"

        on_select_after = """function(evt, actionName, action) {
  for(var i=0;i < evt.rows.length;i++) {
    var row = evt.rows[i];
    if((%(hide_unknown)s) || (%(hide)s) || (%(hide_fs)s) || (%(hide_enc)s) || (%(hide_hasenc)s) || !%(hide_url)s) {
      query(".grid" + actionName).forEach(function(item, idx) {
        domStyle.set(item, "display", "none");
      });
      break;
    }
  }
}""" % {
            'hide': hide_cond,
            'hide_fs': hide_fs,
            'hide_enc': hide_enc,
            'hide_hasenc': hide_hasenc,
            'hide_unknown': hide_unknown,
            'hide_url': 'row.data.%s' % url,
        }

        on_click = """function() {
  var mybtn = this;
  for (var i in grid.selection) {
    var data = grid.row(i).data;
    %(func)s('%(label)s', data.%(url)s, [mybtn,]);
  }
}""" % {
            'func': func,
            'label': escapejs(label),
            'url': url,
        }

        data = {
            'button_name':
            ('<img src="%simages/ui/buttons/%s.png" width="18px" '
             'height="18px">' % (
                 settings.STATIC_URL,
                 icon,
             )),
            'tooltip':
            label,
            'on_select_after':
            on_select_after,
            'on_click':
            on_click,
        }

        return data
Пример #43
0
    def render_tag(self, context, **kwargs):
        from django.utils.html import escapejs

        rendered = self.nodelist.render(context)
        return "'%s'" % escapejs(rendered.strip())
Пример #44
0
    def post(self, request, *a, **ka):
        arguments = {'error': [], 'success': []}

        exhibit_id = request.POST.get('exhibit', '')
        exhibit = None

        try:
            if len(exhibit_id) < 1:
                raise ObjectDoesNotExist()
            exhibit = Exhibit.objects.get(id=exhibit_id)
        except ObjectDoesNotExist:
            arguments['error'].append(
                'Invalid form. Please send your opinion from the exhibit interface.'
            )

        arguments['exhibit_id'] = exhibit_id

        name = request.POST.get('name', '')
        email = request.POST.get('email', '')
        opinion = request.POST.get('opinion', '')
        rating = request.POST.get('rating', '')

        if rating not in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
            arguments['error'].append('Invalid rating value.')

        if len(name) < 1:
            arguments['error'].append('Please input a non-empty name.')

        try:
            if len(email) < 1:
                raise ValidationError('Empty email.')
            validate_email(email)
        except ValidationError:
            arguments['error'].append('Please input a non-empty email.')

        if len(opinion) < 1:
            arguments['error'].append('Please input a non-empty opinion.')

        opinion = escapejs(opinion)

        if len(arguments['error']) < 1:
            new_opinion = Opinion()
            new_opinion.person_name = name
            new_opinion.email = email
            new_opinion.opinion = opinion
            new_opinion.rating = int(rating)
            hash_key = generate_hash_key(email)
            new_opinion.hash_key = hash_key
            new_opinion.exhibit = exhibit

            one_day_after = datetime.today() + timedelta(days=1)
            one_day_after = one_day_after.date()

            new_opinion.timeout = one_day_after

            if send_email(name, exhibit.name, opinion, hash_key, email):
                new_opinion.save()
                arguments['success'].append(
                    'A confirmation email was sent to your address to validated your opinion.'
                )
            else:
                arguments['error'].append(
                    'A problem occurred sending the verification email. Please try again later.'
                )

        return render(request, self.template_name, arguments)
Пример #45
0
def items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """
    def link_in_col(is_first, field_name, cl):
        if cl.list_display_links is None:
            return False
        if is_first and not cl.list_display_links:
            return True
        return field_name in cl.list_display_links

    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        empty_value_display = cl.model_admin.get_empty_value_display()
        row_classes = ['field-%s' % field_name]
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = empty_value_display
        else:
            empty_value_display = getattr(attr, 'empty_value_display',
                                          empty_value_display)
            if f is None or f.auto_created:
                if field_name == 'action_checkbox':
                    row_classes = ['action-checkbox']
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                result_repr = display_for_value(value, empty_value_display,
                                                boolean)
                if allow_tags:
                    warnings.warn(
                        "Deprecated allow_tags attribute used on field {}. "
                        "Use django.utils.html.format_html(), format_html_join(), "
                        "or django.utils.safestring.mark_safe() instead.".
                        format(field_name), RemovedInDjango20Warning)
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                if isinstance(f.remote_field, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = empty_value_display
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f,
                                                    empty_value_display)
                if isinstance(
                        f,
                    (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        row_class = mark_safe(' class="%s"' % ' '.join(row_classes))
        # If list_display_links not defined, add the link tag to the first field
        if link_in_col(first, field_name, cl):
            table_tag = 'th' if first else 'td'
            first = False

            # Display link to the result's change_view if the url exists, else
            # display just the result's representation.
            try:
                url = cl.url_for_result(result)
            except NoReverseMatch:
                link_or_text = result_repr
            else:
                url = add_preserved_filters(
                    {
                        'preserved_filters': cl.preserved_filters,
                        'opts': cl.opts
                    }, url)
                # Convert the pk to something that can be used in Javascript.
                # Problem cases are long ints (23L) and non-ASCII strings.
                if cl.to_field:
                    attr = str(cl.to_field)
                else:
                    attr = pk
                value = result.serializable_value(attr)
                result_id = escapejs(value)
                link_or_text = format_html(
                    '<a href="{}"{}>{}</a>', url,
                    format_html(
                        ' onclick="opener.dismissRelatedLookupPopup(window, '
                        '&#39;{}&#39;); return false;"', result_id)
                    if cl.is_popup else '', result_repr)

            yield format_html('<{}{}>{}</{}>', table_tag, row_class,
                              link_or_text, table_tag)
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if (form and field_name in form.fields
                    and not (field_name == cl.model._meta.pk.name
                             and form[cl.model._meta.pk.name].is_hidden)):
                bf = form[field_name]
                result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
            yield format_html('<td{}>{}</td>', row_class, result_repr)
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield format_html('<td>{}</td>',
                          force_text(form[cl.model._meta.pk.name]))
Пример #46
0
    def render(self, name, value, attrs=None, choices=()):

        apps_available = []  # main container to send to template
        user_permissions = Permission.objects.filter(
            id__in=value or []).values_list('id', flat=True)
        all_perms = Permission.objects.all().values(
            'id', 'codename', 'content_type_id').order_by('codename')
        excluded_perms = set([])
        codename_id_map = {}
        for p in all_perms:
            codename_id_map['%s_%s' %
                            (p['codename'], p['content_type_id'])] = p['id']

        reminder_perms = codename_id_map.copy()
        # used to detect if the tabular permissions covers all permissions, if so, we don't need to make it visible.

        for app in apps.get_app_configs():
            app_dict = {
                'verbose_name': force_text(app.verbose_name),
                'models': []
            }

            for model_name in app.models:
                model = app.models[model_name]
                ct_id = ContentType.objects.get_for_model(
                    model,
                    for_concrete_model=TABULAR_PERMISSIONS_USE_FOR_CONCRETE).pk
                add_perm_name = get_perm_name(model_name, 'add')
                change_perm_name = get_perm_name(model_name, 'change')
                delete_perm_name = get_perm_name(model_name, 'delete')
                # pdb.set_trace()
                add_perm_id = codename_id_map.get(
                    '%s_%s' % (add_perm_name, ct_id), False)
                change_perm_id = codename_id_map.get(
                    '%s_%s' % (change_perm_name, ct_id), False)
                delete_perm_id = codename_id_map.get(
                    '%s_%s' % (delete_perm_name, ct_id), False)

                if add_perm_id and change_perm_id and delete_perm_id and not {
                        add_perm_id, change_perm_id, delete_perm_id
                } & excluded_perms:
                    excluded_perms.update(
                        [add_perm_id, change_perm_id, delete_perm_id])
                    reminder_perms.pop('%s_%s' % (add_perm_name, ct_id))
                    reminder_perms.pop('%s_%s' % (change_perm_name, ct_id))
                    reminder_perms.pop('%s_%s' % (delete_perm_name, ct_id))

                    if app.label in TABULAR_PERMISSIONS_EXCLUDE_APPS \
                            or model_name in TABULAR_PERMISSIONS_EXCLUDE_MODELS \
                            or TABULAR_PERMISSIONS_EXCLUDE_FUNCTION(model):
                        continue

                    app_dict['models'].append({
                        'model_name':
                        model_name,
                        'model':
                        model,
                        'verbose_name_plural':
                        force_text(model._meta.verbose_name_plural),
                        'verbose_name':
                        force_text(model._meta.verbose_name),
                        'add_perm_id':
                        add_perm_id,
                        'add_perm_name':
                        add_perm_name,
                        'change_perm_id':
                        change_perm_id,
                        'change_perm_name':
                        change_perm_name,
                        'delete_perm_id':
                        delete_perm_id,
                        'delete_perm_name':
                        delete_perm_name,
                    })

            if app.models:
                apps_available.append(app_dict)

        request_context = {
            'apps_available': apps_available,
            'user_permissions': user_permissions,
            'codename_id_map': codename_id_map,
            'input_name': self.input_name
        }
        body = get_template(TABULAR_PERMISSIONS_TEMPLATE).render(
            request_context).encode("utf-8")
        self.managed_perms = excluded_perms
        if reminder_perms:
            self.hide_original = False

        # Get "original" FilteredSelectMultiple, and hide it if necessary.
        # Next block is a "copy" of FilteredSelectMultiple render(), except the if reminder_perms: check.
        # Due to change in how SelectFilter take its arguments and the dropping of static('admin/') in django1.9
        # there a check on django version

        if attrs is None:
            attrs = {}
        if '1.10' in django_version:
            attrs['class'] = 'selector-filter'
        else:
            attrs['class'] = 'selectfilter'
        if self.is_stacked:
            attrs['class'] += 'stacked'

        output = [
            super(FilteredSelectMultiple, self).render(name, value, attrs)
        ]
        if reminder_perms:
            output.append(
                '<script type="text/javascript">addEvent(window, "load", function(e) {'
            )

            if '1.8' in django_version:
                output.append(
                    'SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n'
                    % (name, self.verbose_name.replace(
                        '"', '\\"'), int(self.is_stacked), static('admin/')))
            else:  # 1.9
                output.append(
                    'SelectFilter.init("id_%s", "%s", %s); });</script>\n' %
                    (name, escapejs(self.verbose_name), int(self.is_stacked)))

        initial = mark_safe(''.join(output))
        response = ' <hr/>'.join([force_text(body), force_text(initial)])
        return mark_safe(response)
Пример #47
0
def items_for_tree_result(cl, result, form):
    """
    Generates the current list of data.
    """
    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_class = ''
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except (AttributeError, ObjectDoesNotExist):
            result_repr = get_empty_value_display(cl)
        else:
            if f is None:
                if django.VERSION[1] == 4:
                    if field_name == 'action_checkbox':
                        row_class = ' class="action-checkbox disclosure"'
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    result_repr = _boolean_icon(value)
                else:
                    result_repr = smart_text(value)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if not allow_tags:
                    result_repr = escape(result_repr)
                else:
                    result_repr = mark_safe(result_repr)
            else:
                if value is None:
                    result_repr = get_empty_value_display(cl)
                if isinstance(f.rel, models.ManyToOneRel):
                    result_repr = escape(getattr(result, f.name))
                else:
                    result_repr = display_for_field(value, f, '')
                if isinstance(f, models.DateField) or isinstance(f, models.TimeField):
                    row_class = ' class="nowrap"'
            if first:
                if django.VERSION[1] < 4:
                    try:
                        f, attr, checkbox_value = lookup_field('action_checkbox', result, cl.model_admin)
                        if row_class:
                            row_class = "%s%s" % (row_class[:-1], ' disclosure"')
                        else:
                            row_class = ' class="disclosure"'
                    except (AttributeError, ObjectDoesNotExist):
                        pass

        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        # If list_display_links not defined, add the link tag to the first field
        if (first and not cl.list_display_links) or field_name in cl.list_display_links:
            if django.VERSION[1] < 4:
                table_tag = 'td'  # {True:'th', False:'td'}[first]
            else:
                table_tag = {True: 'th', False: 'td'}[first]

            url = cl.url_for_result(result)
            # Convert the pk to something that can be used in Javascript.
            # Problem cases are long ints (23L) and non-ASCII strings.
            if cl.to_field:
                attr = str(cl.to_field)
            else:
                attr = pk
            value = result.serializable_value(attr)
            result_id = repr(force_text(value))[1:]
            first = False
            if django.VERSION[1] < 4:  # versions 1.3 and smaller
                yield mark_safe(
                    '<%s%s>%s<a href="%s"%s>%s</a></%s>' %
                    (table_tag, row_class, checkbox_value, url, (
                        cl.is_popup and
                        ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''),
                     conditional_escape(result_repr), table_tag))
            elif django.VERSION[1] < 7:  # versions 1.4 to 1.7
                yield mark_safe(
                    '<%s%s><a href="%s"%s>%s</a></%s>' %
                    (table_tag, row_class, url, (
                        cl.is_popup and
                        ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''),
                     conditional_escape(result_repr), table_tag))
            else:  # versions 1.8 and greater
                result_id = escapejs(value)
                yield mark_safe(
                    format_html(
                        '<{}{}><a href="{}"{}>{}</a></{}>',
                        table_tag,
                        row_class,
                        url,
                        format_html(
                            ' onclick="opener.dismissRelatedLookupPopup(window, '
                            '&#39;{}&#39;); return false;"', result_id
                        ) if cl.is_popup else '', result_repr, table_tag)
                )

        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if form and field_name in form.fields:
                bf = form[field_name]
                result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
            else:
                result_repr = conditional_escape(result_repr)
            yield mark_safe('<td%s>%s</td>' % (row_class, result_repr))
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield mark_safe('<td>%s</td>' % force_text(form[cl.model._meta.pk.name]))
Пример #48
0
 def get_login_url(self, request, **kwargs):
     next_url = "'%s'" % escapejs(kwargs.get("next") or "")
     process = "'%s'" % escapejs(kwargs.get("process") or "login")
     return "javascript:allauth.persona.login(%s, %s)" % (next_url, process)
Пример #49
0
def map_data(request):
    patients = Patients.objects.all()
    map_patients = get_search_data(patients)
    return render(request, 'map_data.html',
                  {'patients': mark_safe(escapejs(json.dumps(map_patients)))})
Пример #50
0
 def render_props(self):
     if self.props:
         encoded = escapejs(self.json_encoder(self.props))
         return mark_safe("JSON.parse('{0}')".format(encoded))
     return '{}'
Пример #51
0
def dumpjs(v):
    return escapejs(json.dumps(v))
Пример #52
0
def elMeuInforme(request, pk=None):
    """Dades que veurà l'alumne"""

    detall = 'all'

    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    nTaula = 0

    tePermis = True
    semiImpersonat = False
    if pk:
        professor = User2Professor(user)
        alumne = Alumne.objects.get(pk=pk)
        tePermis = professor in alumne.tutorsDeLAlumne()
        semiImpersonat = True
    else:
        alumne = Alumne.objects.get(user_associat=user)

    if not alumne or not tePermis:
        raise Http404

    head = u'{0} ({1})'.format(alumne, unicode(alumne.grup))

    ara = datetime.now()

    report = []

    #----Assistencia --------------------------------------------------------------------
    if detall in ['all', 'assistencia']:
        controls = alumne.controlassistencia_set.exclude(
            estat__codi_estat='P').filter(estat__isnull=False)
        controlsNous = controls.filter(relacio_familia_revisada__isnull=True)

        taula = tools.classebuida()
        taula.codi = nTaula
        nTaula += 1
        taula.tabTitle = 'Faltes i retards {0}'.format(
            pintaNoves(controlsNous.count()))

        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []
        taula.fileres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 25
        capcelera.contingut = u'Dia'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 75
        capcelera.contingut = u'Falta, assignatura i franja horària.'
        taula.capceleres.append(capcelera)

        tots_els_controls = list(
            controls.select_related('impartir', 'estat').order_by(
                '-impartir__dia_impartir', '-impartir__horari__hora'))

        assistencia_calendari = [
        ]  #{"date":"2016-04-02","badge":true,"title":"Example 2"}
        from itertools import groupby
        for k, g in groupby(tots_els_controls,
                            lambda x: x.impartir.dia_impartir):
            gs = list(g)
            gs.reverse()
            assistencia_calendari.append({
                'date':
                k.strftime('%Y-%m-%d'),
                'badge':
                any([c.estat.codi_estat == 'F' for c in gs]),
                'title':
                u'\n'.join([
                    escapejs(u'{0} a {1} ({2})'.format(
                        c.estat, c.impartir.horari.assignatura,
                        c.impartir.horari.hora)) for c in gs
                ])  # Store group iterator as a list
            })

        for control in tots_els_controls:

            filera = []

            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = unicode(
                control.impartir.dia_impartir.strftime('%d/%m/%Y'))
            camp.negreta = False if control.relacio_familia_revisada else True
            filera.append(camp)

            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0} a {1} ({2})'.format(
                control.estat, control.impartir.horari.assignatura,
                control.impartir.horari.hora)
            camp.negreta = False if control.relacio_familia_revisada else True
            filera.append(camp)
            #             assistencia_calendari.append(  { 'date': control.impartir.dia_impartir.strftime( '%Y-%m-%d' ) ,
            #                                              'badge': control.estat.codi_estat == 'F',
            #                                              'title': escapejs( camp.contingut )
            #                                             } )

            #--
            taula.fileres.append(filera)

        report.append(taula)
        if not semiImpersonat:
            controlsNous = controls.update(relacio_familia_notificada=ara,
                                           relacio_familia_revisada=ara)

    #----observacions --------------------------------------------------------------------
        observacions = alumne.incidencia_set.filter(tipus__es_informativa=True)
        observacionsNoves = observacions.filter(
            relacio_familia_revisada__isnull=True)

        taula = tools.classebuida()
        taula.codi = nTaula
        nTaula += 1
        taula.tabTitle = 'Observacions {0}'.format(
            pintaNoves(observacionsNoves.count()))

        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 25
        capcelera.contingut = u'Dia'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 75
        capcelera.contingut = u'Professor i observació.'
        taula.capceleres.append(capcelera)

        taula.fileres = []

        for incidencia in observacions.order_by('-dia_incidencia',
                                                '-franja_incidencia'):
            filera = []
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0}'.format(
                incidencia.dia_incidencia.strftime('%d/%m/%Y'))
            camp.negreta = False if incidencia.relacio_familia_notificada else True
            filera.append(camp)
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.negreta = False if incidencia.relacio_familia_revisada else True
            camp.contingut = u'Sr(a): {0} - {1}'.format(
                incidencia.professional, incidencia.descripcio_incidencia)
            camp.negreta = False if incidencia.relacio_familia_revisada else True
            filera.append(camp)

            #--
            taula.fileres.append(filera)

        report.append(taula)
        if not semiImpersonat:
            observacionsNoves = observacions.update(
                relacio_familia_notificada=ara, relacio_familia_revisada=ara)

    #----incidències --------------------------------------------------------------------
        incidencies = alumne.incidencia_set.filter(tipus__es_informativa=False)
        incidenciesNoves = incidencies.filter(
            relacio_familia_revisada__isnull=True)

        taula = tools.classebuida()
        taula.codi = nTaula
        nTaula += 1
        taula.tabTitle = 'Incidències {0}'.format(
            pintaNoves(incidenciesNoves.count()))

        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 30
        capcelera.contingut = u'Dia i estat'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 70
        capcelera.contingut = u'Professor i Incidència'
        taula.capceleres.append(capcelera)

        taula.fileres = []

        for incidencia in incidencies.order_by('-dia_incidencia',
                                               '-franja_incidencia'):
            filera = []
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0} {1}'.format(
                incidencia.dia_incidencia.strftime('%d/%m/%Y'),
                'Vigent' if incidencia.es_vigent else '')
            camp.negreta = False if incidencia.relacio_familia_revisada else True
            filera.append(camp)
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'Sr(a): {0} - {1}'.format(
                incidencia.professional, incidencia.descripcio_incidencia)
            camp.negreta = False if incidencia.relacio_familia_revisada else True
            filera.append(camp)

            #--
            taula.fileres.append(filera)

        report.append(taula)
        if not semiImpersonat:
            incidenciesNoves.update(relacio_familia_notificada=ara,
                                    relacio_familia_revisada=ara)

    #----Expulsions --------------------------------------------------------------------
        expulsions = alumne.expulsio_set.exclude(estat='ES')
        expulsionsNoves = expulsions.filter(
            relacio_familia_revisada__isnull=True)

        taula = tools.classebuida()
        taula.codi = nTaula
        nTaula += 1
        taula.tabTitle = 'Expulsions {0}'.format(
            pintaNoves(expulsionsNoves.count()))

        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 20
        capcelera.contingut = u'Dia'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 20
        capcelera.contingut = u'Data comunicació'
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 60
        capcelera.contingut = u'Professor i motiu'
        taula.capceleres.append(capcelera)

        taula.fileres = []

        for expulsio in expulsions.order_by('-dia_expulsio',
                                            '-franja_expulsio'):
            filera = []
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0} {1}'.format(
                expulsio.dia_expulsio.strftime('%d/%m/%Y'),
                u'''(per acumulació d'incidències)'''
                if expulsio.es_expulsio_per_acumulacio_incidencies else '')
            camp.negreta = False if expulsio.relacio_familia_revisada else True
            filera.append(camp)
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0}'.format(
                expulsio.moment_comunicacio_a_tutors.strftime('%d/%m/%Y'
                                                              ) if expulsio.
                moment_comunicacio_a_tutors else u'Pendent de comunicar.')
            camp.negreta = False if expulsio.relacio_familia_revisada else True
            filera.append(camp)
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'Sr(a): {0} - {1}'.format(
                expulsio.professor, expulsio.motiu
                if expulsio.motiu else u'Pendent redactar motiu.')
            camp.negreta = False if expulsio.relacio_familia_revisada else True
            filera.append(camp)
            #--
            taula.fileres.append(filera)

        report.append(taula)
        if not semiImpersonat:
            expulsionsNoves.update(relacio_familia_notificada=ara,
                                   relacio_familia_revisada=ara)

    #----Sancions -----------------------------------------------------------------------------
    if detall in ['all', 'incidencies']:
        sancions = alumne.sancio_set.filter(impres=True)
        sancionsNoves = sancions.filter(relacio_familia_revisada__isnull=True)

        taula = tools.classebuida()
        taula.codi = nTaula
        nTaula += 1
        taula.tabTitle = 'Sancions {0}'.format(
            pintaNoves(sancionsNoves.count()))

        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 25
        capcelera.contingut = u'Dates'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 75
        capcelera.contingut = u'Detall'
        taula.capceleres.append(capcelera)

        taula.fileres = []

        for sancio in sancions.order_by('-data_inici'):
            filera = []
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0} a {1}'.format(
                sancio.data_inici.strftime('%d/%m/%Y'),
                sancio.data_fi.strftime('%d/%m/%Y'))
            camp.negreta = False if sancio.relacio_familia_revisada else True
            filera.append(camp)
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0} {1} {2}'.format(
                sancio.tipus, ' - ' if sancio.motiu else '', sancio.motiu)
            camp.negreta = False if sancio.relacio_familia_revisada else True
            filera.append(camp)
            #--
            taula.fileres.append(filera)

        report.append(taula)
        if not semiImpersonat:
            sancionsNoves.update(relacio_familia_notificada=ara,
                                 relacio_familia_revisada=ara)

    #---dades alumne---------------------------------------------------------------------
    if detall in ['all', 'dades']:
        taula = tools.classebuida()
        taula.tabTitle = 'Dades personals'

        taula.codi = nTaula
        nTaula += 1
        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 25
        capcelera.contingut = u'Dades Alumne'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 75
        capcelera.contingut = u''
        taula.capceleres.append(capcelera)

        taula.fileres = []

        #----grup------------------------------------------
        filera = []
        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'Grup'
        filera.append(camp)

        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'{0}'.format(alumne.grup)
        filera.append(camp)

        taula.fileres.append(filera)

        #----data neix------------------------------------------
        filera = []
        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'Data Neixement'
        filera.append(camp)

        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'{0}'.format(alumne.data_neixement)
        filera.append(camp)

        taula.fileres.append(filera)

        #----telefons------------------------------------------
        filera = []
        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'Telèfon'
        filera.append(camp)

        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'{0}'.format(alumne.altres_telefons)
        filera.append(camp)

        taula.fileres.append(filera)

        #----Pares------------------------------------------
        filera = []
        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'Pares'
        filera.append(camp)

        camp = tools.classebuida()
        camp.enllac = None

        camp.multipleContingut = [
            (u'{0} ({1} , {2})'.format(alumne.rp1_nom, alumne.rp1_telefon,
                                       alumne.rp1_mobil), None),
            (u'{0} ({1} , {2})'.format(alumne.rp2_nom, alumne.rp2_telefon,
                                       alumne.rp2_mobil), None),
        ]
        filera.append(camp)

        taula.fileres.append(filera)

        #----adreça------------------------------------------
        filera = []
        camp = tools.classebuida()
        camp.enllac = None
        camp.contingut = u'Adreça'
        filera.append(camp)

        camp = tools.classebuida()
        camp.enllac = None
        localitat_i_o_municipi = alumne.localitat if not alumne.municipi \
            else (alumne.municipi if not alumne.localitat
                  else (alumne.localitat + '-' + alumne.municipi if alumne.localitat != alumne.municipi
                        else alumne.localitat))
        camp.contingut = u'{0} - {1}'.format(alumne.adreca,
                                             localitat_i_o_municipi)
        filera.append(camp)

        taula.fileres.append(filera)

        report.append(taula)

    #----Sortides -----------------------------------------------------------------------------
    if detall in ['all', 'sortides'] and settings.CUSTOM_MODUL_SORTIDES_ACTIU:
        sortides = alumne.notificasortida_set.all()
        sortidesNoves = sortides.filter(relacio_familia_revisada__isnull=True)
        sortides_on_no_assistira = alumne.sortides_on_ha_faltat.values_list(
            'id', flat=True).distinct()
        sortides_justificades = alumne.sortides_falta_justificat.values_list(
            'id', flat=True).distinct()

        taula = tools.classebuida()
        taula.codi = nTaula
        nTaula += 1
        taula.tabTitle = 'Activitats/Sortides {0}'.format(
            pintaNoves(sortidesNoves.count()))

        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 20
        capcelera.contingut = u'Dates'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 35
        capcelera.contingut = u' '
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 35
        capcelera.contingut = u'Detall'
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 10
        capcelera.contingut = u' '
        taula.capceleres.append(capcelera)

        taula.fileres = []

        for sortida in sortides.order_by('-sortida__calendari_desde'):
            filera = []
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = naturalday(sortida.sortida.calendari_desde)
            camp.negreta = False if bool(
                sortida.relacio_familia_revisada) else True
            filera.append(camp)

            #----------------------------------------------
            #  NO INSCRIT A L’ACTIVITAT. L'alumne ha d'assistir al centre excepte si són de viatge de final de curs.
            comentari_no_ve = u""
            if sortida.sortida.pk in sortides_on_no_assistira:
                comentari_no_ve = u"NO INSCRIT A L’ACTIVITAT."
                if sortida.sortida.pk in sortides_justificades:
                    comentari_no_ve += u"NO INSCRIT A L’ACTIVITAT. Té justificada l'absència."

            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = comentari_no_ve
            camp.negreta = False if bool(
                sortida.relacio_familia_revisada) else True
            filera.append(camp)

            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = u'{0}'.format(sortida.sortida.titol_de_la_sortida)
            camp.negreta = False if sortida.relacio_familia_revisada else True
            filera.append(camp)

            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.modal = {}
            camp.modal['id'] = sortida.id
            camp.modal['txtboto'] = u'Detalls'
            camp.modal['tittle'] = u"{0} ({1})".format(
                sortida.sortida.titol_de_la_sortida,
                naturalday(sortida.sortida.calendari_desde),
            )
            camp.modal['body'] = u'{0} a {1} \n\n{2}\n'.format(
                sortida.sortida.calendari_desde.strftime('%d/%m/%Y %H:%M'),
                sortida.sortida.calendari_finsa.strftime('%d/%m/%Y %H:%M'),
                sortida.sortida.programa_de_la_sortida,
            )
            filera.append(camp)
            #--
            taula.fileres.append(filera)

        report.append(taula)
        if not semiImpersonat:
            sortidesNoves.update(relacio_familia_notificada=ara,
                                 relacio_familia_revisada=ara)

    #----Qualitativa -----------------------------------------------------------------------------
    qualitatives_alumne = {
        r.qualitativa
        for r in alumne.respostaavaluacioqualitativa_set.all()
    }
    avui = datetime.now().date()
    qualitatives_en_curs = [
        q for q in qualitatives_alumne
        if (bool(q.data_obrir_portal_families)
            and bool(q.data_tancar_tancar_portal_families)
            and q.data_obrir_portal_families <= avui <=
            q.data_tancar_tancar_portal_families)
    ]

    if detall in ['all', 'qualitativa'] and qualitatives_en_curs:

        respostes = alumne.respostaavaluacioqualitativa_set.filter(
            qualitativa__in=qualitatives_en_curs)
        respostesNoves = respostes.filter(
            relacio_familia_revisada__isnull=True)

        assignatures = list(set([r.assignatura for r in respostes]))
        hi_ha_tipus_assignatura = (
            bool(assignatures) and assignatures[0]
            and assignatures[0].tipus_assignatura is not None
            and assignatures[0].tipus_assignatura.capcelera)
        asignatura_label = assignatures[
            0].tipus_assignatura.capcelera if hi_ha_tipus_assignatura else u"Matèria"

        taula = tools.classebuida()
        taula.codi = nTaula
        nTaula += 1
        taula.tabTitle = u"Avaluació qualitativa {0}".format(
            u"!" if respostesNoves.exists() else "")

        taula.titol = tools.classebuida()
        taula.titol.contingut = ''
        taula.titol.enllac = None

        taula.capceleres = []

        capcelera = tools.classebuida()
        capcelera.amplade = 15
        capcelera.contingut = u'Qualitativa'
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 20
        capcelera.contingut = asignatura_label
        capcelera.enllac = ""
        taula.capceleres.append(capcelera)

        capcelera = tools.classebuida()
        capcelera.amplade = 65
        capcelera.contingut = u''
        taula.capceleres.append(capcelera)

        taula.fileres = []

        respostes_pre = (respostes.order_by(
            'qualitativa__data_obrir_avaluacio', 'assignatura'))

        keyf = lambda x: (x.qualitativa.nom_avaluacio + x.assignatura.
                          nom_assignatura)
        respostes_sort = sorted(respostes_pre, key=keyf)
        from itertools import groupby

        for _, respostes in groupby(respostes_sort, keyf):
            respostes = list(respostes)
            filera = []
            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = respostes[0].qualitativa.nom_avaluacio
            camp.negreta = False if bool(
                respostes[0].relacio_familia_revisada) else True
            filera.append(camp)

            camp = tools.classebuida()
            camp.enllac = None
            camp.contingut = respostes[
                0].assignatura.nom_assignatura or respostes[0].assignatura
            camp.negreta = False if bool(
                respostes[0].relacio_familia_revisada) else True
            filera.append(camp)

            #----------------------------------------------
            camp = tools.classebuida()
            camp.enllac = None
            camp.multipleContingut = []
            for resposta in respostes:
                camp.multipleContingut.append((
                    u'{0}'.format(resposta.get_resposta_display()),
                    None,
                ))
            camp.negreta = False if respostes[
                0].relacio_familia_revisada else True
            filera.append(camp)

            #--
            taula.fileres.append(filera)

        report.append(taula)
        if not semiImpersonat:
            respostesNoves.update(relacio_familia_notificada=ara,
                                  relacio_familia_revisada=ara)

    return render(
        request,
        'report_detall_families.html',
        {
            'report': report,
            'head': u'Informació alumne {0}'.format(head),
            'assistencia_calendari': json.dumps(assistencia_calendari),
        },
    )
Пример #53
0
def json_parse(value):
    """
    This is a correct way of embedding json inside js in an HTML template.
    """
    return mark_safe('JSON.parse(\'%s\')' % escapejs(json.dumps(value)))
Пример #54
0
    def render(self, name, value, attrs=None, choices=()):
        # Initialization
        required = self.attrs.get('ng-required', 'false')
        controller = self.attrs.get('ng-controller', None)
        disabled = self.attrs.get('ng-disabled', None)
        change = self.attrs.get('ng-change',
                                'undefined').replace('"',
                                                     "'").replace("'", "\\'")
        if change != "undefined":
            change = "'{}'".format(change)
        vmodel = self.field_name
        vid = attrs.get('id', 'id_{0}'.format(name))
        vstyle = attrs.get('style', '')
        ngreadonly = attrs.get('ng-readonly', '')
        vform = smart_text(self.form_name)
        placeholder = escapejs(_('Select an option'))
        is_multiple = hasattr(self, "multiple") and self.multiple

        # Render
        html = u"<input name='{0}' ng-required='{1}' ng-model='{0}' type='hidden'".format(
            vmodel, required)
        if controller:
            html += " ng-controller='{}' ".format(controller)
        if disabled:
            html += " ng-disabled='{}' ".format(disabled)
        valuejs = None
        if is_multiple:
            if value:
                if type(value) == list:
                    valuejs = json.dumps([int(x) for x in value])
                else:
                    valuejs = json.dumps([
                        int(value),
                    ])

                html += " ng-init=\"{0}={1}\"".format(vmodel, valuejs)
            else:
                html += " ng-init=\"{0}=[]\"".format(vmodel)
        elif value:
            html += " ng-init=\"{0}='{1}'\"".format(vmodel, value)

        html += ">"

        html += '<ui-select '
        if disabled:
            html += " ng-disabled='{}' ".format(disabled)
        else:
            html += ' ng-disabled="{}"'.format(ngreadonly)
        if controller:
            html += " ng-controller='{}' ".format(controller)
        if is_multiple:
            html += ' multiple '
        # Build options
        html += u" ng-init=\"options.{0}=[".format(vmodel)
        ini = None
        list_value = []
        index = 0

        if is_multiple and not value:
            value = []
        if hasattr(self, "field"):
            for (key, label) in self.field.choices:
                if value == key:
                    ini = index
                html += u"{{'id':'{0}','label':'{1}'}},".format(
                    key, escapejs(smart_text(label)))
                index += 1
        elif type(self.choices) == list:
            for (key, label) in self.choices:
                if value == key:
                    ini = index
                html += u"{{'id':'{0}','label':'{1}'}},".format(
                    key, escapejs(smart_text(label)))
                index += 1
        else:
            if not is_multiple:
                html += u"{{'id':null, 'label':'{0}'}}, ".format(placeholder)

            for choice in self.choices.queryset:
                if value == choice.pk:  # only not multiple
                    ini = index
                html += u"{{'id':'{0}','label':'{1}'}},".format(
                    choice.pk, escapejs(smart_text(choice)))
                if value and (type(value) is list) and (str(choice.pk)
                                                        in value):
                    list_value.append({
                        'id': int(choice.pk),
                        'label': str(choice)
                    })
                index += 1

            # raise Exception(html)
        html += "];"
        # Select if we have already one
        if ini is not None:
            if is_multiple:
                html += u"$select.selected=options.{0};".format(vmodel, ini)
            else:
                html += u"$select.placeholder='options.{0}[{1}];'".format(
                    vmodel, ini)
            # ok html += u"$select.selected=options.{0}".format(vmodel,ini)

        if is_multiple and value is not None:
            html += u"{0}.{1}.$setViewValue({2});".format(
                vform, vmodel,
                json.dumps(list_value).replace('"', "'"))
            # html += u"$parent.{1}.$setViewValue({2});".format(vform,vmodel,json.dumps(list_value).replace('"', "'"))

        html += ' "'
        # Build the rest of the tag
        html += u" id=\"{0}\"".format(vid)
        html += u" ng-model=\"$parent.{0}\"".format(vmodel)
        if is_multiple:
            html += u" on-select=\"selectedOptionSelect({0}.{1},'{2}',{3}, $parent)\"".format(
                vform, vmodel, valuejs, change)
        else:
            if value is None:
                value = "null"
            else:
                value = "'{}'".format(value)
            html += u" on-select=\"selectedOptionSelect({0}.{1},{2},{3}, $parent)\"".format(
                vform, vmodel, value, change)
        html += u' theme="bootstrap"'
        html += u' ng-disabled="disabled"'
        html += u' reset-search-input="false"'
        html += u'>'
        html += u' <ui-select-match placeholder="{}">'.format(placeholder)
        if is_multiple:
            html += u'    {{$item.label}}'
        else:
            html += u'    {{$select.selected.label}}'
        html += u' </ui-select-match>'
        html += u' <ui-select-choices'
        html += u"     style=\"{0}\"".format(vstyle)
        html += u"     repeat=\"value.id as value in options.{0}".format(
            vmodel)
        html += u'            | filter: {label: $select.search}">'
        html += u'     <div ng-bind-html="value.label| highlightSelect: $select.search"></div>'
        html += u' </ui-select-choices>'
        html += u'</ui-select>'
        # Return result
        return html
Пример #55
0
    def render(self, name, value, attrs=None, choices=()):
        # Initialization
        # required=self.attrs.get('ng-required','false')
        vmodel = self.field_name
        # vid=attrs.get('id','id_{0}'.format(name))
        # vstyle=attrs.get('style','')
        vform = self.form_name
        if self.static:
            placeholder = escapejs(_('Press * and select an option'))
        else:
            placeholder = _('Press * or start typing')

            if not self.autofill_url:
                raise IOError("autofill_url not defined")

            vurl = reverse(self.autofill_url, kwargs={'search': 'a'})[:-1]
            # Get access to the get_label() method and request for the label of the bound input
            if value:
                func = resolve(vurl + '*').func
                clss = get_class(func)
                if self.__language:
                    clss.language = self.__language
                label = clss().get_label(value)

        if value is None:
            value = []

        valuejs = []

        if self.static:
            init = ''
            if not value:
                value = []
            if hasattr(self, "field"):
                for (key, label) in self.field.choices:
                    if value == key:
                        valuejs.append(u'{{"id":"{0}","label":"{1}"}},'.format(
                            key, escapejs(smart_text(label))))
                    init += u'{{"id":"{0}","label":"{1}"}},'.format(
                        key, escapejs(smart_text(label)))
            elif type(self.choices) == list:

                for (key, label) in self.choices:
                    if value == key:
                        valuejs.append(u'{{"id":"{0}","label":"{1}"}},'.format(
                            key, escapejs(smart_text(label))))
                    init += u'{{"id":"{0}","label":"{1}"}},'.format(
                        key, escapejs(smart_text(label)))
            else:
                # FORCE RELOAD DATAS
                elements = self.choices.queryset
                elements._result_cache = None
                for choice in elements:
                    init += u'{{"id":"{0}","label":"{1}"}},'.format(
                        choice.pk, escapejs(smart_text(choice)))
                    if value and (type(value) is list) and (choice.pk
                                                            in value):
                        valuejs.append(u'{{"id":"{0}","label":"{1}"}},'.format(
                            int(choice.pk), escapejs(smart_text(choice))))
        else:
            init = "getForeignKeys(http,'{0}',amc_items,{{".format(vurl)
            comma = False
            for field in self.autofill:
                if ':' in field:
                    field_filter = field.split(':')[-1]
                    field = field.split(':')[0]
                else:
                    field_filter = field
                if comma:
                    init += ","
                else:
                    comma = True
                init += "'{0}':{1}.{2}".format(field, vform, field_filter)
            init += "}},'{0}',{0},$select.search,{1})\"".format(
                vmodel, self.autofill_deepness)

        html = u'<md-chips ng-model="amc_select.{0}" md-autocomplete-snap id="{0}" name="{0}" '.format(
            vmodel)
        html += u'    md-transform-chip="amc_transformChip($chip)"'
        # html += u'    initial = "loadVegetables()"'
        html += u"    ng-init = 'amc_items.{0} = [".format(vmodel)
        #        {"name":"Broccoli","type":"Brassica","_lowername":"broccoli","_lowertype":"brassica"}
        html += init
        if valuejs:
            # html += u" ng-init = 'amc_select.{0} = [".format(vmodel)
            html += u"]; amc_select.{0} = [".format(vmodel)
            html += ''.join(valuejs)
            html += u"]'"
        html += u"]'"
        html += u'    md-require-match="amc_autocompleteDemoRequireMatch">'
        html += u'    <md-autocomplete'
        html += u'            md-selected-item="amc_selectedItem.{}"'.format(
            vmodel)
        html += u'            md-search-text="amc_searchText.{}"'.format(
            vmodel)
        html += u'            md-items="item in amc_querySearch(amc_searchText.{0}, \'{0}\', \'{0}\')"'.format(
            vmodel)
        html += u'            md-item-text="item.id"'
        html += u'            placeholder="{}">'.format(placeholder)
        html += u'        <span md-highlight-text="amc_searchText.{}">'.format(
            vmodel)
        html += u'            {{item.label}}</span>'
        html += u'    </md-autocomplete>'
        html += u'    <md-chip-template>'
        html += u'        <span>'
        html += u'        {{$chip.label}}'
        html += u'        </span>'
        html += u'    </md-chip-template>'
        html += u'</md-chips>'
        return html
Пример #56
0
    def _action_builder(self,
                        name,
                        label=None,
                        url=None,
                        func="editObject",
                        icon=None,
                        show=None):

        if url is None:
            url = "_%s_url" % (name, )

        if icon is None:
            icon = name
        if icon is not False:
            icon = '<img src="%simages/ui/buttons/%s.png" width="18px" height="18px">' % (
                settings.STATIC_URL,
                icon,
            )
        else:
            icon = label

        on_select_after = """function(evt, actionName, action) {
                for(var i=0;i < evt.rows.length;i++) {
                    var row = evt.rows[i];

                    if (row.data.jail_isplugin) {
                        if (actionName == 'delete') {
                            query(".grid" + actionName).forEach(function(item, idx) {
                                domStyle.set(item, "display", "none");
                            });
                        }
                    }

                    if (row.data.jail_type != 'pluginjail' || row.data.jail_status == 'Stopped') {
                        if (actionName == 'plugins') {
                            query(".grid" + actionName).forEach(function(item, idx) {
                                domStyle.set(item, "display", "none");
                            });
                        }
                    }

                    if (row.data.jail_status == 'Running') {
                        if (actionName == 'start') {
                            query(".grid" + actionName).forEach(function(item, idx) {
                                domStyle.set(item, "display", "none");
                            });
                        }
                        break;

                    } else if (row.data.jail_status == 'Stopped') {
                        if (actionName == 'stop') {
                            query(".grid" + actionName).forEach(function(item, idx) {
                                domStyle.set(item, "display", "none");
                            });
                        }
                        break;
                    }
                }
            }"""

        on_click = """function() {
                var mybtn = this;
                for (var i in grid.selection) {
                    var data = grid.row(i).data;
                    %(func)s('%(label)s', data.%(url)s, [mybtn,]);
                }
            }""" % {
            'func': func,
            'label': escapejs(label),
            'url': url,
        }

        data = {
            'button_name': icon,
            'tooltip': label,
            'on_select_after': on_select_after,
            'on_click': on_click,
        }

        return data
Пример #57
0
def creation_add(req, uid=None):
    '''
    创意添加,暂时没有处理上传文件的格式
    :param req:
    :param uid:
    :return:
    '''
    if req.method == "GET":
        users = models.User.objects.all().order_by("UserName")
        labels = models.ProjectLabel.objects.all()
        if uid:
            pass
        else:
            return render(req, 'admina/creation_add.html', {
                "labels": labels,
                "users": users,
            })
    else:
        resData = {"status": 0, "message": ""}
        try:
            data = req.POST
            print data.get('creation_user')
            creation_user_id = data.get('creation_user')
            print data.get('creation_init_time')
            creatino_init_time = data.get('creation_init_time')
            print creatino_init_time
            creation_is_use = data.get('IsUse')
            creatino_init_time = data.get('creation_init_time')
            creation_name = escapejs(data.get('creation_name'))
            creation_tagids = data.get(u'Tags')
            creation_descibe = data.get(u'creation_descibe')
            print creation_tagids
            print locals()
            if (req.FILES):
                creation_img = req.FILES.get('Img')
            else:
                creation_img = None
            if creatino_init_time:
                creatino_init_time = creatino_init_time.split('-')
                creatino_init_time = datetime.datetime(
                    int(creatino_init_time[0]), int(creatino_init_time[1]),
                    int(creatino_init_time[2]))
            else:
                creatino_init_time = datetime.datetime.now()
            if int(creation_is_use) == 1:
                creation_is_use = False
            else:
                creation_is_use = True
            user = models.User.objects.get(Id=creation_user_id)
            creation = models.Creation.objects.create(
                user=user,
                IsUse=creation_is_use,
                Date=creatino_init_time,
                Name=creation_name,
                Img=creation_img,
                Describe=creation_descibe)
            creation.save()
            for tagid in creation_tagids.split(','):
                tag = models.ProjectLabel.objects.get(Id=tagid)
                creation2ProjectLabel = models.Creation2ProjectLabel.objects.create(
                    creation=creation, projectLabel=tag)
                creation2ProjectLabel.save()
            resData['message'] = '创建成功'
            resData['status'] = 1
        except Exception as e:
            print(e)
            resData['message'] = str(e)
        return HttpResponse(JsonResponse(resData))
Пример #58
0
def escapejs_filter(value):
    """Hex encode characters for use in jquery strings."""
    return escapejs(value)
Пример #59
0
def items_for_result(cl, result, form):
    """
    Generates the actual list of data.
    """
    first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_classes = ['field-%s' % field_name]
        try:
            f, attr, value = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            if f is None:
                if field_name == 'action_checkbox':
                    row_classes = ['action-checkbox']
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                result_repr = display_for_value(value, boolean)
                # Strip HTML tags in the resulting text, except if the
                # function has an "allow_tags" attribute set to True.
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_classes.append('nowrap')
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if field_val is None:
                        result_repr = EMPTY_CHANGELIST_VALUE
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f)
                if isinstance(
                        f,
                    (models.DateField, models.TimeField, models.ForeignKey)):
                    row_classes.append('nowrap')
        if force_text(result_repr) == '':
            result_repr = mark_safe('&nbsp;')
        row_class = mark_safe(' class="%s"' % ' '.join(row_classes))
        # If list_display_links not defined, add the link tag to the first field
        if (first and not cl.list_display_links
            ) or field_name in cl.list_display_links:
            table_tag = 'th' if first else 'td'
            first = False

            # Display link to the result's change_view if the url exists, else
            # display just the result's representation.
            try:
                url = cl.url_for_result(result)
            except NoReverseMatch:
                link_or_text = result_repr
            else:
                url = add_preserved_filters(
                    {
                        'preserved_filters': cl.preserved_filters,
                        'opts': cl.opts
                    }, url)
                # Convert the pk to something that can be used in Javascript.
                # Problem cases are long ints (23L) and non-ASCII strings.
                if cl.to_field:
                    attr = str(cl.to_field)
                else:
                    attr = pk
                value = result.serializable_value(attr)
                result_id = escapejs(value)
                link_or_text = format_html(
                    '<a href="{0}"{1}>{2}</a>', url,
                    format_html(
                        ' onclick="opener.dismissRelatedLookupPopup(window, &#39;{0}&#39;); return false;"',
                        result_id) if cl.is_popup else '', result_repr)

            yield format_html('<{0}{1}>{2}</{3}>', table_tag, row_class,
                              link_or_text, table_tag)
        else:
            # By default the fields come from ModelAdmin.list_editable, but if we pull
            # the fields out of the form instead of list_editable custom admins
            # can provide fields on a per request basis
            if (form and field_name in form.fields
                    and not (field_name == cl.model._meta.pk.name
                             and form[cl.model._meta.pk.name].is_hidden)):
                bf = form[field_name]
                result_repr = mark_safe(force_text(bf.errors) + force_text(bf))
            yield format_html('<td{0}>{1}</td>', row_class, result_repr)
    if form and not form[cl.model._meta.pk.name].is_hidden:
        yield format_html('<td>{0}</td>',
                          force_text(form[cl.model._meta.pk.name]))
Пример #60
0
def get_page_context(page,
                     user,
                     resource_edit=False,
                     extended_metadata_layout=None,
                     request=None):
    """Inject a crispy_form layout into the page to display extended metadata.

    :param page: which page to get the template context for
    :param user: the user who is viewing the page
    :param resource_edit: True if and only if the page should render in edit mode
    :param extended_metadata_layout: layout information used to build an ExtendedMetadataForm
    :param request: the Django request associated with the page load
    :return: the basic template context (a python dict) used to render a resource page. can and
    should be extended by page/resource-specific page_processors

    Resource type specific app needs to call this method to inject a crispy_form layout
    object for displaying metadata UI for the extended metadata for their resource

    TODO: refactor to make it clear that there are two different modes = EDITABLE | READONLY
                - split into two functions: get_readonly_page_context(...) and
                get_editable_page_context(...)
    """
    file_type_error = ''
    if request:
        file_type_error = request.session.get("file_type_error", None)
        if file_type_error:
            del request.session["file_type_error"]

    content_model = page.get_content_model()
    # whether the user has permission to view this resource
    can_view = content_model.can_view(request)
    if not can_view:
        if user.is_authenticated():
            raise PermissionDenied()
        return redirect_to_login(request.path)

    discoverable = content_model.raccess.discoverable
    validation_error = None
    resource_is_mine = False
    if user.is_authenticated():
        resource_is_mine = content_model.rlabels.is_mine(user)

    metadata_status = _get_metadata_status(content_model)

    belongs_to_collections = content_model.collections.all()

    tool_homepage_url = None
    if not resource_edit:  # In view mode
        landing_page_res_obj = content_model
        landing_page_res_type_str = landing_page_res_obj.resource_type
        if landing_page_res_type_str.lower() == "toolresource":
            if landing_page_res_obj.metadata.app_home_page_url:
                tool_homepage_url = content_model.metadata.app_home_page_url.value

    just_created = False
    just_copied = False
    create_resource_error = None
    just_published = False
    if request:
        validation_error = check_for_validation(request)

        just_created = request.session.get('just_created', False)
        if 'just_created' in request.session:
            del request.session['just_created']

        just_copied = request.session.get('just_copied', False)
        if 'just_copied' in request.session:
            del request.session['just_copied']

        create_resource_error = request.session.get('resource_creation_error',
                                                    None)
        if 'resource_creation_error' in request.session:
            del request.session['resource_creation_error']

        just_published = request.session.get('just_published', False)
        if 'just_published' in request.session:
            del request.session['just_published']

    bag_url = content_model.bag_url

    if user.is_authenticated():
        show_content_files = user.uaccess.can_view_resource(content_model)
    else:
        # if anonymous user getting access to a private resource (since resource is discoverable),
        # then don't show content files
        show_content_files = content_model.raccess.public

    rights_allow_copy = rights_allows_copy(content_model, user)

    qholder = content_model.get_quota_holder()

    readme = content_model.get_readme_file_content()
    if readme is None:
        readme = ''
    has_web_ref = res_has_web_reference(content_model)

    keywords = json.dumps(
        [sub.value for sub in content_model.metadata.subjects.all()])
    topics = Topic.objects.all().values_list('name',
                                             flat=True).order_by('name')
    topics = list(topics)  # force QuerySet evaluation

    # user requested the resource in READONLY mode
    if not resource_edit:
        content_model.update_view_count(request)
        temporal_coverage = content_model.metadata.temporal_coverage
        temporal_coverage_data_dict = {}
        if temporal_coverage:
            start_date = parser.parse(temporal_coverage.value['start'])
            end_date = parser.parse(temporal_coverage.value['end'])
            temporal_coverage_data_dict['start_date'] = start_date.strftime(
                '%Y-%m-%d')
            temporal_coverage_data_dict['end_date'] = end_date.strftime(
                '%Y-%m-%d')
            temporal_coverage_data_dict['name'] = temporal_coverage.value.get(
                'name', '')

        spatial_coverage = content_model.metadata.spatial_coverage
        spatial_coverage_data_dict = {}
        spatial_coverage_data_dict['default_units'] = \
            content_model.metadata.spatial_coverage_default_units
        spatial_coverage_data_dict['default_projection'] = \
            content_model.metadata.spatial_coverage_default_projection
        spatial_coverage_data_dict['exists'] = False
        if spatial_coverage:
            spatial_coverage_data_dict['exists'] = True
            spatial_coverage_data_dict['name'] = spatial_coverage.value.get(
                'name', None)
            spatial_coverage_data_dict['units'] = spatial_coverage.value[
                'units']
            spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get(
                'zunits', None)
            spatial_coverage_data_dict[
                'projection'] = spatial_coverage.value.get('projection', None)
            spatial_coverage_data_dict['type'] = spatial_coverage.type
            if spatial_coverage.type == 'point':
                spatial_coverage_data_dict['east'] = spatial_coverage.value[
                    'east']
                spatial_coverage_data_dict['north'] = spatial_coverage.value[
                    'north']
                spatial_coverage_data_dict[
                    'elevation'] = spatial_coverage.value.get(
                        'elevation', None)
            else:
                spatial_coverage_data_dict[
                    'northlimit'] = spatial_coverage.value['northlimit']
                spatial_coverage_data_dict[
                    'eastlimit'] = spatial_coverage.value['eastlimit']
                spatial_coverage_data_dict[
                    'southlimit'] = spatial_coverage.value['southlimit']
                spatial_coverage_data_dict[
                    'westlimit'] = spatial_coverage.value['westlimit']
                spatial_coverage_data_dict[
                    'uplimit'] = spatial_coverage.value.get('uplimit', None)
                spatial_coverage_data_dict[
                    'downlimit'] = spatial_coverage.value.get(
                        'downlimit', None)
        languages_dict = dict(languages_iso.languages)
        language = languages_dict[content_model.metadata.language.code] if \
            content_model.metadata.language else None
        title = content_model.metadata.title.value if content_model.metadata.title else None
        abstract = content_model.metadata.description.abstract if \
            content_model.metadata.description else None

        missing_metadata_elements = content_model.metadata.get_required_missing_elements(
        )
        maps_key = settings.MAPS_KEY if hasattr(settings, 'MAPS_KEY') else ''

        context = {
            'cm': content_model,
            'resource_edit_mode': resource_edit,
            'metadata_form': None,
            'citation': content_model.get_citation(),
            'custom_citation': content_model.get_custom_citation(),
            'title': title,
            'readme': readme,
            'abstract': abstract,
            'creators': content_model.metadata.creators.all(),
            'contributors': content_model.metadata.contributors.all(),
            'temporal_coverage': temporal_coverage_data_dict,
            'spatial_coverage': spatial_coverage_data_dict,
            'keywords': keywords,
            'language': language,
            'rights': content_model.metadata.rights,
            'sources': content_model.metadata.sources.all(),
            'relations': content_model.metadata.relations.all(),
            'show_relations_section': show_relations_section(content_model),
            'fundingagencies': content_model.metadata.funding_agencies.all(),
            'metadata_status': metadata_status,
            'missing_metadata_elements': missing_metadata_elements,
            'validation_error': validation_error if validation_error else None,
            'resource_creation_error': create_resource_error,
            'tool_homepage_url': tool_homepage_url,
            'file_type_error': file_type_error,
            'just_created': just_created,
            'just_copied': just_copied,
            'just_published': just_published,
            'bag_url': bag_url,
            'show_content_files': show_content_files,
            'discoverable': discoverable,
            'resource_is_mine': resource_is_mine,
            'rights_allow_copy': rights_allow_copy,
            'quota_holder': qholder,
            'belongs_to_collections': belongs_to_collections,
            'show_web_reference_note': has_web_ref,
            'current_user': user,
            'maps_key': maps_key
        }

        return context

    # user requested the resource in EDIT MODE

    # whether the user has permission to change the model
    can_change = content_model.can_change(request)
    if not can_change:
        raise PermissionDenied()

    temporal_coverage = content_model.metadata.temporal_coverage
    temporal_coverage_data_dict = {}
    if temporal_coverage:
        start_date = parser.parse(temporal_coverage.value['start'])
        end_date = parser.parse(temporal_coverage.value['end'])
        temporal_coverage_data_dict['start'] = start_date.strftime('%m-%d-%Y')
        temporal_coverage_data_dict['end'] = end_date.strftime('%m-%d-%Y')
        temporal_coverage_data_dict['name'] = temporal_coverage.value.get(
            'name', '')
        temporal_coverage_data_dict['id'] = temporal_coverage.id

    spatial_coverage = content_model.metadata.spatial_coverage
    spatial_coverage_data_dict = {'type': 'point'}
    spatial_coverage_data_dict['default_units'] = \
        content_model.metadata.spatial_coverage_default_units
    spatial_coverage_data_dict['default_projection'] = \
        content_model.metadata.spatial_coverage_default_projection
    spatial_coverage_data_dict['exists'] = False
    if spatial_coverage:
        spatial_coverage_data_dict['exists'] = True
        spatial_coverage_data_dict['name'] = spatial_coverage.value.get(
            'name', None)
        spatial_coverage_data_dict['units'] = spatial_coverage.value['units']
        spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get(
            'zunits', None)
        spatial_coverage_data_dict['projection'] = spatial_coverage.value.get(
            'projection', None)
        spatial_coverage_data_dict['type'] = spatial_coverage.type
        spatial_coverage_data_dict['id'] = spatial_coverage.id
        if spatial_coverage.type == 'point':
            spatial_coverage_data_dict['east'] = spatial_coverage.value['east']
            spatial_coverage_data_dict['north'] = spatial_coverage.value[
                'north']
            spatial_coverage_data_dict[
                'elevation'] = spatial_coverage.value.get('elevation', None)
        else:
            spatial_coverage_data_dict['northlimit'] = spatial_coverage.value[
                'northlimit']
            spatial_coverage_data_dict['eastlimit'] = spatial_coverage.value[
                'eastlimit']
            spatial_coverage_data_dict['southlimit'] = spatial_coverage.value[
                'southlimit']
            spatial_coverage_data_dict['westlimit'] = spatial_coverage.value[
                'westlimit']
            spatial_coverage_data_dict['uplimit'] = spatial_coverage.value.get(
                'uplimit', None)
            spatial_coverage_data_dict[
                'downlimit'] = spatial_coverage.value.get('downlimit', None)

    if extended_metadata_layout:
        metadata_form = ExtendedMetadataForm(
            resource_mode='edit' if can_change else 'view',
            extended_metadata_layout=extended_metadata_layout)
    else:
        metadata_form = None

    maps_key = settings.MAPS_KEY if hasattr(settings, 'MAPS_KEY') else ''

    grps_member_of = []
    groups = Group.objects.filter(gaccess__active=True).exclude(
        name="Hydroshare Author")
    # for each group set group dynamic attributes
    for g in groups:
        g.is_user_member = user in g.gaccess.members
        if g.is_user_member:
            grps_member_of.append(g)
    try:
        citation_id = content_model.metadata.citation.first().id
    except:
        citation_id = None

    context = {
        'cm':
        content_model,
        'resource_edit_mode':
        resource_edit,
        'metadata_form':
        metadata_form,
        'creators':
        content_model.metadata.creators.all(),
        'title':
        content_model.metadata.title,
        'readme':
        readme,
        'contributors':
        content_model.metadata.contributors.all(),
        'relations':
        content_model.metadata.relations.all(),
        'sources':
        content_model.metadata.sources.all(),
        'fundingagencies':
        content_model.metadata.funding_agencies.all(),
        'temporal_coverage':
        temporal_coverage_data_dict,
        'spatial_coverage':
        spatial_coverage_data_dict,
        'keywords':
        keywords,
        'metadata_status':
        metadata_status,
        'missing_metadata_elements':
        content_model.metadata.get_required_missing_elements(),
        'citation':
        content_model.get_citation(),
        'custom_citation':
        content_model.get_custom_citation(),
        'citation_id':
        citation_id,
        'rights':
        content_model.metadata.rights,
        'bag_url':
        bag_url,
        'current_user':
        user,
        'show_content_files':
        show_content_files,
        'validation_error':
        validation_error if validation_error else None,
        'discoverable':
        discoverable,
        'resource_is_mine':
        resource_is_mine,
        'quota_holder':
        qholder,
        'just_created':
        just_created,
        'relation_source_types':
        tuple((type_value, type_display)
              for type_value, type_display in Relation.SOURCE_TYPES
              if type_value != 'isReplacedBy' and type_value != 'isVersionOf'
              and type_value != 'hasPart'),
        'show_web_reference_note':
        has_web_ref,
        'belongs_to_collections':
        belongs_to_collections,
        'maps_key':
        maps_key,
        'topics_json':
        mark_safe(escapejs(json.dumps(topics))),
        'czo_user':
        any("CZO National" in x.name for x in user.uaccess.communities),
        'odm2_terms':
        list(ODM2Variable.all()),
    }

    return context