def post(self, request, *args, **kwargs):
        """Handle the datas for posting a quick entry,
        and redirect to the admin in case of error or
        to the entry's page in case of success"""
        data = {
            "title": request.POST.get("title"),
            "slug": slugify(request.POST.get("title")),
            "status": DRAFT if "save_draft" in request.POST else PUBLISHED,
            "sites": [Site.objects.get_current().pk],
            "authors": [request.user.pk],
            "template": "entry_detail.html",
            "creation_date": timezone.now(),
            "last_update": timezone.now(),
            "content": request.POST.get("content"),
            "tags": request.POST.get("tags"),
        }
        form = QuickEntryForm(data)
        if form.is_valid():
            form.instance.content = linebreaks(form.cleaned_data["content"])
            entry = form.save()
            return redirect(entry)

        data = {
            "title": smart_str(request.POST.get("title", "")),
            "content": smart_str(linebreaks(request.POST.get("content", ""))),
            "tags": smart_str(request.POST.get("tags", "")),
            "slug": slugify(request.POST.get("title", "")),
            "authors": request.user.pk,
            "sites": Site.objects.get_current().pk,
        }
        return redirect("%s?%s" % (reverse("admin:zinnia_entry_add"), urlencode(data)))
def view_scholarship(request, scholarship_key):
    if not scholarship_key:
        scholarship_key = request.GET.get('sk')
    scholarship_id = request_utils.decrypt_sk(scholarship_key)

    scholarship = Scholarship.objects.get(id=scholarship_id)
    # get description html ready
    if '<div>' in scholarship.description:
        description = scholarship.description
    else:
        description = linebreaks(scholarship.description)
    if scholarship.additional_restriction and '<div>' in scholarship.additional_restriction:
        additional_restriction = scholarship.additional_restriction
    else:
        additional_restriction = linebreaks(scholarship.additional_restriction)

    context = {'scholarship_model': scholarship,
               'scholarship_key': scholarship_key,
               'page_title': scholarship.title,
               'description': description,
               'additional_restriction': additional_restriction,
               'environment': settings.ENVIRONMENT
    }
    return render_to_response('view_scholarship.html',
                              context,
                              context_instance=RequestContext(request))
Example #3
0
    def post(self, request, *args, **kwargs):
        """Handle the datas for posting a quick entry,
        and redirect to the admin in case of error or
        to the entry's page in case of success"""
        form = QuickEntryForm(request.POST)
        if form.is_valid():
            entry_dict = form.cleaned_data
            status = PUBLISHED
            if "save_draft" in request.POST:
                status = DRAFT
            entry_dict["content"] = linebreaks(entry_dict["content"])
            entry_dict["slug"] = slugify(entry_dict["title"])
            entry_dict["status"] = status
            entry = Entry.objects.create(**entry_dict)
            entry.sites.add(Site.objects.get_current())
            entry.authors.add(request.user)
            return redirect(entry)

        data = {
            "title": smart_str(request.POST.get("title", "")),
            "content": smart_str(linebreaks(request.POST.get("content", ""))),
            "tags": smart_str(request.POST.get("tags", "")),
            "slug": slugify(request.POST.get("title", "")),
            "authors": request.user.pk,
            "sites": Site.objects.get_current().pk,
        }
        return redirect("%s?%s" % (reverse("admin:zinnia_entry_add"), urlencode(data)))
def view_quick_nodetype(request):
    """View for quickly post an Nodetype"""
    if request.POST:
        form = QuickNodetypeForm(request.POST)
        if form.is_valid():
            nodetype_dict = form.cleaned_data
            status = PUBLISHED
            if 'save_draft' in request.POST:
                status = DRAFT
            nodetype_dict['content'] = linebreaks(nodetype_dict['content'])
            nodetype_dict['slug'] = slugify(nodetype_dict['title'])
            nodetype_dict['status'] = status
            nodetype = Nodetype.objects.create(**nodetype_dict)
            nodetype.sites.add(Site.objects.get_current())
            nodetype.authors.add(request.user)
            return redirect(nodetype)

        data = {'title': smart_str(request.POST.get('title', '')),
                'content': smart_str(linebreaks(request.POST.get(
                    'content', ''))),
                'tags': smart_str(request.POST.get('tags', '')),
                'slug': slugify(request.POST.get('title', '')),
                'authors': request.user.pk,
                'sites': Site.objects.get_current().pk}
        return redirect('%s?%s' % (reverse('admin:gstudio_nodetype_add'),
                                   urlencode(data)))

    return redirect('admin:gstudio_nodetype_add')
def view_quick_gbobject(request):
    """View for quickly post an Gbobject"""
    if request.POST:
        form = QuickGbobjectForm(request.POST)
        if form.is_valid():
            gbobject_dict = form.cleaned_data
            status = PUBLISHED
            if 'save_draft' in request.POST:
                status = DRAFT
            gbobject_dict['content'] = linebreaks(gbobject_dict['content'])
            gbobject_dict['slug'] = slugify(gbobject_dict['title'])
            gbobject_dict['status'] = status
            gbobject = Gbobject.objects.create(**gbobject_dict)
            gbobject.sites.add(Site.objects.get_current())
            gbobject.authors.add(request.user)
            return redirect(gbobject)

        data = {'title': smart_str(request.POST.get('title', '')),
                'content': smart_str(linebreaks(request.POST.get(
                    'content', ''))),
                'tags': smart_str(request.POST.get('tags', '')),
                'slug': slugify(request.POST.get('title', '')),
                'authors': request.user.pk,
                'sites': Site.objects.get_current().pk}
        return redirect('%s?%s' % (reverse('admin:objectapp_gbobject_add'),
                                   urlencode(data)))

    return redirect('admin:objectapp_gbobject_add')
