django-markupfield returns string - python

I'm trying to set up a Django app that has a MarkupField in it's model, like this:
from django.db import models
from markupfield.fields import MarkupField
class Recipe(models.Model):
instructions = MarkupField(default_markup_type='markdown')
Then I render the field in a Jinja2 template, like this:
{% if recipe.instructions %}
{{ recipe.instructions }}
{% else %}
No instructions have been added yet.
{% endif %}
Rendering of the markdowned text works flawless, but it is placed as a string inside the DOM so the browser doesn't interpret the HTML tags, like you can see here:
I don't feel like I missed something relevant in the django-markupfield's docs, but somehow I need to get rid of this string representation.
Anyone of you guys got an idea? Thanks in advance.

Thanks to #doru's advices I stumbled across the Jinja2 documentation and found the autoescaping statement:
{% autoescape off %}{{ recipe.instructions }}{% endautoescape %}
This one worked for me.
It's even possible to make it work globally by setting the autoescape option to False.
{
'BACKEND': 'django_jinja.backend.Jinja2',
...
'OPTIONS': {
'autoescape': False,
...
}
},

Related

jinja2 : how to match string to json field

I'm having a problem in a jinja template. If I have an object 'jsonobj' like so:
{
"type": "test",
"people": [{"name": "bill", "age": 43}]
}
in my template I'm trying to do an if like
{% if 'test' is jsonobj.type %}
<!-- some html here -->
{% else %}
<!-- some other html here -->
{% endif %}
but I get an error:
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endfor'. You probably made a nesting mistake. Jinja is expecting this tag, but currently looking for 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
when I add curlies around jsonobj.type I get
jinja2.exceptions.TemplateSyntaxError: expected token 'name', got '{'
Was looking at the docs here and I thought it should work...any ideas?
thanks
I tried any variation I could think of; ==, is, isin and so on. Tried wrapping json obj in one and two sets of curlies. Did lots of googling
May be you forget endif tag at end?
{% if 'test' is jsonobj.type %}
...
{% else %}
...
{% endif %}
{% endif %} it seems you forgot to turn off the if blog
I was able to resolve this issue by making sure the whitespace/indenting was even. That seemed to resolve the issue

How to go through a Django dictionary in HTML template

Im new to Django and I don't really have a clear idea how the Django Template language works but I have a dictionary that is something like this:
{
"info":{
"a":"test1",
"b":"test2",
}
}
How can I get the values for "a" and "b" in Django template.
I'm not sure if that makes sense but what I mean would look something like this in Python:
for i in info:
print(info.i)
I already tried this but it didn't work
{%for i in info %}
{% if info.i %}
console.log('{{info.i}}')
{% endif %}
{% endear %}

Show url link only if condition meet using data in model - Django

I am using template to render basic html in django and specify link as below.
<li>Geometry</li>
I want to hide this link based on condition using model information.
Does anyone know how to do this?
You can surround the html in an if statement using the Django template language:
{% if object.something %}
<li>Geometry</li>
{% endif %}
You can use operators, filters or complex expressions if object.something is not a boolean
Django has an if template tag, see:
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#if
from the docs:
{% if not athlete_list %}
There are no athletes.
{% endif %}

Jinja2 variable (string) not being printed if surrounded by {{ delimiter }}

