Django custom filter instance

Source: Internet
Author: User
Django custom filter instance requirement: use a key to take values from the dictionary, for example, test [key] = value

Views. py

From django. template import RequestContextfrom django. shortcuts import render_to_responsedef view (request) dicts = {"key1": 1, "key2": 2, "key3": 3,} return render_to_response ("index.html ", {"dicts": dicts,}, context_instance = RequestContext (request ))

1. create templatetags in the app directory/create an empty file _ init _. py and myfilter. py in this directory

2. edit in myfilter. py

From django import templateregister = template. library () def key (d, key_name): value = 0 try: value = d [key_name] doesn t KeyError: value = 0 return valueregister. filter ('key', key)

3. use in the template

{% Load myfilter %} # load custom tags {dicts | key: "key1 "}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.