How to display object in template Flask as json? - python

I have a route method:
#app.route('/add', methods=['GET'])
def add_view():
return render_template('add.html', categories=api.categories())
Then I tried to display categories as JSON inside template add.html:
{{ categories | json }}
It does not work

I find it hard to understand exactly what you're looking for here so I'd like to see more details but here's an answer based on what I think you're asking for (I'll edit this to suit your needs / remove this comment entirely if things change).
You're invoking api.categories() and are looking to render this as JSON on your HTML template, yes?
OK what I'd recommend here is to ensure that api.categories() is returning an instance of dict. For example, your api.categories() call should return something like this:
{
"testKey1": "testValue1",
"testKey2": "testValue2"
}
Now to render this as JSON in your HTML template. You can import the json module in your Flask module using the following import:
import json
Now your return statement in your add_view method will be as follows:
return render_template('add.html', categories=json.dumps(api.categories()))
You can now do something like as follows in your HTML template:
<script>
document.write("{{categories}}");
<script>
This should render your JSON for you just fine.

Related

Iterate over json string items in jinja2

Hi I need to send data in string format to my jinja templates, and the render them. The only way I found is to format my data as JSON and send it as a string to the renderer. But I don´t know how to use it in the templates, it seems that the tojson filter it´s not for this purpose, because it keeps rendered a string.
to keep it simple I'm doing something similar to:
import json
a = {"a":1,"b":[1,2,3,4]}
response = json.dumps(a)
in template:
{{ response }}
{{ response|tojson }}
both give a string response, not a dict or an object that I can use to render based on the values
You can import json to use it's load function to load it into jinja.
from json import loads
environment = jinja2.Environment(whatever)
environment.filters['load'] = loads
{{ response|load }}
Reference:
Import a Python module into a Jinja template?

Set the default template filter for the context_processor in flask

In my flask app i have these codes:
from __main__ import app
#app.context_processor
def breakline():
return { 'break': '<br>' }
How to use in html format is as follows:
{{ break }}
The above code works but there is a problem; A safe filter is needed to detect <br>; But I do not want to be added in html format every time like this:
{{ break | safe }}
I want this safe filter to be applied automatically and no longer need to be used in the html page. Is such a thing possible?
This is just an example and I do not just want to be able to create a <br>. I want to know if a filter can be added to a context_processor or not.
You can mark your html code as safe by using Markup.
from flask import Markup
#app.context_processor
def breakline():
return { 'break': Markup('<br>') }

Django returning static HTML in views.py?

So I have a standard Django project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using HttpResponse() I know it's a bit unorthodox, but this is an example of what I'm thinking about:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
def index(request):
html = """
<html>
<body>
This is my bare-bones html page.
</body>
</html>
"""
return HttpResponse(html)
My corresponding JS and stylesheets would be stored in the same directory as views. py in my app in this example. Just making sure: I'm not asking if this works, because I already know the answer is yes, I just want to know if there are any disadvantages/drawbacks to this method, and why don't more people do this?
You can use built-in template renderer to get works filters/templatetags/etc
Most people dont use this because it mixes Python with HTML and gets very messy and out of hand very quickly
To answer your question, this solution works alright, but it is not adopted by many programmers because it makes the whole code disorganized and not easy to understand.
Also, this system would not be good for large projects because the code would contain lots of html in the same file as the python. It is always nice and time saving to separate code into files based on performance.
A better solution
Save your html in a folder called templates in the current directory, in this case, the templates folder can contain an index.html file which would have
<html>
<body>
This is my bare-bones html page.
</body>
</html>
in the views create an index view for this template using the code below
def index(request):
return render(request, 'index.html')
if you would need to pass in some data to the html you can use context in the request as shown below:
def index(request):
context = {
"name":"some name"
}
return render(request, 'index.html', context=context)
access the data in html using the structure below:
<html>
<body>
The data passed to the page is {{name}}.
</body>
</html>
I hope this helps

Django Variable Template Tags

<p>Hello, my name is {{ name }} ! </p>
Where/how do I set the variable: name = 'mike'? I've tried putting this in the settings.py and models.py file and it does not work.
Any info of proper code to put in a .py file would be great! I've searched through the docs page but didn't see how to set a variable for retrieval.
You need to set your variable value in the view function which normally put in view.py
e.g.
def hello(request):
return render(request, "hello.html", {"name": "mike"})
And you may would like to check https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render to find more about how to render templates with passed variables.
You need also learn more about how does Django's URL mapping works https://docs.djangoproject.com/en/dev/ref/urls/
Use context processors in django. Django handles this dilemma of making some information available to
all pages with something called context processors.
Some Code is like this,
Create a new file called context_processors.py inside your utils app directory, and add the
following code to it:
from project import settings
def context_data(request):
return {
'name': settings.name,
'request': request
}

Using variables in Django model content

i like to use the url template tag in my model's content.
example:
models content:
Car.description = 'this is a link to our main page: home'
in template.html:
<div>{{ Car.description }}</div>
result
<div>this is a link to our main page: home
is it possible, or do i have to write my own template tag?
thanks in advance
Roman
Assuming you have this:
car.description = 'this is a link to our main page: home'
You can do:
from django.template import Context, Template
from django.core.urlresolvers import reverse
class Car(models.Model):
def description_with_url(self):
return Template(self.description).render({'url': reverse('home')})
or use the same logic in custom template tag instead of method..
I can't figure out why you would need to do that. Assuming that I fully-understood your question, you are attempting to store something within a model's field that then behaves "dynamically" when rendered.
A model field's content that stores a URL should contain a URL and only a URL by utilizing the URLField.
Else, if you're dynamically building the URL from somewhere else, simply use template markup, i.e. the url template tag as it is meant to be used; it can also take parameters depending on the specific URL pattern. I.e. the url tag is meant to be used in the template's context.
Let me know if you update the question to describe what you are trying to achieve. But storing "behaviour" at data level is something to simply stay away from.

Categories

Resources