Example #6
0
 def get_content(self, params):
     if 'body-html' in params:
         return params['body-html']
     if 'stripped-html' in params:
         return linkify(linebreaks(params['stripped-html']))
     if 'body-plain' in params:
         return linkify(linebreaks(params['body-plain']))
def view_quick_entry(request):
    """View for quickly post an Entry"""
    if request.POST:
        form = QuickEntryForm(request.POST)
        if form.is_valid():
            entry_dict = form.cleaned_data
            status = PUBLISHED
            if 'save_draft' in request.POST:
                status = DRAFT
            entry_dict['content'] = linebreaks(entry_dict['content'])
            entry_dict['slug'] = slugify(entry_dict['title'])
            entry_dict['status'] = status
            entry = Entry.objects.create(**entry_dict)
            entry.sites.add(Site.objects.get_current())
            entry.authors.add(request.user)
            return redirect(entry)

        data = {'title': smart_str(request.POST.get('title', '')),
                'content': smart_str(linebreaks(request.POST.get(
                    'content', ''))),
                'tags': smart_str(request.POST.get('tags', '')),
                'slug': slugify(request.POST.get('title', '')),
                'authors': request.user.pk,
                'sites': Site.objects.get_current().pk}
        return redirect('%s?%s' % (reverse('admin:zinnia_entry_add'),
                                   urlencode(data)))

    return redirect('admin:zinnia_entry_add')
Example #8
0
    def post(self, request, *args, **kwargs):
        """Handle the datas for posting a quick entry,
        and redirect to the admin in case of error or
        to the entry's page in case of success"""
        data = {
            'title': request.POST.get('title'),
            'slug': slugify(request.POST.get('title')),
            'status': DRAFT if 'save_draft' in request.POST else PUBLISHED,
            'sites': [Site.objects.get_current().pk],
            'authors': [request.user.pk],
            'content_template': 'zinnia/_entry_detail.html',
            'detail_template': 'entry_detail.html',
            'creation_date': timezone.now(),
            'last_update': timezone.now(),
            'content': request.POST.get('content'),
            'tags': request.POST.get('tags')}
        form = QuickEntryForm(data)
        if form.is_valid():
            form.instance.content = linebreaks(form.cleaned_data['content'])
            entry = form.save()
            return redirect(entry)

        data = {'title': smart_str(request.POST.get('title', '')),
                'content': smart_str(linebreaks(request.POST.get(
                    'content', ''))),
                'tags': smart_str(request.POST.get('tags', '')),
                'slug': slugify(request.POST.get('title', '')),
                'authors': request.user.pk,
                'sites': Site.objects.get_current().pk}
        return redirect('%s?%s' % (reverse('admin:zinnia_entry_add'),
                                   urlencode(data)))
Example #9
0
 def get_content(self, params):
     if "body-html" in params:
         return params["body-html"]
     if "stripped-html" in params:
         return linkify(linebreaks(params["stripped-html"]))
     if "body-plain" in params:
         return linkify(linebreaks(params["body-plain"]))
def view_quick_gbobject(request):
    """View for quickly post an Gbobject"""
    if request.POST:
        form = QuickGbobjectForm(request.POST)
        if form.is_valid():
            gbobject_dict = form.cleaned_data
            status = PUBLISHED
            if "save_draft" in request.POST:
                status = DRAFT
            gbobject_dict["content"] = linebreaks(gbobject_dict["content"])
            gbobject_dict["slug"] = slugify(gbobject_dict["title"])
            gbobject_dict["status"] = status
            gbobject = Gbobject.objects.create(**gbobject_dict)
            gbobject.sites.add(Site.objects.get_current())
            gbobject.authors.add(request.user)
            return redirect(gbobject)

        data = {
            "title": smart_str(request.POST.get("title", "")),
            "content": smart_str(linebreaks(request.POST.get("content", ""))),
            "tags": smart_str(request.POST.get("tags", "")),
            "slug": slugify(request.POST.get("title", "")),
            "authors": request.user.pk,
            "sites": Site.objects.get_current().pk,
        }
        return redirect("%s?%s" % (reverse("admin:objectapp_gbobject_add"), urlencode(data)))

    return redirect("admin:objectapp_gbobject_add")
Example #11
0
def format_flatpage(flatpage):
    value = flatpage.content

    format = flatpage.format
    if format == 'application/xhtml+xml':
        return value
    elif format == 'text/x-livejournal':
        return linebreaks(value)
    elif format == 'text/x-rst':
        return restructuredtext(value)
    else: # format == 'text/plain':
        return linebreaks(escape(value))
Example #12
0
def get_instance_field_value_and_label(field_name, instance, fun_kwargs, request):
    if '__' in field_name:
        current_field_name, next_field_name = field_name.split('__', 1)
        return get_instance_field_value_and_label(next_field_name, getattr(instance, current_field_name), fun_kwargs,
                                                  request)
    else:
        callable_value = getattr(instance, 'get_%s_display' % field_name, None)
        if not callable_value:
            callable_value = getattr(instance, field_name)

        value = get_callable_value(callable_value, fun_kwargs)

        if isinstance(value, bool):
            value = _('Yes') if value else _('No')
        else:
            value = display_for_value(value)

        try:
            field = instance._meta.get_field_by_name(field_name)[0]
        except (FieldDoesNotExist, AttributeError):
            field = None

        if field:
            label = field.verbose_name

            value = display_for_field_value(instance, field, value, callable_value, request)

        else:
            label = callable_value.short_description

        return mark_safe(linebreaks(conditional_escape(force_text(value)))), label
