Login

Tag "template"

Snippet List

TemplateTag to call a method / function WITH arguments

**Callmethod** - TemplateTag to call a method on an object with arguments from within a template {% callmethod hotel.room_price_for_night night_date="2018-01-02" room_type=room_type_context_var %} ## equals ## >>> hotel.room_price_for_night(night_date="2018-01-02", room_type="standard") #Assuming "standard" is the value of room_type_context_var Django doesn't allow calling a method with arguments in the template to ensure good separation of design and code logic. However, sometimes you will be in situations where it is more maintainable to pass an argument to a method in the template than build an iterable (with the values already resolved) in a view. Furthermore, Django doesn't strictly follow its own ideology: the {% url "url:scheme" arg, kwarg=var %} templatetag readily accepts variables as parameters!! This template tag allows you to call a method on an object, with the specified arguments. Usage: {% callmethod object_var.method_name "arg1_is_a_string" arg2_is_a_var kwarg1="a string" kwarg2=another_contect_variable %} e.g. {% callmethod hotel.room_price_for_night date="2018-01-02" room_type="standard" %} {% callmethod hotel.get_booking_tsandcs "standard" %} NB: If for whatever reason you've ended up with a template context variable with the same name as the method you want to call on your object, you will need to force the template tag to regard that method as a string by putting it in quotes: {# Ensure we call hotel.room_price_for_night() even though there's a template var called {{ room_price_for_night }}! #} {% callmethod hotel."room_price_for_night" date="2018-01-02" room_type="standard" %} * **@author:** Dr Michael J T Brooks * **@version:** 2018-01-05 * **@copyright:** Onley Group 2018 (Onley Technical Consulting Ltd) [http://www.onleygroup.com](http://www.onleygroup.com) * **@license:** MIT (use as you wish, AS IS, no warranty on performance, no liability for losses, please retain the notice) * **@write_code_GET_PAID:** Want to work from home as a Django developer? Earn £30-£50 per hour ($40-$70) depending on experience for helping Onley Group develop its clients' Django-based web apps. E-mail your CV and some sample portfolio code to: [email protected] Copyright 2018 Onley Group Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice, credits, and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  • template
  • tag
  • templatetag
  • function
  • template-tag
  • args
  • kwargs
  • methods
  • argument
  • template-arguments
Read More

Relative paths for Django template tags 'extends' and 'include'.

[The problem](http://stackoverflow.com/questions/671369/django-specifying-a-base-template-by-directory): {% extends "./../base.html" %} won't work with extends. It causes a lot of inconvenience, if you have an extensive hierarchy of django templates. This library allows relative paths in argument of 'extends' and 'include' template tags. Relative path must start from "./" Just write in your templates as follows: ``` {% load relative_path %} {% extends "./base.html" %} ``` this will extend template "base.html", located in the same folder, where your template placed ``` {% load relative_path %} {% extends "./../../base.html" %} ``` extend template "base.html", located at two levels higher same things works with 'include' tag. ``` {% load relative_path %} {% include "./base.html" %} ``` include base.html, located near of your template. **Warning!** The rule 'extends tag must be first tag into template' is disabled by this library. Write your template with caution. **Compatibility** Code was tested with Django versions from 1.4 to 1.9 Installation. ------------- Installation is differs for Django version 1.9 and previous versions, because 1.9 brings many changes into template's mechanizm. **Django 1.9** Plug reference to library code in 'TEMPLATES' key of settings.py or django.settings.configure() ``` TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(ROOT_PROJECT, 'tpl').replace('\\', '/')], 'OPTIONS': { 'loaders': [ 'dotted_path_to_relative_path_file.FileSystem19', 'dotted_path_to_relative_path_file.AppDirectories19', ], 'libraries': { 'relative_path': 'dotted_path_to_relative_path_file', }, }, }] ``` **Django 1.4/1.8** Put 'relative_path.py' file to the 'templatetags' folders of your app. (app must be included into INSTALLED_APPS tuple) In settings.py or django.settings.configure(), replace standard django template loaders by loaders from this library ``` TEMPLATE_LOADERS = ( 'dotted_path_to_relative_path_file.FileSystem', 'dotted_path_to_relative_path_file.AppDirectories', ) ```

  • template
  • extends
  • custom-tag
  • include
  • relative-path
Read More

Reusable form template with generic view

If you require lots of forms in your project and do not want to be creating an extended template for each one I propose this solution. Classes in the html correspond to bootstrap, you can work without them if you do not use bootstrap.

  • template
  • django
  • dynamic
  • fields
  • forms
  • generic
  • generic-views
  • html
  • form
  • bootstrap
  • reusable
  • custom
  • modelform
  • crud
  • dynamic-form
Read More

Datetime adjuster for Django Templates

The filter is **specific to datetime objects** and no allowance has been made to convert strings or epoch times. Also **no type checking** is performed so misuse will result in an error. To use include the above snippet in a file called templatetags/customfilters.py or append to existing filters file then load: `{% load customfilters %}` in your template, then to use it: `{{ dateobject|adjust:"months=1"|date:"Y/m/d" }}` To push the dateobject forward by a month, or: `{{ dateobject|adjust:"weeks=-1"|date:"Y/m/d" }}` To push the dateobject back a week, or: `{{ dateobject|adjust:"years=1, months=2"|date:"Y/m/d" }}` To push the dateobject forward by a year and 2 months

  • template
  • filter
  • datetime
  • calculation
  • adjust
  • relativedelta
Read More

Load template from specific app

It's an update of snippet [https://djangosnippets.org/snippets/1376/](https://djangosnippets.org/snippets/1376/) to work with Django 1.8. With this piece of code, you can override admin templates without copy or symlink files. Just write your template and extend the target.

  • template
  • loader
  • app
Read More

Cancel URL Mixin

**CancelMixin** A simple mixin to use with ```generic.CreateView``` and ```generic.UpdateView``` view form templates to effortlessly implement a "Cancel" button. This smart mixin will add a URL to your context, ```{{ cancel_url }}```, that can be used as a cancel link in your form template. If no referrer URL is provided, the cancel button will link to ```default_cancel_url```, which can be overridden by view. ** **

  • template
  • django
  • mixin
  • update
  • create
  • cbv
Read More

get_querystring template tag

A Django Template tag used to construct urls with current querystring parameters. This is based on some code that I've written some years ago. Enjoy.

  • template
  • templatetag
  • querystring
Read More

django form template with bootstrap

## required * `{% load trans%}`before using this snippets * Add this [template filter](https://djangosnippets.org/snippets/2253/) to your custom templatetags and load it before using this snippets * Bootstrap framework

  • template
  • form
Read More

Display values from a bound (submitted) form

Function that takes a bound form (submitted form) and returns a list of pairs of field label and user chosen value. It takes care of: 1. fields that are not filled out 2. if you want to exclude some fields from the final list 3. ChoiceField (select or radio button) 4. MultipleChoiceField (multi-select or checkboxes) Usage: if form.is_valid(): form_data = get_form_display_data(form, exclude=['captcha']) It's trivial to display the list of pairs in a template: {% for key, value in form_data %} {{ key }}: {{ value }}{% endfor %}

  • template
  • email
  • form
Read More

262 snippets posted so far.