Login

Top-rated snippets

Snippet List

Model inheritance with content type and inheritance-aware manager

inspired by crucialfelix's [inheritance hack](http://www.djangosnippets.org/snippets/1031/), which was a far better method of fetching a model's subclassed version from an instance than my own, i decided to bake his snippet in to my own inheritance hack, which i think benefits both. the result is a query set that returns subclassed instances per default. So - in the snippet's example, querying `Meal.objects.all()[0]` will return a salad object, if that instance of Meal happens to be the parent of a Salad instance. To my mind this is closer to the 'intuitive' way for a query set on an inheriting model to behave. **Updated:** added subclassing behaviour for the iterator access as well. **Updated:** incorporated carljm's feedback on inheritance

  • manager
  • inheritance
Read More

Switch template tag

The `{% switch %}` tag compares a variable against one or more values in `{% case %}` tags, and outputs the contents of the matching block. An optional `{% else %}` tag sets off the default output if no matches could be found: {% switch result_count %} {% case 0 %} There are no search results. {% case 1 %} There is one search result. {% else %} Jackpot! Your search found {{ result_count }} results. {% endswitch %} Each `{% case %}` tag can take multiple values to compare the variable against: {% switch username %} {% case "Jim" "Bob" "Joe" %} Me old mate {{ username }}! How ya doin? {% else %} Hello {{ username }} {% endswitch %}

  • tag
  • templatetag
  • switch
Read More

Create variables within templates

