Why my code Django into HTMl variables didnt work - python

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

Related

How to render in template in Django?

I am trying to display my data on the HTML file but I am unable to display, I have a function in views.py file and i render this function data on my HTML file, but it's not going to the HTML path, please let me know how I can display data in Django default template.
Here is my app appname and its have a views.py file and this file has a function that displays my data on the HTML page...
please have a look at the views.py file...
def mydata():
var1=Mymodel.objects.all()
template_name='../templates/admin/appname/modelname/change_list.html'
context={'var1':var1}
return render(request, template_name, context)
Note: this template folder is that which Django provides in default, it's not available inside my app (appname), it's available outside of my app
so main issue is in thsi path template_name='../templates/admin/appname/modelname/change_list.html', because it's getting the correct path
Create folder templates inside you app, put there template.html. Then in views.py:
def mydata(request):
you code
return render(request, 'template.html', locals())
locals will collect all variables that you created inside function.

Django include templates in markdown

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)

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 Admin Custom Pages and Features

I'm (new to) working in Django and would like to create two features that do not rely upon models/database tables. The basis of this app is as a web-based wrapper to a Python application.
The features are:
I would like to be able to load a ConfigObj text file into a page and edit it's configuration prior to saving again.
I would like to be able to call command line python/bash scripts and display their output on a page - like exec in PHP.
At the moment I'm working on simple custom admin pages without model as described here:
Django admin, section without "model"?
Would this be the right direction to go in? I'm not sure proxy tables apply as the features I desire have nothing to do with any data.
So far I have looked at is it possible to create a custom admin view without a model behind it and a few other links. At the moment I have:
main/urls.py
url(r'^admin/weectrl', include('weectrl.urls')),
which links with weectrl/urls.py
from weectrl import views
urlpatterns = patterns('',
(r'^admin/weectrl/manage/$', weectrl_manage_view),
(r'^admin/weectrl/config/$', weectrl_config_view),
)
which points to weectrl/views.py
def weectrl_manage_view(request):
r = render_to_response('admin/weectrl/manage.html', context, RequestContext(request))
return HttpResponse(r)
def weectrl_config_view(request):
r = render_to_response('admin/weectrl/config.html', context, RequestContext(request))
return HttpResponse(r)
The current error message is name 'weectrl_manage_view' is not defined
Ok, found something that works.
In the main url.py
url(r'^admin/weectrl/', include('weectrl.urls')),
In app/urls.py
urlpatterns = patterns('',
url(r'^config/$', views.config, name='config'),
url(r'^manage/$', views.manage, name='manage'),
)
and in app/views.py
def config(request):
context = ""
return render(request, 'weectrl/config.html', context)
def manage(request):
context = ""
return render(request, 'weectrl/manage.html', context)
html files are in app/templates/app/...

Categories