Strip unwanted html entieties - python

I'm upgrading mezzanine/django application from Mezzanine4.x/python2.7 to Mezzanine5.0/python3.7. My HTML page has been created using templatetags. Now the upgaraded page shows unwanted html entieties when checked with browser's (Firefox or Chrome) view page source feature. In python 2.7 it looks like
<p><a href='/'>Etusivu</a> > Ajankohtaista</p>
whereas in python 3.7 it shows
<p><a href='/'>Etusivu tags1</a> > Ajankohtaista</p>
these unwanted entieties are not seen with browser's inspect element feature.
from html:
<!doctype html>
{% load pages_tags mezzanine_tags i18n future staticfiles statfi_tags %}
<body id="{% block body_id %}body{% endblock %}">
{% block base %}
<div id="container">
<main id="page">
<div class="row">
<div id="breadcrumbs" class="col-xs-7 col-sm-8 col-md-9 col-lg-10">
{% block breadcrumbs %}
{% if page.basicpage %}
<p>{% anna_murut page.basicpage %}</p>
{% endif %}
{% endblock %}
</div>
</div>
{% endblock %}
</main>
</div>
{% endblock %}
</body>
</html>
from statfi_tags.py
# -*- coding: utf-8 -*-
from django import template
from datetime import date
from page_types import models
from django.db import models
from django.contrib.sites.models import Site
from django.template import Context, RequestContext
from django.template import Library, Node
from page_types.models import BasicPage, RegisterDescPage
from mezzanine.pages.models import Page, Link
from django.utils.encoding import *
register = template.Library()
def anna_murut(BasicPage):
sivu = BasicPage
letka = letka = u"<a href='/'>Etusivu</a> > "
if not "/" + BasicPage.slug == site_url(BasicPage):
letka += u"<a href='"+ site_url(BasicPage) +"'>"+ str(paasite(BasicPage)) +"</a> > "
letka += BasicPage.title
return letka
register.simple_tag(anna_murut)
Python 2.7-version in browser:
Python 3.7-version in browser:
Any ideas how to fix python 3.7 version? I don't know it it could be fixed in python code as the unwanted entities are note seen when I print the string returned by function "anna_murut".

The newer Django versions mark simple tags as unsafe by default, that means they may contain user submitted harmful code, therefore Django will escape any "dangerous" HTML tag.
You have to mark explicitly any string returned by custom tags as safe in order to avoid the default escaping.
from django.utils.safestring import mark_safe
def anna_murut(BasicPage):
# ...
return mark_safe(letka)
Just make sure that letka does not contain any unescaped user-submitted content.

Related

Show variable from flask in include html page

I have header.html:
<body>
<a class="navbar-brand mr-4 d-flex align-items-center" href="{{ url_for('dash') }}">
<img class="img-fluid" src="../static/assets/images/live-steam/logo.png" alt="Image">
<p class="px-1 font-weight-bold font-14">{{sys_domain}}</p>
</a>
</body>
and .py code:
#flask.route('/header')
def header():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SELECT * FROM system_settings')
user = cur.fetchone()
sys_domain = (user['system_name'])
return render_template("header.html", sys_domain=sys_domain)
When i include this header page to another page '{{sys_domain}}' show nothing!
example of page that header.html include to it:
<body>
<header>
{% include 'header.html' %}
</header>
</body>
I believe it is because when you try to use include, it will not call via the flask route. It is including the template directly and rendering it. You can check this official template documentation link
You can use the "with" keyword of jinja2 to call it that way.
You can check this link to have an idea of this.
You can retrieve the user['system_name'] from mysql as sys_domain variable in the route function of .py code from where you are calling the html file in which header.html is to be called. Then you can do something like this.
{% with sys_domain=sys_domain %}
{% include 'header.html' %}
{% endwith %}

How can I open a page with only one django model object's info after clicking it's ImageField on another page?