Here is a Django template tag that allows you to create complex variables specified in JSON format within a template. It enables you to do stuff like: {% var as person %} { "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 }, "phoneNumbers": [ "212 555-1234", "646 555-4567" ] } {% endvar %} <p>{{person.firstName}}, </br> {{person.address.postalCode}}, </br> {{person.phoneNumbers.1}} </p> This tag also enables me to do dynamic CSS using as follows: # urlpatters urlpatterns = patterns('', (r'^css/(?P<path>.*\.css)$', 'get_css'), ) #views def get_css(request, path): return render_to_response('css/%s' % path, {}, mimetype="text/css; charset=utf-8") # dynamic css within in /path/to/app/templates/css' {% load var %} {% var as col %} { "darkbg": "#999", "lightbg": "#666" } {% endvar %} {% var as dim %} { "thinmargin": "2em", "thickmargin": "10em" } {% endvar %} body { background: {{col.darkbg}}; margin: {{dim.thinmargin}}; }

  • tag
  • json
  • css
  • variables
  • var
Read More

Upload progress handler using cache framework

Ticket [#2070](http://code.djangoproject.com/ticket/2070) allows you to create your own file upload handlers. Here's an example handler that tracks a file's upload so you might display a progress meter after form submission. The snippet has two parts, the upload handler which tracks progress, and an upload_progress view used to report back to the browser. The upload handler uses [django's cache framework](http://www.djangoproject.com/documentation/cache/#the-low-level-cache-api) to store the data, which can then be retrieved by the view to send back to the browser. Note: Your form's http post request must have a query parameter (X-Progress-ID) sent along with it, which should contain a unique key to identify the upload. That key will also be sent with your ajax requests to the upload_progress view to retrieve the progress data. Setup: place the UploadProgressCachedHandler anywhere you like on the python path, and add to your settings.py: from django.conf import global_settings FILE_UPLOAD_HANDLERS = ('path.to.UploadProgressCachedHandler', ) + \ global_settings.FILE_UPLOAD_HANDLERS Set up the upload_progress view in any of your apps along with a corresponding entry in your urlconf. Here's some javascript example code to make the ajax requests and display the progress meter: <http://www.djangosnippets.org/snippets/679/> .

  • ajax
  • upload
  • progress
Read More

MultiFileWidget

This is a multi file upload widget. That does not require adding multiple file input fields. It requires jQuery.MultiUpload (http://www.fyneworks.com/jquery/multiple-file-upload/)

  • newforms
  • upload
  • multi-file-upload
  • file
Read More

Create new variables in templates

Sometimes you want to create a temporal variable to store something or do anything you want with it, problem is that django template system doesn't provide this kind of feature. This template tag is just for that. Syntax:: {% assign [name] [value] %} This will create a context variable named [name] with a value of [value] [name] can be any identifier and [value] can be anything. If [value] is a callable, it will be called first and the returning result will be assigned to [name]. [value] can even be filtered. Example:: {% assign count 0 %} {% assign str "an string" %} {% assign number 10 %} {% assign list entry.get_related %} {% assign other_str "another"|capfirst %} {% ifequal count 0 %} ... {% endifequal %} {% ifequal str "an string" %} ... {% endifequal %} {% if list %} {% for item in list %} ... {% endfor %} {% endif %}

  • template
  • variable
  • assign
Read More

User post_save signal to auto create 'admin' profile

**How to use:** 1. puts this code at the end of the `models.py` file who haves the User Profile class declared; 2. verify if your User Profile class has the name 'UserProfile'. If not, change the code to the right name. **About:** this snippet makes the ORM create a profile each time an user is created (or updated, if the user profile lost), including 'admin' user.

  • admin
  • user
  • userprofile
Read More

RestfulView

In the same vein as [snippet 436](http://www.djangosnippets.org/snippets/436/), this allows you to differentiate view logic by HTTP method such as GET, POST, PUT, DELETE. This is also very useful combined with the [HttpMethodsMiddleware snippet](http://www.djangosnippets.org/snippets/174/). I am not the author, but I have found it to be very helpful.

  • rest
  • http
  • urlconf
Read More

Include captchas from recaptcha.net

Recaptcha is a free service that helps you protect your forms against spam bots by displaying a picture showing 2 words or playing an audio file telling 8 digits for the visually handicapped. After registration on http://recaptcha.net a private and a public key are generated. Put the keys in settings.py. Find client code for recaptcha at http://pypi.python.org/pypi/recaptcha-client. Put the file captcha.py into application root.

  • captcha
  • recaptcha
Read More
Author: b23
  • 8
  • 29

Logging Middleware

This is a simple Logging Middleware that uses the python logging functions. Simply drop this snippet in a file in your project such as `logmw.py` (don't try to call it `logging.py` though), then add the class to MIDDLEWARE_CLASSES in your settings file. (for instance, `'mysite.logmw.LoggingMiddleware'`) Updated 8/25/08: added PhonyLogger class that swallows log messages when logging is disabled, so code doesn't have to care if it's on or not (thanks to goodness for suggesting the idea, though I missed it before)

  • middleware
  • logging
Read More

Basic logic filters

Usage: {% if item|IN:list %} The item is in the list. {% endif %} {% if customer.age|LE:18 %} Go play out here. {% endif %} {% if product.price|add:delivery_cost|GT:balance %} Insufficient funds. {% endif %} You've got the idea. Special thanks to [guychi](http://www.djangosnippets.org/snippets/379/).

  • template
  • filter
  • logic
Read More

simple string formatting filter

I use this filter quite a bit to keep my templates less cluttered. Instead of: {%if some_variable%}, {{some_variable}}{%endif%} I can write: {{some_variable|format:", %s"}} A common one I use is: {{some_variable|format:"<p>%s</p>"}}

  • filter
  • format
  • stringformat
Read More

Datetime widget

This widget uses: [DHTML Calendar Widget](http://www.dynarch.com/projects/calendar/). It is very simple implementation but may be easily extended/changed/refined. 1. Necessary files: First download calendar package and extract it to your MEDIA folder (MEDIA/calendar/...) You'll also need a small gif that will be shown as a button that allows user to display calendar. By default this 'gif' is searched at '[MEDIA]images/calbutton.gif' but you may change this path in the code (calbtn variable). You need to download or create callbutton.gif image by yourself (it is not included). 2. Include css and js files in your page (as shown in the comment in the code). 3. In form code assign a widget to a field as usual (see newforms documentation for more details). 4. It is possible to change date format by specifying different value for 'dformat' attribute of widget class. If you get javascript errors while trying to open calendar try to use english translation file (calendar-en.js). I've found that some translations, eg. Polish, are broken by default. In this case you should override your language translation with english one and translate it by yourself (it is easy).

  • datetime
  • date
  • calendar
  • widget
  • dhtml
Read More

JSONField

This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript. **Example** (models.py): from django.db import models from jsonfield import JSONField class Sequence(models.Model): name = models.CharField(maxlength=25) list = JSONField() **Example** (shell): fib = Sequence(name='Fibonacci') fib.list = [0, 1, 1, 2, 3, 5, 8] fib.save() fib = Sequence.objects.get(name='Fibonacci') fib.list.append(13) print fib.list [0, 1, 1, 2, 3, 5, 8, 13] fib.get_list_json() "[0, 1, 1, 2, 3, 5, 8, 13]" *Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.

  • models
  • model
  • json
  • db
  • field
  • json-field
Read More

Support for {% macro %} tags in templates, version 2

Tag library that provides support for *macros* in Django templates. **Usage example:** **0)** Save this file as <yourapp>/templatetags/macros.py **1)** In your template load the library: {% load macros %} **2)** Define a new macro called 'my_macro' with parameter 'arg1': {% macro my_macro arg1 %} Parameter: {{ arg1 }} {% endmacro %}` **3a)** Use the macro with a String parameter: {% usemacro my_macro "String parameter" %} **3b)** or with a variable parameter (provided the context defines 'somearg' variable, e.g. with value "Variable parameter"): {% usemacro my_macro somearg %} **3c)** **!!NEW!!** `usemacro` now also supports filters attached to parameters: {% usemacro my_macro "lowercase parameter"|upper %} Output of the above code would be: Parameter: String parameter Parameter: Variable parameter Parameter: LOWERCASE PARAMETER **4)** **!!NEW!!** Alternatively save your macros in a separate file, e.g. "mymacros.html" and load it into the current template with: {% loadmacros "mymacros.html" %} Macros can take *zero or more arguments* and both context variables and macro arguments are resolved in macro body when used in `{% usemacro ... %}` tag. Bear in mind that Macros are local to each template file and are not inherited through `{% extends ... %}` blocks.

  • template
  • tag
  • macro
  • usemacro
  • loadmacros
Read More

3110 snippets posted so far.