templates variables in django - django

I'm trying to use template variable to access templates dictionaries
when I do {{ pair_name.8 }} it works
but {% with xx=8 %}{{ pair_name.xx }}{% endwith %} doestnt work, please help

I'm trying to use template variable to access templates dictionaries.
The Django template language is deliberately restricted to prevent subscripting, function calls (with parameters), etc. This is to discourage people from writing business logic in the template.
You can implement a custom template filter to perform a subscript lookup, or work with the Jinja template engine. But probably a more elegant way to do this is to alter the view, and prepare the logic in a more accessible way.
For example if you need the xx-th item, in the view, you perform a mapping with:
def some_view(request):
pair_names = [] # some data
xx = 8
data = [pair_name[xx] for pair_name in pair_names]
context = {'pair_names': data}
return render(request, 'some_template.html', context)
Processing this in the view is not only more elegant, but often more efficient as well, since the template engine often is less efficient in walking through data structures.

#Peace Bytheway - Just my 2 cents- Templates should be as dumb as possible which means try and avoid heavy logic from your template into the view. Ideally, you should also keep the view lightweight. Not much processing. The concept behind the view is to simply delegate. So, separating responsibilities into the right layer is very crucial.

Related

How to call a variable function with parameter in django template?

I want to achieve something like this within a Django template.
{{ variable.function(parameter) }}
Where variable is a variable passed through a context to a template, in this case, an instance of a model.
I have tried different methods, but no one seems to work.
This is not possible in Django templates: they are crippled on purpose in order to prevent template designers from shooting themselves in the foot. The reasoning is that the only logic in templates should be presentation logic and all business logic should be kept in the view. Some people thinks it is fair enough and some think it is a bit condescending (those dumb template designers are not smart enough to use functions and methods safely).
I can think of 3 choices:
use jinja2 instead.
write a custom template filter.
keep all the logic in the view where Django designers think you are supposed to keep it.
I will not explain how to use Jinja2 because it is already explained in the docs and because the example in the question works verbatim if you switch to it instead of native Django templates. This simply works in Jinja2:
{{ variable.function(parameter) }}
Now the template filter solution: first you must follow a code layout convention. The filter itself would be something like this:
# at your_tag_library.py
#register.filter(name='call_with')
def apply_callable(callable, arg):
return callable(arg)
Then in the template you can do:
{% load your_tag_library %}
{{ variable.function|call_with:parameter }}
Of course the last option is the one from Daniel's answer - precompute the value in the view and just display the result in the template:
context['result'] = variable.function(parameter)
And in your template you just need {{ result }}.
There is no way to do this.
You can create another variable and pass it through the context so you could use it.
Like:
context['result'] = variable.function(parameter)
In your view.
And in your template:
{{ result }}

Django's equivalence of ASP.NET UserControl