I am displaying django models on one of my website's pages. When I press one's ImageField on the page, I want it to open another page including only that one object. How do I do that ?
I thought about using the filter method in my views.py for filtering through my objects and finding that exact one, but I don't know what arguments to use.
Any ideas? (I am a beginner in django)
VIEWS.PY
from django.shortcuts import render
import requests
from . import models
def index(request):
return render(request, 'base.html')
def new_search(request): ********NOT IMPORTANT (I THINK)********
search = request.POST.get('search')
models.Search.objects.create(search=search)
objects = models.Object.objects.all()
results = objects.filter(name__contains=search).all()
args = { 'results': results }
return render(request, "my_app/new_search.html", args)
def individual_page(request):
link = request.GET.get('object-link')
objects = models.Object.objects.all()
return render(request, "my_app/individual_page.html")
MY TEMPLATE
{% extends "base.html" %}
{% block content %}
{% load static %}
<h2 style="text-align: center">{{ search | title }}</h2>
<div class="row">
{% for result in results %}
<div class="col s4">
<div class="card medium">
<div class="card-image">
<a name="object-link" href="{% url 'individual_page' %}"><img src="{{ result.image.url }}" alt=""></a>
</div>
<div class="card-content">
<p>{{result.name}}</p>
</div>
<div class="card-action">
View listing: Price TEST
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
So, the thing I want to do is: when I press the anchor tag that includes the image, I get redirectioned to another page which contains only that one object's info.

In Django, how to implement boilerplate HTML variables with Dynamic URLs used in templates and DB objects?