Example #13
0
def create_location(request):
    if request.method == 'POST':
        form = LocationForm(request.POST)
        if form.is_valid():
            # TODO: check if is in Israel
            point = Point([form.cleaned_data['lng'], form.cleaned_data['lat']])
            form.instance.point = point
            location = form.save()
            if request.is_ajax():
                return JsonResponse({
                    'name':
                    html.escape(location.name),
                    'info':
                    linebreaks(location.information),
                    'lat':
                    format(location.point.coords[1], ".5f"),
                    'lng':
                    format(location.point.coords[0], ".5f"),
                })
            return redirect("home")
    else:
        form = LocationForm()

    return render(request, 'general/templates/locations/location_form.html', {
        'form': form,
    })
Example #14
0
def filter_linebreaks(*args, **kwargs):
    """
    Convert \n to <br/>.

    """
    from django.utils.html import linebreaks
    return linebreaks(args[0])
Example #15
0
 def get_html(self):
     """
     Get the HTML for a message while stripping
     excessive line breaks and converting markdown
     :return: The HTML for this message
     """
     return linebreaks(markdown(self.text.rstrip()).rstrip())
Example #16
0
    def json_safe(self):
        json_dict = super(SystemNode, self).json_safe()
        json_dict.update(parent_node_id=self.parent_node_id,
                         notes_text=self.notes,
                         notes_html=django_html.linebreaks(self.notes))

        if self.system:
            json_dict.update(name=self.system.name, type=self.system.type,
                             region=self.system.region)

            if not self.system.region and self.system.wspace_effect:
                json_dict['wspace_effect'] = (
                    wmc.WSPACE_EFFECTS_HTML[self.system.wspace_effect] %
                    wmc.WSPACE_EFFECT_CLASSES[self.system.wspace_effect][
                        self.system.type])
        else:
            json_dict.update(name=None, type=None, region=None)

            if (self.parent_connection and
                self.parent_connection.wormhole.sig != 'K162'):
                json_dict['type'] = self.parent_connection.wormhole.type

        if self.parent_connection:
            json_dict['parent_connection'] = self.parent_connection.json_safe()
        else:
            json_dict['parent_connection'] = None

        return json_dict
Example #17
0
    def process_response(self, request, response):
        if hasattr(request, 'profiler'):
            request.profiler.create_stats()
            io = StringIO()

            sort = request.ORIGINAL_GET.get('sort', 'cumulative')
            stats_args = []
            for arg in request.ORIGINAL_GET.get('stats', '').split(','):
                if arg.replace('.', '').isdigit():
                    arg = float(arg) if '.' in arg else int(arg)
                stats_args.append(arg)

            stats = (
                pstats.Stats(request.profiler, stream=io).sort_stats(sort))
            if 'callers' in request.ORIGINAL_GET:
                stats.print_callers(*stats_args)
            elif 'callees' in request.ORIGINAL_GET:
                stats.print_callees(*stats_args)
            else:
                stats.print_stats(*stats_args)

            lines = []
            for line in linebreaks(io.getvalue()).split('<br />'):
                lines.append('<pre>{0}</pre>'.format(line))
            response.content = '''
                <style>
                pre:nth-child(even) {{ background: rgb(242, 242, 242); }}
                </style>
                {body}
            '''.format(body=''.join(lines))
        return response
Example #18
0
 def html_lead(self):
     """
     Returns the "lead" field formatted in HTML.
     """
     if self.lead:
         return linebreaks(self.lead)
     return ''
Example #19
0
 def location_link(self):
     if self.location.startswith('['):
         link = markdown(self.location)
     else:
         link = '<a href="https://maps.google.com/?q={}">{}</a>'.format(
             quote(self.location), linebreaks(self.location))
     return mark_safe(link)
Example #20
0
    def _output(self):
        """It is this method that is responsible for rendering the 
        object in HTML.
        """
        if self.text is None or self.text == "":
            return u""

        if self.text_format == '\E':
            return linebreaks(urlize(escape(self.text)))
        elif self.text_format == '\T':
            try:
                return textile(self.text)
            except:
                return mark_safe(_('There is an error in the Textile.'))
        elif self.text_format == '\M':
            try:
                return markdown(self.text, MARKDOWN_EXTENSIONS)
            except:
                return mark_safe(_('There is an error in the Markdown.'))
        elif self.text_format == '\R':
            try:
                return restructuredtext(self.text)
            except:
                return mark_safe(
                    _('There is an error in the reStructuredText.'))
        elif self.text_format == '\H' or self.text_format == '\W':
            return mark_safe(self.text)
        else:
            return mark_safe(escape(self.text))
Example #21
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        del self.fields['password']
        self.fields["phone"].validators = [account_validators.phone_number_validator]
        self.fields['event_date'].input_formats = ['%d-%b-%Y']
        self.fields['event_date'].help_text = "Please enter the date of the " \
                                              "event you will be attending.  This will help us " \
                                              "retrieve your disclaimer on the day."

        self.helper = FormHelper()
        self.helper.layout = Layout(
            HTML("<h3>Your details</h3>"),
            "first_name",
            "last_name",
            "email",
            "address",
            "postcode",
            "phone",
            "date_of_birth",
            "event_date",
            HTML("<h3>Emergency Contact Information</h3>"),
            "emergency_contact_name",
            "emergency_contact_phone",
            "emergency_contact_relationship",
            HTML("<h3>Health Questionnaire</h3>"),
            "health_questionnaire_responses",
            HTML("<h3>Disclaimer Terms</h3>"),
            HTML(mark_safe(linebreaks(self.disclaimer_content.disclaimer_terms))),
            "terms_accepted",
            "password",
            Submit('submit', 'Save')
        )
