Login

Most bookmarked snippets

Snippet List

Lazily lookup dynamically for templates

If you've ever wanted to dynamically lookup values in the template layer (e.g. `dictionary[bar]`), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data. These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example: from lazy_lookup import lazy_lookup_dict def some_view(request): users = User.objects.values('id', 'username') articles = Article.objects.values('user', 'title', 'body') articles = dict([(x['user'], x) for x in articles]) return render_to_response('some_template.html', {'data': lazy_lookup_dict(users, key=lambda x: x['id'], article=articles, item_name='user')}) Then in the template layer you'd write something like: {% for user_data in data %} {{ user_data.user.username }}, {{ user_data.article.title }} {% endfor %}

  • template
  • dynamic
  • lookup
  • lazy
  • dynamic-lookup
Read More

FixedEmailMessage

Django EmailMessage class has no cc support and has bug in bcc support. Core developers won't add cc support (see ticket http://code.djangoproject.com/ticket/5790), and I don't want to wait half a year until they will realize they have a flaw that bcc recipients are sent to regular "to:" recipients and fix it. So, if you want to use EmailMessage class right now, you'd better use FixedEmailMessage class. Class contract is the same, except for a new cc constructor argument.

  • email
  • smtp
  • mail
  • message
  • emailmessage
  • cc
Read More

check if form has changed (deprecated)

This is deprecated. I don't use it anymore, since forms now have the attribute "has_changed". The method form_changed() returns a boolean value. It is True if the submitted values of the bound and valid form are different than the initial values. It works for me. Feedback welcome. Set debug=True if you want to know what's going on.

  • deprecated
Read More

XFN Form Field

**This is a newforms field for XFN relationships.** It normalizes input by removing excess whitespace, converting to lowercase and removing duplicates. This field also validates the relationship according to the [XFN profile](http://gmpg.org/xfn/11): `me` can only appear by itself and, at most, one value from each of the family, friendship and geographical categories is allowed. The `XFN_*` constants would probably be imported from somewhere else in practice, but are included here for simplicity.

  • newforms
  • fields
  • forms
  • form
  • field
  • xfn
Read More

Convert Unicode to ASCII

Unicode is great, but there are places where the conversion ends up with unintelligible characters. I first noticed this with curly quotes entered in forms on our site. `unicode_to_ascii` converts compound characters to close approximations in ASCII: such as umlaut-u to u, 1/2 (fraction glyph) to 1/2. You can add additional mappings in CHAR_REPLACEMENTS.

  • unicode
  • ascii
  • convert
Read More

packjs templatetag

Based on jspacker by Dean Edwards, Python port by Florian Schulze: http://www.crowproductions.de/repos/main/public/packer/jspacker.py Packs javascript Example usage:: {% packjs %} var a = 1; var b = 2; var c = 3; alert(a+b); {% endpackjs %} This example would return this script:: eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[c]=k[c]||c;k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp("\\b"+e(c)+"\\b","g"),k[c]);return p}('0 5 = 1;\n 0 4 = 2;\n 0 7 = 3;\n 6(5+4);\n',8,8,'var||||b|a|alert|c'.split('|'),0,{}))

  • templatetag
  • javascript
  • pack
Read More

prevent GET or POST requests

This will return HTTP 405 if request was not POSTed. same way you can forbide POST request, change 'POST' to 'GET' Decorators provided for your convenience.

  • view
  • request
  • post
Read More

SeparatedValuesField

A Django newforms field which takes another newforms field during initialization and validates every item in a comma-separated list with this field class. Please use it like this: from django.newforms import EmailField emails = CommaSeparatedValuesField(EmailField) You would be able to enter a string like "[email protected],[email protected]" because every email address would be validated when clean() is executed. This of course also applies to any other Field class. You can define the sepator (default: ",") during initialization with the `separator` parameter like this: from django.newforms import EmailField` emails = SeparatedValuesField(EmailField, separator="###")

  • newforms
  • field
  • comma
  • separated
Read More

ManyToMany field with newforms

In editing a ManyToMany field in a form, it is necessary to clear the entries in the bridge table before adding new entries. So first save the new entries, remove the old entries in the multiple choice field and then add the new entries. It is also necessary to add the commit_on_success decorator to make sure that the whole process is in one transaction.

  • newforms
  • multiplechoicefield
  • manytomany
Read More

Another means of updating a subset of a model's fields

Based on the UPDATE query section of `Model.save()`, this is another means of limiting the fields which are used in an UPDATE statement and bypassing the check for object existence which is made when you use `Model.save()`. Just make whatever changes you want to your model instance and call `update`, passing your instance and the names of any fields to be updated. Usage example: import datetime from forum.models import Topic from forum.utils.models import update topic = Topic.objects.get(pk=1) topic.post_count += 1 topic.last_post_at = datetime.datetime.now() update(topic, 'post_count', 'last_post_at') (Originally intended as a comment on [Snippet 479](/snippets/479/), but comments aren't working for me)

  • model
  • db
  • update
Read More

Cloud Tag template example

This is the example of a Django Template that makes use of the clouds example given in the link. It uses the simple CSS selector font-style which can be expressed as per centage. Check the code in http://www.djangosnippets.org/snippets/473/

  • tag
  • template-tag
  • tagging
  • clouds
  • cloud
Read More

render_to_json

**Explanation:** I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime. **Setup:** Saves the snippet as `myproject/utils.py` or add the code to some place in your project with same ends. **Use in a view:** from myproject.utils import render_to_json from django.contrib.admin.models import User def json_view(request): admin_user = User.objects.get(username='admin') return render_to_json( 'json/example.json', locals(), ) **Update:** This code can be used as complement to [http://www.djangosnippets.org/snippets/154/](JsonResponse snippet) too.

  • template
  • json
Read More

Per-site vary cache on language

I like the per-site caching offered by Django (it's simple) and I like the cache to be dependent on the chosen language. Unfortunately with the current `CacheMiddleware` you can either have the one or the other but not both at the same time. `VaryOnLangCacheMiddleware` is a small wrapper around `CacheMiddleware`. It looks at the `request.LANGUAGE_CODE` (set by `LocaleMiddleware`) and appends it to your `CACHE_MIDDLEWARE_KEY_PREFIX`. So "mysiteprefix" becomes "mysiteprefix_en" or "mysiteprefix_de-AT" depending on the user's chosen language. Site-wide, so no messing with per-view decorators and stuff. To use this, make sure `VaryOnLangCacheMiddleware` comes below `LocaleMiddleware` in your settings.py. If you haven't set your `CACHE_MIDDLEWARE_KEY_PREFIX`, it's works, too. **Update:** Replaced `super()` calls with `CacheMiddleware.xxx(self, ...)`.

  • middleware
  • i18n
  • cache
  • language
Read More

Redirect Multiple Domains to a Single Domain

Often, you may register more than one domain name for your website, which may have a primary domain of *mysite.com.au*: 1. mysite.com 2. my-site.com 3. mysite.net 4. mysite.co.uk For SEO and brand awareness reasons, (remember: every page should have exactly one URL) you want every visitor to end up on your primary domain, *mysite.com.au*. This middleware checks the HTTP_HOST for all incoming requests, and sends the user to http://www.mysite.com.au/ if they've managed to hit another domain.

  • middleware
  • redirect
  • domains
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

3110 snippets posted so far.