String to Integer in Django Template - python

I have rendering one string in django template but in django template, I want to convert it into integer. I have tried many thing like |add:to_int but it doesn't work.

#Vaibhav Mishra,
Does it work for you? https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#add
Like: {% value|add:"0" %}
If it does not work for you: then create a custom template filter and register it:
YOUR_APP_FOLDER/
__init__.py
models.py
templatetags/
__init__.py
your_app_name_extras.py [any valid filename.py]
views.py
in your_app_name_extras.py
from django import template
register = template.Library()
#register.filter()
def to_int(value):
return int(value)
In your template file, you need to put the code:
{% load your_app_name_extras %}
{{ value|to_int }}
For more details:
https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
Need to convert a string to int in a django template

You can do like that:
{% if string_value == int_value|stringformat:'s' %} {% endif %}

Related

Send object to child template in {% include %} tag in Django

How can I send list or object to sub template while including template?
{% include "subtpl.html" with parameter={"name":"Saifullah","address":"Lahore"} %}
When I run the above code I get
TemplateSyntaxError Could not parse the remainder: '{"name":"Saifullah","address":"Lahore"}' from '{"name":"Saifullah","address":"Lahore"}'
You can't do this with Django templates.
You can pass the object if you add it to the template context in the view, for example:
def my_view(request):
parameter = {"name":"Saifullah","address":"Lahore"}
return render(request, 'my_template.html', {'parameter': parameter}
{% include "subtpl.html" with parameter=parameter %}
Or you could unpack the dictionary and use multiple keyword arguments.
{% include "subtpl.html" with name="Saifullah" address="Lahore" %}

How do I access the `BLOG_SLUG` string?

When I type {{ settings }} on a template and open it with Mezzanine, it shows me {u'MEZZANINE_ADMIN_PREFIX': u'grappelli/'}. I'm trying to access settings.BLOG_SLUG, but cannot get that setting to appear in the template. Here's a small snip of what my template looks like.
{% load mezzanine_tags keyword_tags i18n %}
{% block main %}
{{ settings }}
{% endblock %}
How do I get my template to display the string stored in setting.BLOG_SLUG?
you have to pass settings.BLOG_SLUG from your view than you would be able to display it in html.
for example you have written line settings.py file like
BLOG_SLUG = 'something'
than you can retrieve it in your view as
SETTINGS.BLOG_SLUG
and you can pass it from your view to html

Django template tags forloop

I have created a template tag and trying to loop through the results from the template tag
but I don't get any results
tags.py
from django import template
from loadprograms import dbcontext
register = template.Library()
#register.simple_tag
def get_category():
x = dbcontext.DBContext()
results = x.executequery("Select name from Categories")
categories = [each[0] for each in results]
return categories
template code
{% load category_tags %}
{% get_category %}
{% for each in get_category %}
{{ each }}
{% endfor %}
The {% get_category %} prints all the categories without any issues but the for loop stmt
that loop through the results does not work
What could be the problem?
To make this change in your tag, you'll have to set a variable in the context, but if your objective is to have a list of categories available in templates, just like you would have passed it in from the view - then you need to write a template context processor, which will allow all views to have this variable in their context.
A template context processor is just a method that adds to the request context, by returning a dictionary. Think of it like a view function, that just returns a context.
from .models import Categories
def cat_names(request):
return {'category_names': Category.objects.values_list('name', flat=True)}
To activate this context processor, you have to do a few things:
Add the above code to a file called template_processors.py in the same place as your models.py and views.py.
In your settings.py, add the fully-qualified name of the method to the TEMPLATE_CONTEXT_PROCESSORS setting, making sure you don't override the defaults. To do this easily, import the default settings first, then add to it:
from django.conf.default_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + ('yourapp.template_processors.cat_names',)
Use the render shortcut, which will make sure the context is correctly passed.
In your views, you can now just do this:
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
In your home.html, you can now do:
{% for name in category_names %}
{{ name }}
{% endfor %}

How do I access my own template variables from within a custom template tags template?

I am using Django to build a website.
I have a context processor setup that looks something like this:
TEMPLATE_CONTEXT_PROCESSORS = (
...
"mysite.context_processors.mystandardvariables"
)
This adds some standard variables that I like to use in templates, such as SITE_NAME and SITE_ROOT.
I have just created my first custom template tag and I find that I cannot access these standard variables.
I don't get any errors and my page displays ok, it's just that the variable that I want are not available.
To check which variables are available I already used {% debug %}.
My tag looks like this:
#register.inclusion_tag('search/search_snippet.html', takes_context = True)
def search(context):
form = forms.SearchForm()
return {'form': form }
The template for the tag looks like this:
<form action="{{ SITE_ROOT }}search" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
I am including the search tag in my home page like this:
{% extends "base.html" %}
{% load search_tags %}
{% block content %}
{% search %}
{% endblock %}
To answer my own question, I figured out a way to do what I want using a normal template tag rather than an inclusion tag.
#register.tag
def search(parser, token):
return SearchNode()
class SearchNode(template.Node):
def render(self, context):
return render_to_string('search/search_snippet.html',
{ 'form' : forms.FindForm() }, context)
Here I am passing the context through to the function that renders my template to a string.
I would have preferred to implement this as an inclusion tag as it seems like less work, but I wasn't sure how to get it to work.
If anyone knows how to get this working with an inclusion tag please answer and I'll mark your question as the right answer.

Include a view in a template

In django I have a view that fills in a template html file but inside the html template I want to include another view that uses a different html template like so:
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ view.that_other_function }}
{% endblock content %}
Is this possible?
Yes, you need to use a template tag to do that. If all you need to do is render another template, you can use an inclusion tag, or possibly just the built in {% include 'path/to/template.html' %}
Template tags can do anything you can do in Python.
https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
[Followup]
You can use the render_to_string method:
from django.template.loader import render_to_string
content = render_to_string(template_name, dictionary, context_instance)
You'll either need to resolve the request object from the context, or hand it in as an argument to your template tag if you need to leverage the context_instance.
Followup Answer: Inclusion tag example
Django expects template tags to live in a folder called 'templatetags' that is in an app module that is in your installed apps...
/my_project/
/my_app/
__init__.py
/templatetags/
__init__.py
my_tags.py
#my_tags.py
from django import template
register = template.Library()
#register.inclusion_tag('other_template.html')
def say_hello(takes_context=True):
return {'name' : 'John'}
#other_template.html
{% if request.user.is_anonymous %}
{# Our inclusion tag accepts a context, which gives us access to the request #}
<p>Hello, Guest.</p>
{% else %}
<p>Hello, {{ name }}.</p>
{% endif %}
#main_template.html
{% load my_tags %}
<p>Blah, blah, blah {% say_hello %}</p>
The inclusion tag renders another template, like you need, but without having to call a view function. Hope that gets you going. The docs on inclusion tags are at: https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#inclusion-tags
Using your example and your answer to Brandon's response, this should work for you then:
template.html
{% block content %}
Hey {{stuff}} {{stuff2}}!
{{ other_content }}
{% endblock content %}
views.py
from django.http import HttpResponse
from django.template import Context, loader
from django.template.loader import render_to_string
def somepage(request):
other_content = render_to_string("templates/template1.html", {"name":"John Doe"})
t = loader.get_template('templates/template.html')
c = Context({
'stuff': 'you',
'stuff2': 'the rocksteady crew',
'other_content': other_content,
})
return HttpResponse(t.render(c))
Someone created a template tag that loads a view. I've tried it, and it works. The advantage of using that template tag is that you don't have to rewrite your existing views.

Categories

Resources