Example #22
0
    def get_dumped_data_display(self, instance):
        def make_object(pairs):
            pairs = sorted(pairs, key=operator.itemgetter(0))
            return collections.OrderedDict(pairs)

        dumped_data = json.loads(
            instance.dumped_json,
            object_pairs_hook=make_object,
        )
        parts = [
            '<table><thead><tr><th>',
            ugettext('Key'),
            '</th><th>',
            ugettext('Value'),
            '</th></tr></thead><tbody>',
        ]
        for key, value in dumped_data.items():
            parts.extend([
                '<tr><th>',
                key,
                '</th><td>',
                linebreaks(value),
                '</td></tr>',
            ])
        parts.append('</tbody></table>')
        return ''.join(parts)
Example #23
0
def safe_markdown(value, arg=''):
    """
    Runs Markdown over a given value, optionally using various
    extensions python-markdown supports.
    
    Syntax::
    
        {{ value|markdown:"extension1_name,extension2_name..." }}
    
    To enable safe mode, which strips raw HTML and only returns HTML
    generated by actual Markdown syntax, pass "safe" as the first
    extension in the list.
    
    If the version of Markdown in use does not support extensions,
    they will be silently ignored.
    
    """
    try:
        import markdown
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError('Error in markdown filter: Markdown could not be imported.')
        else:
            # Try to salvage this; whatever we do, we shouldn't
            # return potentially unsafe HTML.
            from django.utils.html import escape, linebreaks
            return linebreaks(escape(value))
    else:
        extensions=arg.split(",")
        if len(extensions) > 0 and extensions[0] == "safe":
            extensions = extensions[1:]
            safe_mode = True
        else:
            safe_mode = False
        return markdown.markdown(value, extensions, safe_mode=safe_mode)
Example #24
0
def router(request, path=None):
    if path:
        paths = path.split('/')
        values = None
        if len(paths) == 2:
            # if paths[1] == 'index.html':
            #     return HttpResponseRedirect('/%s/'%paths[0])
            # if paths[1] == '':
            #     paths[1] = 'index.html'

            minisite = get_object_or_404(Minisite, slug=paths[0])
            page = get_object_or_404(Page, slug=paths[1], minisite=minisite)
            if page.format == '0':
                page.text_html = linebreaks(urlize(imgize(page.text)))
            if page.format == '2':
                html = gfm(page.text)
                html = page.text
                page.text_html = markdown.markdown(
                    html, ['extra', 'codehilite', 'toc', 'nl2br'],
                    safe_mode=False,
                    html_replacement_text='--RAW HTML NOT ALLOWED--',
                    output_format='html5')
            values = {'minisite': minisite, 'page': page}
        else:
            return HttpResponseRedirect('/%s/' % path)
        return render_to_response('home/minisite.html',
                                  values,
                                  context_instance=RequestContext(request))
    return HttpResponseNotFound()
    def prepare(self):
        # Set the template and title for the page content, if they are not set (but don't save them)
        self.title = self.title or self.page.title
        self.template = self.template or self.page.template
        self.slug = self.slug or self.page.slug

        if not self.description:
            self.description = ''
        if not self.keywords:
            self.keywords = ''
        if not self.page_topic:
            self.page_topic = ''

        # Convert the content to HTML
        if self.content_type == 'html':
            pass  # Nothing to do
        elif self.content_type == 'markdown':
            self.content = markdown(self.content)
        elif self.content_type == 'textile':
            self.content = textile(self.content)
        elif self.content_type == 'rst':
            self.content = rst(self.content)
        else:
            self.content = mark_safe(linebreaks(escape(self.content)))
        self.toc = mark_safe(self.toc)
        return self