If anyone here is ASP.NET pro, you might know what I mean by user control. I wish to create a similar one in django instead.
So, my problem is that I have several pages in my website, but I need a search bar to appear in every pages. Since I require the views.py to operate this search bar, I cannot do a simple method of
{% include 'something.html' %}
Therefore, can anyone suggest how can I do it?
There are a couple of ways to accomplish what you're wanting to do:
Context Processors
Template Tags
Context Processors can augment the template context with values, regardless of which template is loaded. They are akin to filters in Rails.
Template Tags, like Context Processors, can accomplish anything you can do in Python, but are implemented at the template level.
If you need something to be present on every template, one of the simplest ways to accomplish this is with an inclusion tag, which can also accept values passed to it. An inclusion tag could be implemented at your highest level template, a.k.a your MasterPage, and as long as you don't put it in a block and override it, it would appear on every page that includes that template in its inheritance chain.
If it's just something you want to include on every page, and it doesn't need to do any processing, you should just be able to place the code you want in the top-most template and have subsequent templates inherit that.
I typically have a "base.html" template that all of my templates inherit from. If I need something to be in every page, I put it there. If it's something I want there by default, but want to be able to augment it in subsequent templates, I will place it into a block. That block will let you include or override its default content.
I know this post is kind of old but I just came across it and found a kind-of-solution that works. I call it kind-of-solution because it is a workaround.
I have a few different sites on which I want to display logging information. This display always looks the same (it has the same html) and has the same database table and model class behind it.
My solution/workaround uses the django filters:
in views.py I put the list of log-entries in the context
context = {'list_log': Log.objects.filter(condition = True) }
template = loader.get_template('my_html_file.html')
return HttpResponse(template.render(context, request))
in my_html_file.html I use a custom filter
{{ list_log|get_log_uc|safe }}
in the filters.py I load another html file with this custom filter
#register.filter
def get_log_uc(list_log):
template = loader.get_template('user_control_log.html')
context = { 'list_log' : log }
return template.render(context)
in user_control_log.html I have the user control equivalent html
{% for log in list_log %}
<p>log.something</p>
{% endfor %

Django tags and filters in Lift?

This is a generalization of my previous question about pluralize filter:
Does lift have an equivalent of Django's tags and filters?
Tags are small piece of predefined code that can be used directly in html template, for example:
{% now "jS F Y H:i" %}
renders the time right now in the given format.
Filters
Filters operate (in html template) on the context variables in the template, for example:
{{ value|capfirst }}
if called on a value "john" will result in "John". Or:
{{ value|length }}
will render the length of the string into the template.
As you can see the filters operate on the context variables that are passed to the template.
Considering tags, you could define those yourself with snippets.
As snippet is basically a callback much as a Django tag is. You don’t get any easier syntax, though, because Lift’s templates are pure XML/Html.
<Lift:Tag.now format="jS F Y H:i" />
And the logic would be defined in
class Tag {
def now: NodeSeq = // ...
}
Filtering is something you generally can’t do in a Lift template because Lift doesn’t allow any variables in a template. The whole concept is thus inapplicable. (You could do XML transforms or or bind magic but that would be a bit too much for a simple value.length.)
No, if you need the length of some value in your Html, you will have to define that inside the snippet and expose it.
If you really can’t live without filters in your template (though I can assure you, it is a good thing to separate all HTML template and code and it works once you are used to it), have a look at Scalate which may be used together with Lift as well.
This kind of logic should be in the render method of a snippet. Display code in pure Scala (rather than in a template language hybrid) is a first-class citizen with respect to testing, IDE's and refactoring tools.
These kinds of transforms don't come built-in, but you can add them with implicits:
class HappyString(s: String) {
def capfirst = ....
}
implicit def toHappyString(s: String) = new HappyString(s)
Then call these in your render method before binding whatever value it is you're generating.

django extends different base templates

I understand we can use "extends variable" in the template to switch between two different extended templates.
e.g.
views:
if something:
base = 'base1.html'
else:
base = 'base2.html'
return render_to_response ('template.html', {'base':base})
template.html:
{% extends base %}
Normally that works fine. However, my problem is that I am using django-registration of which I don't have to write my own view to handle the registration and login process. That also means that I am not able to pass the variable to the template. Though I do have the registration templates under my project directory. (like login.html)
Unfortunately, Django can't do this in the template:
{% if something %}
{% extends 'base1.html' %}
{% else %}
{% extends 'base2.html' %}
{% endif %}
The only way I know that the 'variable base' can be passed down to the auth-login is to write my own views like login, logout,etc. This seems like not fitting the DRY model and fairly error prone going forward.
Is there another way that I can accomplish this? Or any pointers to workaround the problem?
Thanks.
-P
If it's just 2 (or 3) options where that 'something' can be made to a Boolean, then you could use the yesno filter:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#yesno
So:
{% extends something|yesno:"base1.html,base2.html" %}
If you want something a bit more free-form, then you could make use of the extra context / custom context processor option mentioned above, and try something like:
{% extends selected_template|default:"base2.html" %}
where selected template is just the path to whatever base template you like.
To be honest this looks to me like a code smell - I've used django-registration a few times, I work on quite large sites and I never needed to extend a template from another template which is only known at run time.
Anyway, if you really want to pass a custom variable to a template rendered by 3rd party module, and you don't want to hack that module, then you have to use e.g. custom template context processor. Also, django-registration allows extra_context to be passed to its views, maybe that would be enough. You can also try monkey-patching. Or maybe you can try manipulating template folders or template loaders to get what you need.
But all these things are IMHO hacks and you shouldn't use different templates for one view, unless it's a generic view.
I think you should not place differences between the templates into the selection of different base templates. Having different base templates is what violates the DRY principle. Place the common things into a template, ie. registration.html, the differences into other templates that you call via 'include':
{%extends base.html%}
{%if something%}
{%include "type1.html"%}
{%else%}
{%include "type2.hmtl"%}
where the template names are the same as you would use in the view definition.
This probably isn't what you are looking for, but could you just include your conditionals in your base.html?

Filtering models with inheritance in Django

I have two Django model classes that are structured similar to the following:
class Build(models.Model):
project = models.CharField(max_length=100)
...
class CustomBuild(Build):
custom_type = ...
...
I want to select all Builds and CustomBuilds (each CustomBuild has a one-to-one relationship with a Build) from the database with a specific project attribute.
I believe Build.objects.filter(project="myproject") will select the correct objects but many of them will be missing the additional data (such as custom_type) that would be provided by a CustomBuild object. On the other hand, filtering CustomBuild.objects will exclude those objects that are not CustomBuilds.
How can I accomplish this? Thanks.
There are a couple approaches you can take to handling the QuerySets of "mixed models" that you obtain when you perform this kind of query. A lot of it depends on your ultimate goal.
The "simple and dumb" way, which I use a lot, is to manage the results with utility functions. If you plan to process the result of Build.objects.filter(project="myproject") in a template, for example, you could use custom template tags or filters to take special action. Assume in the below code build_objects contains the result of your filter():
{% for build in build_objects %}
{% if build|is_custom_build %}
<p>This is a custom build of custom type {{ build.custom_build.custom_type }}!</p>
{% endif %}
<p>This is a custom build OR a standard build</p>
{% endfor %}
The obvious problem here is if you have numerous subclasses, writing template filters may be impractical or grow tedious. However, in my experience I usually have a half-dozen subclasses at most so this is not always a problem.
You could also write a parameterized filter like so:
{% if build|is_of_buildtype:"custom_build" %}
With the filter code as follows:
def is_of_buildtype_filter(value, arg):
if hasattr(value, arg): return True
else: return False
This filter simply checks for the presence of the argument as an attribute on the build object (passed in as value). The argument string should be the name of the automatically generated OneToOneField that you want to detect, in this case custom_build.
For view code, similar sorts of helper functions would work the same way but are even easier because you don't need to write custom filters or tags.
This approach works in many cases, but there are more complicated scenarios where it might not be practical. Unfortunately, Django cannot natively provide you with a QuerySet that contains subclass instances when you perform operations on the base class (ie. a QuerySet that truly contains "mixed models"). You may require this in situations where processing the results with helper functions is not possible.
I personally avoid these situations entirely, usually by rethinking my model design. But if that's not possible, there are many interesting attempts at solutions, like this Inheritance MixIn. There are also several Django snippets on the subject. Be aware, though, that almost any solution like this will be performance-limited.
You can fetch Build objects with Build.objects.filter() and access the subclass when you need to:
qs = Build.objects.all()
build_obj = qs[4]
custom_build_obj = build_obj.custom_build
custom_build_obj.custom_type = ...