I have a macro in jinja2 that was working perfectly up until I tried to pass a string to it that looks something like this /test/{{ vehicle.id }}. The string printed to the page is /test/.
The string is coming from a database, so I'm a little confused what's happening. It's like jinja is trying to parse the string and replace the values (which is actually what I'm trying to accomplish), but it's failing and ripping the expression out instead. I tried passing the vehicle dict to the macro as well to see if it would 'just work', but no dice. I thought if maybe I had vehicle available to the context it would work without much effort on my part.
Here's some simple sample code:
# Assume db_values.url is set to '/test/{{ vehicle.id }}'
{% macro banner(db_values, vehicle={}) %}
{% endmacro %}
And where I'm calling it:
# Assume vehicle = { 'id': '1' }
{{ vehicle.id }}
{{ db_values }}
<div class="banner-link">
{{ banner(db_values, vehicle) }}
</div>
And this is what's being outputted to the page:
1
{u'url': u'/test/'}
<div class="banner-link">
</div>
Hitting mongodb directly in terminal responds with:
{ 'url': 'test/{{ vehicle.id }}' }
Anybody else run into something like this before? Basically what I'm trying to do is allow somebody in an admin interface to use tokens in the url that are replaced at runtime based on the context of the page. Seems simple enough, but jinja keeps stripping it.
Okay, I solved this on my own. The reason my database value had the {{ vehicle.id }} syntax in it is because I wanted to jinja to parse it. So when jinja wasn't parsing it (probably because of a context issue), I took to a custom filter and I'm happily on my way.
Here's the gist of it:
Jinja2 Filter
from jinja2 import Environment
def replace_tokens(url, vehicle):
if url is not None:
url = Environment().from_string(url).render({ 'vehicle': vehicle })
return url
Macro
# Assume db_values.url is set to '/test/{{ vehicle.id }}'
{% macro banner(db_values, vehicle={}) %}
{% endmacro %}

I have problems with setting up django-pagination

I'm making a template for Django site (it's quote database). I wanna have Digg-like pagination. Altough, author of the application has made his own pagination, unfortunately without page numering (just "previous" and "next" links). So I've installed django-pagination, but I can't use it with the site. I'm completly new in Django, even programming - I'm just a simple webdesigner... OK, here we go.
There is the original script: https://bitbucket.org/fleg/fqdb/
The first thing is a problem with template context processors. My settings.py didn't have this section, so I added it exactly like in django-pagination documentation. When I run the site, I get an error: "Put 'django.contrib.auth.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application". So how I have to order that?
A second problem is template. I use it exactly like on the screencast:
{% extends "fqdb/base.html" %}
{% load pagination_tags %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<h1>{{ title }}</h1>
{% if quotes %}
{% autopaginate quotes %}
{% for quote in quotes %}
{% include 'fqdb/quote_body.html' %}
{% endfor %}
{% paginate %}
{% else %}
<p>Brak cytatów.</p>
{% endif %}
{% endblock %}
But I get "Template error: Caught KeyError while rendering: request". But... Seriously, I don't know what's wrong with this code!
There is the paginated view - quote list. It work without pagination, so I don't think if it's a problem, but maybe.
def list_paged(request, page, order_by_what, title, reverse_name):
hash = get_ip_hash(request)
lista = Quote.objects.filter(accepted = True).order_by(order_by_what)[:]
returnDict = {'quotes': lista, 'title': title, 'hash': hash, 'sidebar': get_sidebar()}
return render_to_response('fqdb/quote_list.html', {'quotes': get_quotes(quotes)}, context_instance=RequestContext(request))
I have modified it to not paginating, because it's django-pagination task. You can find original view on Bitbucket.
Maybe do you know some better pagination solutions?
It looks like you need to add django.contrib.auth.context_processors.auth and django.core.context_processors.request context processors to your TEMPLATE_CONTEXT_PROCESSORS setting.
Before you defined TEMPLATE_CONTEXT_PROCESSORS, django would have used the default. It looks as if some of your code requires the auth processor, hence your first error message.
The KeyError looks to me as if you require the request processor.
Try the following in your settings file:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
#"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
#"django.core.context_processors.static",
#"django.contrib.messages.context_processors.messages")
"django.core.context_processors.request"
)
I've used the default list given in the Django 1.3 request context docs, added the request processor, and commented out the ones that you don't seem to need.
The order of template context processors does not usually matter, as long as they do not define overlapping variable names.
If the objects are passed from a templatetag
def comment_app(context):
objects = Comments.objects.get_tree_for_object(context['content_object'])
return {
'comments_tree': objects,
'request': context['request']
}
register.inclusion_tag('comments/comment_app.html', takes_context=True)(comment_app)
note the: 'request': context['request']
{% autopaginate quotes N%}
N - how many items you need for each page

Categories