Example #26
0
def html_to_markdown(html):
    # Drupal uses nl2br() for display
    html = linebreaks(html)

    # If there are <br> in <code>, we need to wrap them into <pre>
    soup = BeautifulSoup(html, 'lxml')
    for code in soup.findAll('code'):
        if code.find('br') is not None:
            code.wrap(soup.new_tag('pre'))

        # Pandoc does shit with <br> inside <pre>, just replace them with linebreaks
        for br in code.findAll('br'):
            br.replaceWith('\n')

    # Drupal uses <cite>, pandoc wants <blockquote>
    for cite in soup.findAll('cite'):
        cite.name = 'blockquote'

    html = soup.prettify(encoding='utf-8')

    # Convert to pandoc-markdown
    with subprocess.Popen(
        ['/usr/bin/pandoc', '--columns=120', '--from=html', '--to=markdown'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL) as pandoc:
        markdown = pandoc.communicate(html)[0].decode('utf-8')

    # pandoc-markdown uses \ as line break, python-markdown uses two spaces
    return RE_PANDOC_MARKDOWN_LINEBREAKS.sub('  ', markdown)
Example #27
0
    def send_acceptance_email(self, object, body_text=None, subject=None):
        if body_text:
            text_message = body_text
        else:
            text_message = loader.render_to_string(
                "email/demande_acceptee.txt", {"organisation": object})
        html_message = loader.render_to_string(
            "email/empty.html",
            {"content": mark_safe(linebreaks(text_message))})

        if subject is None:
            subject = ("Aidants Connect - la demande d'habilitation n° "
                       f"{object.data_pass_id} a été acceptée")

        recipients = set(object.aidant_requests.values_list("email",
                                                            flat=True))
        recipients.add(object.manager.email)
        recipients.add(object.issuer.email)

        send_mail(
            from_email=settings.EMAIL_ORGANISATION_REQUEST_ACCEPTANCE_FROM,
            recipient_list=list(recipients),
            subject=subject,
            message=text_message,
            html_message=html_message,
        )
Example #28
0
            def get_rendered(self):
                field_value = getattr(self, _name)
                mt = getattr(self, "%s_markup_type" % name)
                
                if mt == markup_settings.MARKUP_PLAIN_TEXT:
                    field_value = field_value.strip()
                    if field_value:
                        field_value = escape(field_value)
                        try:
                            # try to urlize if there are no invalid IPv6 URLs
                            field_value = urlize(field_value)
                        except ValueError:
                            pass
                        field_value = linebreaks(field_value)
                elif mt == markup_settings.MARKUP_RAW_HTML:
                    pass
                elif mt == markup_settings.MARKUP_HTML_WYSIWYG:
                    pass
                elif mt == markup_settings.MARKUP_MARKDOWN:
                    try:
                        import markdown
                    except ImportError:
                        if settings.DEBUG:
                            raise Warning("Error in {% markdown %} filter: The Python markdown library isn't installed.")
                        return field_value
                    else:
                        field_value = markdown.markdown(field_value)

                # remove empty paragraphs
                field_value = field_value.replace('<p></p>', '')

                return mark_safe(field_value)
Example #29
0
    def renderQuote(self, with_title=True):
        output = []
        if self.author.date_birth:
            dob = gregtime.strftime(self.author.date_birth, settings.strftime_format) if settings.use_strftime else str(self.author.date_birth.year)
            if self.author.date_death:
                dod = gregtime.strftime(self.author.date_death, settings.strftime_format) if settings.use_strftime else str(self.author.date_death.year)
                lifestr = ' (' + dob + '&ndash;' + dod + ')'
            else:
                in_prop = '' if settings.use_strftime else 'in '
                lifestr = ' (born ' + in_prop + dob + ')'
        else:
            lifestr = ''
        if with_title:
            output.append('<h1>' + self.name + '</h1>')
        output.append('<p><em>' + self.description + '</em></p>' if self.description else '')
        output.append('<div id="left">')
        if self.text:
            output.append("""<div id="quote">
<div>""" + linebreaks(self.text) + """<br />
</div>
</div>""")
        else:
            output.append('<br />')
        output.append("""</div>
<div id="right">
<p>&mdash; <strong>""" + self.author.name + '</strong>' + lifestr + '<br />' + self.author.description + '</p>')
        output.append('</div>')
        return '\r\n'.join(output)
Example #30
0
    def prepare(self):
        # Set the template and title for the page content, if they are not set (but don't save them)
        self.title = self.title or self.page.title
        self.template = self.template or self.page.template
        self.slug = self.slug or self.page.slug

        if not self.description:
            self.description = ''
        if not self.keywords:
            self.keywords = ''
        if not self.page_topic:
            self.page_topic = ''
    
        # Convert the content to HTML
        if self.content_type == 'html':
            pass # Nothing to do
        elif self.content_type == 'markdown':
            self.content = markdown(self.content)
        elif self.content_type == 'textile':
            self.content = textile(self.content)
        elif self.content_type == 'rst':
            self.content = rst(self.content)
        else:
            self.content = mark_safe(linebreaks(escape(self.content)))
        self.toc = mark_safe(self.toc)
        return self
Example #31
0
        def append_comment_start(comment, list, html):
            commentmeta = {
                    'id': comment.id,
                    'url': comment.get_absolute_url(),
                    'name': comment.user_name,
                    'user_url': comment.user_url,
                    'date': comment.date.strftime('%Y %B %d, %H:%M'),
                    'depth': comment.get_depth(),
                    'edit': comment.get_admin_url(),
                    'spam': comment.get_spam_url(),
                    'content': linebreaks(comment.content),
#                    'parity': comment.get_parity(),
                    'parity': get_even_or_odd(comment),
                }
            if not comment.has_parent():
                #TODO author's comment
                html.append('<li class="comment %(parity)s thread-%(parity)s depth-%(depth)d" id="comment-%(id)d">\n' % commentmeta)
            else:
                html.append('<li class="comment %(parity)s depth-%(depth)d" id="comment-%(id)d">\n' % commentmeta)

            if commentmeta['user_url']:
                html.append('<div id="div-comment-%(id)d"><div class="comment-author vcard"><cite><a href="%(user_url)s" rel="external nofollow">%(name)s</a></cite></div>\n' % commentmeta)
            else:
                html.append('<div id="div-comment-%(id)d"><div class="comment-author vcard">%(name)s</div>\n' % commentmeta)

            if context['user'].is_staff:
                html.append('<div class="comment-meta commentmetadata"><a href="%(url)s">%(date)s</a>&nbsp;&nbsp;<a href="%(edit)s" title="Edit comment">Edit</a>. <a href="%(spam)s" title="Spam comment">Spam</a></div>\n'
                   '<p>%(content)s</p>\n' % commentmeta)
            else:
                html.append('<div class="comment-meta commentmetadata"><a href="%(url)s">%(date)s</a></div>\n'
                   '<p>%(content)s</p>\n' % commentmeta)

            if comment.get_depth() < COMMENT_MAX_DEPTH:
                html.append('<div class="reply"><a rel="nofollow" href="%(url)s#respond" onclick=\'return addComment.moveForm("div-comment-%(id)d", "%(id)d", "respond")\'>Reply</a></div></div>\n\n' % commentmeta)
Example #32
0
 def page_video_story(self, facebook_user, page_story):
     categories = set()
     if 'description' not in page_story:
         return
     message = linebreaks(page_story['description'])
     created_date = page_story['updated_time']
     if isinstance(created_date, unicode):
         created_date = dateutil.parser.parse(created_date)
     permalink = facebook_user.get_object(page_story['id'], fields='permalink_url')['permalink_url']
     embed_html = facebook_user.get_object(page_story['id'], fields='embed_html')
     
     if permalink.startswith('/'):
         permalink = "https://www.facebook.com%s" % permalink
     
     content = """<div class="NB-facebook-rss">
                      <div class="NB-facebook-rss-message">%s</div>
                      <div class="NB-facebook-rss-embed">%s</div>
                 </div>""" % (
         message,
         embed_html.get('embed_html', '')
     )
     
     story = {
         'title': page_story.get('story', message),
         'link': permalink,
         'description': content,
         'categories': list(categories),
         'unique_id': "fb_post:%s" % page_story['id'],
         'pubdate': created_date,
     }
     
     return story
Example #33
0
def linebreaks_filter(value):
    """
    Replaces line breaks in plain text with appropriate HTML; a single
    newline becomes an HTML line break (``<br />``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    return linebreaks(value, False)
Example #34
0
 def fix_linebreaks(self, content):
     content = content.replace('<p>', '')
     content = content.replace('</p>', '\n\n')
     content = content.replace('<br>', '\n')
     content = content.replace('<br/>', '\n')
     content = content.replace('<br />', '\n')
     return html.linebreaks(content)
Example #35
0
def markup(text, format):
    if format == models.RENDER_TYPE_HTML:
        return text
    elif format == models.RENDER_TYPE_TEXT:
        return html.linebreaks(html.escape(text))
    elif format == models.RENDER_TYPE_MARKDOWN:
        return markdown.Markdown().convert(text)
    elif format == models.RENDER_TYPE_TEXTILE:
        return textile.textile(text)
    elif format == models.RENDER_TYPE_RST:
        warning_stream = cStringIO.StringIO()
        parts = publish_parts(text,
                              writer_name='html4css1',
                              settings_overrides={
                                  '_disable_config': True,
                                  'embed_stylesheet': False,
                                  'warning_stream': warning_stream,
                                  'report_level': 2,
                              })
        rst_warnings = warning_stream.getvalue()
        if rst_warnings:
            logging.warn(rst_warnings)
        return parts['html_body']
    else:
        raise ValueError('invalid markup')
Example #36
0
 def _output(self):   
     """It is this method that is responsible for rendering the 
     object in HTML.
     """ 
     if self.text is None or self.text == "":
         return u""
     
     if self.text_format == '\E':
         return linebreaks(urlize(escape(self.text)))
     elif self.text_format == '\T':
         try:
             return textile(self.text)
         except:
             return mark_safe(_('There is an error in the Textile.'))
     elif self.text_format == '\M':
         try:
             return markdown(self.text, MARKDOWN_EXTENSIONS)
         except:
             return mark_safe(_('There is an error in the Markdown.')) 
     elif self.text_format == '\R':
         try:
             return restructuredtext(self.text)
         except:
             return mark_safe(_('There is an error in the reStructuredText.'))
     elif self.text_format == '\H' or self.text_format == '\W':
         return mark_safe(self.text)
     else:
         return mark_safe(escape(self.text))
Example #37
0
 def page_video_story(self, facebook_user, page_story):
     categories = set()
     if 'description' not in page_story:
         return
     message = linebreaks(page_story['description'])
     created_date = page_story['updated_time']
     if isinstance(created_date, unicode):
         created_date = dateutil.parser.parse(created_date)
     permalink = facebook_user.get_object(page_story['id'], fields='permalink_url')['permalink_url']
     embed_html = facebook_user.get_object(page_story['id'], fields='embed_html')
     
     if permalink.startswith('/'):
         permalink = "https://www.facebook.com%s" % permalink
     
     content = """<div class="NB-facebook-rss">
                      <div class="NB-facebook-rss-message">%s</div>
                      <div class="NB-facebook-rss-embed">%s</div>
                 </div>""" % (
         message,
         embed_html.get('embed_html', '')
     )
     
     story = {
         'title': page_story.get('story', message),
         'link': permalink,
         'description': content,
         'categories': list(categories),
         'unique_id': "fb_post:%s" % page_story['id'],
         'pubdate': created_date,
     }
     
     return story
Example #38
0
def text_to_linebreaks(txt):
	if txt:
		import re
		from django.utils.html import linebreaks
		return linebreaks(txt)
	else:
		return None
Example #39
0
    def get_dumped_data_display(self, instance):

        def make_object(pairs):
            pairs = sorted(pairs, key=operator.itemgetter(0))
            return collections.OrderedDict(pairs)

        dumped_data = json.loads(
            instance.dumped_json, object_pairs_hook=make_object,
        )
        parts = [
            '<table><thead><tr><th>',
            ugettext('Key'),
            '</th><th>',
            ugettext('Value'),
            '</th></tr></thead><tbody>',
        ]
        for key, value in dumped_data.items():
            parts.extend([
                '<tr><th>',
                key,
                '</th><td>',
                linebreaks(value),
                '</td></tr>',
            ])
        parts.append('</tbody></table>')
        return ''.join(parts)
Example #40
0
def safe_markdown(value, arg=''):
    """
    Runs Markdown over a given value, optionally using various
    extensions python-markdown supports.

    Syntax::

        {{ value|markdown:"extension1_name,extension2_name..." }}

    To enable safe mode, which strips raw HTML and only returns HTML
    generated by actual Markdown syntax, pass "safe" as the first
    extension in the list.

    If the version of Markdown in use does not support extensions,
    they will be silently ignored.
    """
    try:
        import markdown
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError(
                'Error in markdown filter: Markdown could not be imported.')
        else:
            # Try to salvage this; whatever we do, we shouldn't
            # return potentially unsafe HTML.
            from django.utils.html import escape, linebreaks
            return linebreaks(escape(value))
    else:
        extensions = arg.split(",")
        if len(extensions) > 0 and extensions[0] == "safe":
            extensions = extensions[1:]
            safe_mode = True
        else:
            safe_mode = False
        return markdown.markdown(value, extensions, safe_mode=safe_mode)
Example #41
0
def paginate_reviews(request, id):
    check_post_likes = False
    if request.method == 'GET':
        review_list = Reviews.objects.filter(
            show__id=id, has_post=True).prefetch_related('user')
        paginate_reviews = []
        paginator = Paginator(review_list, 15)
        page = request.GET.get('page')
        reviews = paginator.get_page(page)
        for review in reviews:
            has_user_liked_post = 'false'
            review_data = {
                "user": review.user.custom_username,
                "avatar": review.user.avatar.url,
                "post": linebreaks(escape(review.post)),
                "user_like": has_user_liked_post,
                "rating": str(review.rating),
                "likes": len(review.user_likes) if review.user_likes else 0
            }
            paginate_reviews.append(review_data)
        return JsonResponse({
            'paginated_reviews': json.dumps(paginate_reviews),
            'next_page': reviews.has_next()
        })
    raise PermissionDenied
Example #42
0
def render_activity(item):
    if not item.group:
        # not implemented
        return

    action_str = ACTIVITY_ACTION_STRINGS[item.type]

    if item.type == Activity.CREATE_ISSUE:
        action_str = action_str.format(**item.data)

    output = ''

    if item.user:
        user = item.user
        name = user.first_name or user.email
        output += '<span class="avatar"><img src="%s"></span> ' % (get_gravatar_url(user.email, size=20),)
        output += '<strong>%s</strong> %s' % (escape(name), action_str)
    else:
        output += '<span class="avatar sentry"></span> '
        output += 'The system %s' % (action_str,)

    output += ' <span class="sep">&mdash;</span> <span class="time">%s</span>' % (timesince(item.datetime),)

    if item.type == Activity.NOTE:
        output += linebreaks(urlize(escape(item.data['text'])))

    return mark_safe(output)
Example #43
0
def render_activity(item):
    if not item.group:
        # not implemented
        return

    action_str = ACTIVITY_ACTION_STRINGS[item.type]

    if item.type == Activity.CREATE_ISSUE:
        action_str = action_str.format(**item.data)

    output = ''

    if item.user:
        user = item.user
        name = user.first_name or user.email
        output += '<span class="avatar"><img src="%s"></span> ' % (get_gravatar_url(user.email, size=20),)
        output += '<strong>%s</strong> %s' % (escape(name), action_str)
    else:
        output += '<span class="avatar sentry"></span> '
        output += 'The system %s' % (action_str,)

    output += ' <span class="sep">&mdash;</span> <span class="time">%s</span>' % (timesince(item.datetime),)

    if item.type == Activity.NOTE:
        output += linebreaks(urlize(escape(item.data['text'])))

    return mark_safe(output)
Example #44
0
 def html_lead(self):
     """
     Returns the "lead" field formatted in HTML.
     """
     if self.lead:
         return linebreaks(self.lead)
     return ''
Example #45
0
def run(request, code_name = ''):
    code_name = code_name.strip()

    if request.POST:
        data = request.POST.copy()
    else:
        data = request.GET.copy()

    try:
        if code_name:
            c = CodeStore.objects.get(name = code_name)

            if not c.allow_anonymous and not (request.user.is_authenticated() and request.user.is_superuser):
                return HttpResponseForbidden()

            code = c.code
            input_data = c.data
            desc = c.description or ''
        else:
            if not (request.user.is_authenticated() and request.user.is_superuser):
                return HttpResponseForbidden()

            c = None
            code = data.get('code', '')
            desc = ''
            input_data = ''

        input_data = data.get('data', input_data)

        runobj = RunObj(request, code, input_data)
        out = runobj()

        tmp = u"<div style='font-weight:bold;'>%s</div>" % linebreaks(desc)
        tmp2 = u"<form method='post'><input type=submit value=Refresh><br><textarea name='data' cols=50 rows=5>%s</textarea></form><br>" % input_data

        out = linebreaks(out)
        if c and c.allow_input:
            out = tmp + tmp2 + out
        else:
            out = tmp + out
        return HttpResponse(out)

    except CodeStore.DoesNotExist, e:
        if request.user.is_authenticated() and request.user.is_superuser:
            return HttpResponse(unicode(e))
        else:
            raise Http404
Example #46
0
    def html_dump(self, seen=None, follow_sets=True):
        html = [
        ]  # the enclosing <table> and </table> must be provided by the template
        if seen is None:
            seen = set([self.__class__.__name__])
        for field in self._meta.fields:
            value = getattr(self, field.name)
            if field.rel and hasattr(value, 'html_dump'):
                seen.add(value.__class__.__name__)
                content = '<table bgcolor="yellow">%s</table>' % value.html_dump(
                    seen, follow_sets=False)
            else:
                content = unicode(value)
                if u'\n' in content:
                    content = linebreaks(content)
            html.append('<tr><th>%s</th><td>%s</td></tr>' %
                        (field.name, content))
        if follow_sets:
            for field_name in dir(self):
                try:
                    value = getattr(self, field_name)
                except AttributeError:
                    continue  # ignore Manager (objects attribute)
                else:
                    if hasattr(
                            value, '__class__'
                    ) and value.__class__.__name__ == 'RelatedManager':
                        inner_html = []
                        for rel_value in value.all():
                            id = '#%s' % rel_value.pk
                            if (hasattr(rel_value, 'html_dump') and
                                (rel_value.__class__.__name__ not in seen)):
                                seen.add(rel_value.__class__.__name__)
                                content = '<table>%s</table>' % rel_value.html_dump(
                                    seen, follow_sets=False)
                            else:
                                content = unicode(rel_value)
                            if u'\n' in content:
                                content = linebreaks(content)
                            inner_html.append(
                                '<tr><th>%s</th><td>%s</td></tr>' %
                                (id, content))
                        content = '<table>%s</table>' % '\n\t'.join(inner_html)
                        html.append('<tr><th>%s</th><td>%s</td></tr>' %
                                    (field_name, content))

        return '\n'.join(html)
Example #47
0
def html_format(value):
    """
    Return the HTML by format argument of the value
    """
    if not value:
        return ''
    elif '</p>' not in value:
        return linebreaks(value)
 def render_error(self, error):
     """
     A default implementation to render an exception.
     """
     return (
         '<div style="color: red; border: 1px solid red; padding: 5px;">'
         "<p><strong>%s</strong></p>%s</div>" %
         (_("Error:"), linebreaks(escape(str(error)))))
Example #49
0
def costformat(cost, unit):
    if unit == 1:
        value = "RMB ¥\n{:.2f}".format(float(cost))
    elif unit == 2:
        value = "H.K.$\n{:.2f}".format(float(cost))
    elif unit == 3:
        value = "U.S.$\n{:.2f}".format(float(cost))
    return mark_safe(linebreaks(value))
Example #50
0
 def _update(self, request, datum):
     confirm_message = self.get_confirm_message(request, datum)
     if confirm_message:
         self.attrs['data-confirm'] = linebreaks(confirm_message)
     confirm_class = self.get_confirm_class(request, datum)
     if confirm_class:
         self.attrs['data-confirm-class'] = str(confirm_class)
     return self.update(request, datum)
def _html_stripper(url):
    response = urllib2.urlopen(url)
    htmlresponce = response.read()
    # replaces <br> and <p> tags with newline charecter
    text = html.linebreaks(htmlresponce)
    # strips remaing html tags
    text = html.strip_tags(text)
    return text
Example #52
0
def wpArticle(format_string):
    '''
    Simple tag to pull the contents of a Wordpress Article inside a Django
    template. Best used with caching.
    '''
    wp = wpClient()
    post = wp.call(GetPost(format_string))
    return linebreaks(wpCaption(post.description))
Example #53
0
 def form_valid(self, form):
     ticket = self.get_object()
     ticket.notes = notes = form.cleaned_data['notes']
     ticket.save()
     if notes:
         return HttpResponse(linebreaks(notes, autoescape=True))
     else:
         return HttpResponse()
Example #54
0
    def render(self):
        """Outputs set of radio fields in a div.
    """

        from django.utils.html import linebreaks

        return linebreaks(u'<div class="quant_radio">%s</div>' %
                          u'\n'.join([u'%s' % force_unicode(w) for w in self]))
def linebreaks_filter(value, autoescape=True):
    """
    Replace line breaks in plain text with appropriate HTML; a single
    newline becomes an HTML line break (``<br>``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    return mark_safe(linebreaks(value, autoescape))
Example #56
0
def linebreaks_filter(value, autoescape=True):
    """
    Replaces line breaks in plain text with appropriate HTML; a single
    newline becomes an HTML line break (``<br />``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    return mark_safe(linebreaks(value, autoescape))
Example #57
0
 def _get_content(self, params, force_plain=False):
     if 'body-enriched' in params and not force_plain:
         return params['body-enriched']
     if 'body-html' in params and not force_plain:
         return params['body-html']
     if 'stripped-html' in params and not force_plain:
         return params['stripped-html']
     if 'body-plain' in params:
         return linkify(linebreaks(params['body-plain']))
Example #58
0
 def htmlize(self, content):
     """
     Convert to HTML the content if the MARKUP_LANGUAGE
     is set to HTML to optimize the rendering and avoid
     ugly effect in WYMEditor.
     """
     if MARKUP_LANGUAGE == 'html':
         return linebreaks(content)
     return content
Example #59
0
def linebreaks(value, autoescape=None):
    """
    Replaces line breaks in plain text with appropriate HTML; a single
    newline becomes an HTML line break (``<br />``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    from django.utils.html import linebreaks
    autoescape = autoescape and not isinstance(value, SafeData)
    return mark_safe(linebreaks(value, autoescape))