Django include templates in markdown - python

I have Django templates written in Markdown. I'd like to implement template tag to include rendered markdown.
{% include_md 'mytemplate.md' }
I wrote template tag to render my template:
import markdown
from django.template import Library, loader, Context
#register.simple_tag(takes_context=True)
def include_md(context, template_name):
t = loader.get_template(template_name)
return t.render(Context({
#...
}))
but I need to put somewhere in the middle of my function something like:
markdown.markdown(template_content)
Unfortunately, template loader doesn't return content of template. So what is a best way to achieve rendering? I woudln't like to implement my own opening template methods with open().

Django provides a convenience method render_to_string for situations like this:
from django.template.loader import render_to_string
#register.simple_tag(takes_context=True)
def include_md(context, template_name):
template = render_to_string(template_name, context)
return markdown.markdown(template)

Related

Why my code Django into HTMl variables didnt work

I’m trying to get a variable into a html document with python and django
def nombrarVariables(request):
nombre="juan"
doc_externo=open("SeleccionGrafica2.html")
template=Template(doc_externo.read())
doc_externo.close()
contexto=Context({"variable": nombre})
documento=template.render(contexto)
return HttpResponse(documento)
Can you try this snippet in a more concise way:
from django.shortcuts import render
def nombrarVariables(request):
nombre = 'juan'
context = {'nombre': nombre}
return render(request, 'SeleccionGrafica2.html', context)
In your template you can access your variable with {{nombre}} and in the render function change the path of your templates regarding your file structure

How to pass a query set to the context class in Django?

I am trying to pass a queryset object to django context class, but doing so results in the following error: TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
Now i understand that the context accepts only a dictionary but i am following an example from a book called django_unleashed which uses Django version 1.8 and i am using django 2.0. and i guess it was done like that in previous versions.
So my question is how should i do this step correctly using django 2.0
from django.shortcuts import render
from django.http import HttpResponse
from .models import Tag
from django.template import Context, loader
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template('organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
As the error suggests, you should use a regular dictionary for the context:
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template('organizer/tag_list.html')
context = {'tag_list': tag_list}
output = template.render(context)
return HttpResponse(output)
In practice, you would usually use the render shortcut rather than manually rendering the template:
from django.shortcuts import render
def homepage(request):
tag_list = Tag.objects.all()
context = {'tag_list': tag_list}
return render(request, 'organizer/tag_list.html', context)
'''you have a model class named 'Tag',
wish your template is on ' Project directory/ app directory/ template/ same name of app directory'
example: let your project name is 'Website' and app name is 'organizer' then the template will be on: 'Website/ organizer/ templates/ organizer/ tag_list.html' Confirm your TEMPLATES setting is default on setting.py file."'
from django.shortcuts import render
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
context = { 'tag_list' : tag_list}
return render ( request, 'organizer/tag_list.html', context)

What is the difference between render() of DjangoTemplates class and render() method found in django.shortcuts module?

I am trying to learn Django. I am creating a small applicationt to understand its basic functionalities. In views.py of a django app, some tutorials use render() from template while others use render() from django shortcuts module.
For instance, in views.py
from django.shortcuts import render
def home(request):
context = {}
template = "app/add_item.html"
return render(request, template,context)
and yet others,
from django.http.response import HttpResponse
from app.models import Items # this is the model
def home(request):
item_list = Items.objects.order_by('-item_name')
template = loader.get_template('app/add_item.html') # could be index.html as well
context = {
'item_list': item_list,
}
return HttpResponse(template.render(context, request))
What is the difference between render() method of DjangoTemplates class and render() method found in django.shortcuts module? Which one should I prefer and why?
django.shortcuts.render is, as its name implies, a shortcut for returning a rendered template as a response from a view. Its use is rather limited to that context. It takes an HttpRequest instance as its first argument and its main purpose, per the docs, is to
combine a given template with a given context dictionary and returns an HttpResponse object with that rendered text.
Importantly, this selects a template by name. It is intended to select a template for rendering and returning as a response.
Template.render is part of the low-level template API and takes the single template, represented by that object, and renders it to a string.
Importantly, this takes only the template already represented by your object. It has no mechanism for discovering another template to render.
Generally, the shortcut version is the most useful, as quite often you want to return a rendered template as a response from your views. This is the whole reason it exists.

Django - manually build HttpResponse, but want to use a template too

When returning an HttpResponse object with render_to_response you can provide a template and it will use that template and fill in all the {{ variables }} you've set within your template.
If I want to build my HttpResponse object manually, is it possible to still use one of my templates in my template directory?
Using render_to_string, you will get rendered string. You can pass the returned string to the HttpResponse.
from django.template.loader import render_to_string
...
rendered = render_to_string('my_template.html', {'foo': 'bar'})
response = HttpResponse(rendered)
Yes - you can use Django's template loader to load your template as a Template object, and then render it to a string, which you pass to HttpResponse:
from django.template import Template, Context
from django.template.loader import get_template
def my_view(request):
temp = get_template('/path/to/template.html')
result = temp.render(Context({'context': 'here'})
return HttpResponse(result)
EDIT
Just noticed #falsetru's answer above - that's probably a better and shorter way!

Not work variables in django templates

My context dictionary not sending to my templates.
I have function
from django.shortcuts import render_to_response
from django.template import RequestContext
def home(request):
return render_to_response('home.html',{'test':'test'},context_instance=RequestContext(request))
and i have simple template such as:
<html>
<body>
my test == {{test}}
</body>
</html>
When i open my site in browser, i have "my test == ".
settings.py is default. I dont use something custom. What the problem?
Server is apache with wsgi module.
I know, but I see your post just now. You did great, but you need something more to do. Here is the view
def home(request):
# You need to retrieve something from the database or create a variable here
test = Test.Objects.all()
# Use Context Dic
context = {
'test': test,
}
# Then Use the return
return render(request, 'home.html', context)
(EDITED)
Now this will work.

Categories