Login

Tag "function"

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

Send templated email with text | html | optional files

Use this to send emails to your users, takes one template and renders it as html or text as needed. Credits to """ Jutda Helpdesk - A Django powered ticket tracker for small enterprise. (c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details. lib.py - Common functions (eg multipart e-mail) """ MIT licence I only removed the specific project parts and made it general to use. The original project repository https://github.com/rossp/django-helpdesk/

  • template
  • email
  • function
Read More

Wrapper-function Pattern

This is an example how to create a wrapping function that can read all incoming arguments, do something with them and then call the original function. This pattern works well with generic views. Note that wrapper function accepts arguments in both ways: as a list of unnamed arguments and as a list of keyword-value pairs. A real-world example: def published_object_list(request, *args, **kwargs): arg_names = object_list.func_code.co_varnames params = dict(zip(arg_names, args)) params.update(kwargs) params['queryset'] = params['queryset'].filter(is_published=True) if request.is_ajax(): params['template_name'] = "ajax/" + params['template_name'] return object_list(request, **params)

  • view
  • function
  • wrapper
Read More

MySQL django password function

This functions encodes a password in the same format as django. You can set the auth_user.password column with the result of this function: update `auth_user`.`password` set `password` = django_password('secret') where id = 1234;

  • function
  • password
  • mysq
  • sha
Read More

function_tag

register any python function as a tag with an optional name. usage: in templatetags: @function_tag() def foo(arg): return do_something(arg) in template: {% foo arg %} or {% foo arg as variable %}{{ variable.bar }}

  • tag
  • function
Read More

Functional Filters

I've been working on a project where I realized that I wanted to call methods on Python objects *with arguments* from within a Django template. As a silly example, let's say your application maintains users and "permissions" that have been granted to them. Say that permissions are open-ended, and new ones are getting defined on a regular basis. Your `User` class has a `check_permission(p)` method that return `True` if the user has been granted the permission `p`. You want to present all the users in a table, with one row per user. You want to each permission to be presented as a column in the table. A checkmark will appear in cells where a user has been granted a particular permission. Normally, in order to achieve this, you'd need to cons up some sort of list-of-dicts structure in Python and pass that as a context argument. Ugh! Here's how you'd use the `method`, `with`, and `call` filters to invoke the `check_permission` method from within your template. (Assume that you've provided `users` and `permissions` as context variables, with a list of user and permission objects, respectively.) <table> <tr> <th></th> {% for p in permissions %} <th>{{ p.name }}</th> {% endfor %} </tr> {% for u in users %} <tr> <td>{{ u.name }}</td> {% for p in permissions %} <td> {% if user|method:"check_permission"|with:p|call" %}X{% endif %} </td> {% endfor %} </tr> {% endfor %} </table> The `call_with` method is a shortcut for single-argument invocation; for example, we could have re-written the above as {% if user|method:"check_permission"|call_with:p %}...{% endif %} Anyway, this has been useful for me. Hope it's helpful for others! --chris P.S., tip o' the cap to Terry Weissman for helping me polish the rough edges!

  • filter
  • filters
  • function
  • object
  • method
Read More

Function/Stored Procedure Manager

Ever want to call stored procedures from Django easily? How about PostgreSQL functions? That's that this manager attempts to help you with. To use, just stick this in some module and in a model do: class Article(models.Model): objects = ProcedureManager() Now you can call procedures (MySQL or PostgreSQL only) to filter for models like: Article.objects.filter_by_procedure('ProcName', request.user) This will attempt to construct a queryset of objects. To just get random values, do: Article.objects.values_from_procedure('ProcName', request.user) Which will give you a list of dictionaries.

  • function
  • db
  • manager
  • db-api
  • stored-procedure
Read More

Cache Any Function

A decorator similar to `cache_page`, which will cache any function for any amount of time using the Django cache API. I use this to cache API calls to remote services like Flickr in my view, to prevent having to hit their servers on every request. I posted a sample function which uses the [delicious API](http://www.djangosnippets.org/snippets/110/) in the function, also. **Update**: It now also will put in a temporary 'in-process' variable (an instance of `MethodNotFinishedError`) in the cache while the function is processing. This will prevent the cache from calling the method again if it's still processing. This does not affect anything **unless you're using threads**.

  • cache
  • function
  • threading
  • threads
  • thread
Read More

9 snippets posted so far.