In Django, in my DB I've created string variables containing boilerplate HTML with dynamic URLs, and I can't quite get them to work in my templates.
I'm using render_as_template (https://github.com/danielrozenberg/django-render-as-template/blob/master/render_as_template/templatetags/render_as_template.py) so the dynamic URLs work. I tried custom template tags, but when I use those with render_as_template, it fails to load.
I then tried a custom context processor. I created two functions in the context processor, one for hyperlinks, and one for tooltips. I got the tooltips processor to work, but I can only reference them in the template via their number in the auto-generated dict from the queryset.
I did the same with the hyperlink processor, then tried modifying it to use string keys instead of integers, but it doesn't load all of the field. I must be missing something.
custom_tags.py
from django import template
register = template.Library()
#register.simple_tag
def rdo_hyper():
value = Boilerplate.objects.filter(name='RDO').values_list('hyperlink',flat=True)
return value[0]
# It's only going to return one field.
# Expected output: <a href="{% url 'guides:rdo' %}" target=”_blank” rel=”noopener noreferrer”>Foobar</a>
# tried a non-DB version, just in case
#register.simple_tag
def rdo_hyper2():
value = "<a href=\"{% url \'guides:rdo\' %}\" target=\”_blank\” rel=\”noopener noreferrer\”>Foobar</a>"
return value
# Expected output: <a href="{% url 'guides:rdo' %}" target=”_blank” rel=”noopener noreferrer”>Foobar</a>
custom_context.py
from myapp.apps.wizard.models import Boilerplate
def boilerplate_hyperlink_processor(request):
boilerplate_hyper = {
"foo": Boilerplate.objects.filter(name='Aftermarket').values_list('hyperlink',flat=True),
"bar": Boilerplate.objects.filter(name='Sights').values_list('hyperlink',flat=True)
}
return {'boilerplate_hyper': boilerplate_hyper}
# Expected output of boilerplate_hyper.foo:
#<a href="{% url 'guides:aftermarket' %}" target=”_blank” rel=”noopener noreferrer”>Aftermarket Support</a>
#
# Expected output of boilerplate_hyper.bar:
# <a href="{% url 'guides:sights' %}" target=”_blank” rel=”noopener noreferrer”>Sights</a>
def boilerplate_tooltip_processor(request):
boilerplate_tooltip = Boilerplate.objects.values_list('tooltip',flat=True)
return {'boilerplate_tooltip': boilerplate_tooltip}
# Expected output of boilerplate_tooltip.0:
#<sup></sup>
template.html
{% load static %}
{% load custom_tags %}
{% rdo_hyper as rdo_hyper %}
{% rdo_hyper2 as rdo_hyper2 %}
{% load render_as_template %}
...
<html>
{% autoescape off %}
1. {% rdo_hyper %}
2. {{ rdo_hyper }}
3. {% rdo_hyper2 %}
4. {{ rdo_hyper2 }}
5. {% render_as_template rdo_hyper %}
6. {{ boilerplate_hyper.foo }}
7. {% render_as_template boilerplate_hyper.foo %}
8. {% render_as_template boilerplate_tooltip.0 %}
{% endautoescape %}
{# The hyperlink value is:
<a href="{% url 'guides:aftermarket' %}" target=”_blank” rel=”noopener noreferrer”>
Aftermarket Support</a> #}
</html>
In template.html, the following occurs:
Renders, but the dynamic URL fails.
Doesn't render the variable at all. Otherwise page loads fine.
Renders, but the dynamic URL fails.
Doesn't render the variable at all. Otherwise page loads fine.
Doesn't render the variable at all. Otherwise page loads fine.
Only renders "Aftermarket Support']>" instead of the full hyperlink field from the DB.
Throws this error:
TemplateSyntaxError:
In template <unknown source>, error at line 1.
Could not parse the remainder: '\'guides:aftermarket\'' from '\'guides:aftermarket\''
1 <QuerySet ['<a href="{% url \'guides:aftermarket\' %}" target=”_blank” rel=”noopener noreferrer”>Aftermarket Support</a>']>
Works fine.
It's great that {% render_as_template boilerplate_tooltip.0 %} works, but I would much rather reference variables in templates through a string key. After all, the ethos of Django's templating language is that its templates can be read and written by non-programmers. Any ideas?
I went back to trying custom tags and this seems to work:
custom_tags.py
#register.simple_tag(takes_context=True)
def rdo_hyper2(context):
value = "<a href=\"{% url \'guides:rdo\' %}\" target=\”_blank\” rel=\”noopener noreferrer\”>Foobar</a>"
rendered = context.template.engine.from_string(value).render(context)
return rendered
template.html
{% load custom_tags %}
...
{% rdo_hyper2 %}
When including {% rdo_hyper2 %} or other custom tags inside a DB field, I also have to use {% load custom_tags %} at the top of that field every time or else it throws:
Invalid block tag on line 12: 'rdo_hyper2'. Did you forget to register or load this tag?
Hopefully that's not resource intensive!

django tag 'get_recent_articles' received too many positional arguments

I am trying to make a recent article list in the sidebar of my blog. So I make a tag in templatetags.
I use django1.8 and python2.7.
templatetags/blog_tags.py
from ..models import Article,Category
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
#register.simple_tag
def get_recent_articles(num=5):
return Article.objects.all()[:num]
base.html
{% load blog_tags %}
<!DOCTYPE html>
...
<div class="widget widget-recent-posts">
<h3 class="widget-title">recent</h3>
{% get_recent_articles as article_list %}
<ul>
{% for article in article_list %}
<li>
{{ article.title }}
</li>
{% endfor %}
</ul>
</div>
When I runserver,Template error,Traceback display the problem line is {% get_recent_articles as article_list %}
TemplateSyntaxError at /blog/index/
'get_recent_articles' received too many positional arguments
How do I solve this error? Please give me some advices.
Any help will be much appreciated.
The ability for simple tags to store their results in a variable was added in Django 1.9.
In previous versions, you should use the assignment_tag decorator instead.

Django html redirects but doesn't load page

I am creating a Django web application and have come across the following problem.
I have created a new html page called teamList.html, which when clicking a href hyperlink on the main page, should redirect to teamList page. The url in the browser, which starts as http://127.0.0.1:8000/ changes to http://127.0.0.1:8000/teamList, but the page underneath doesn't change, but instead reloads the starting page.
The current application handles the login and main page in the html as such (default after login displays a graph):
#index.html
<body>
<img src="{% static "myApp/images/logo.gif" %}" alt="logo" />
{% if user.is_authenticated %}
<p>currently logged in as: {{ user.first_name }} {{ user.last_name }}
<p>logout
<p>Team List
<div id="radarChart">
{% block radarChartBlock %}{% endblock %}
</div>
{% else%}
<div id="login">
{% block login %}{% endblock %}
</div>
{% endif %}
</body>
My urls.py looks like this:
from django.conf.urls import patterns, url
from myApp import views
urlpatterns = patterns('',
#http://localhost:8000/
url(r'^$', views.index, name='index'),
url(r'^/teamList/$', views.renderTeamList, name='teamList')
)
EDIT: My views.py method for my teamList.html looks like this:
from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from myApp.models import FocusArea
from myApp.tables import TeamTable
from django_tables2 import RequestConfig
def renderTeamList(request):
table = TeamTable()
RequestConfig(request).configure(table)
return render(request, 'teamList.html', {'table': table})
In addition to the comments there is a problem with your urls.py. Your regular expression for teamList url starts with / and therefore will not match http://127.0.0.1:8000/teamList as Django replaces a leading slash by default. From the docs:
There’s no need to add a leading slash, because every URL has that. For example, it’s ^articles, not ^/articles.
For more details see Django docs here.

Categories