Login

All snippets

Snippet List

escapejs block tag

Block tag version of [escapejs](http://www.djangoproject.com/documentation/templates/#escapejs). Handy when using inclusion tags to generate AJAX responses.

  • tag
  • javascript
  • escapejs
Read More

Manager introspecting attached model

[A comment on a recent blog entry of mine](http://www.b-list.org/weblog/2008/feb/25/managers/#c63422) asked about a setup where one model has foreign keys pointing at it from several others, and how to write a manager which could attach to any of those models and query seamlessly on the relation regardless of what it's named. This is a simple example of how to do it: in this case, both `Movie` and `Restaurant` have foreign keys to `Review`, albeit under different names. However, they both use `ReviewedObjectManager` to provide a method for querying objects whose review assigned a certain rating; this works because an instance of `ReviewedObjectManager` "knows" what model it's attached to, and can introspect that model, using [Django's model-introspection API](http://www.b-list.org/weblog/2007/nov/04/working-models/), to find out the correct name to use for the relation, and then use that to perform the query. Using model introspection in this fashion is something of an advanced topic, but is extremely useful for writing flexible, reusable code. **Also**, note that the introspection cannot be done in the manager's `__init__()` method -- at that point, `self.model` is still `None` (it won't be filled in with the correct model until a bit later) -- so it's necessary to come up with some way to defer the introspection. In this case, I'm doing it in a method that's called when the relation name is first needed, and which caches the result in an attribute.

  • managers
  • models
  • introspection
Read More

widget to capture a geographic Point

The class LocationField renders a form field with map (from google maps) and a mark. It allows the user to drag the mark to point at some particular location, whose value (lat, lng) is saved in a hidden field. It requires jquery and google maps.

  • newforms
  • forms
  • gis
  • google
  • field
  • maps
  • widget
Read More

cache_smart template tag

cache_smart template tag is a drop in replacement for default cache tag by Django but with the added bonus to be more resistant against dog-pile/stampeding effect. This snippet uses a extra cache entry to store a stale time so we don't have to pickle/unpickle to store this extra value. If this cache entry returns None, as in expired it will reset the stale timeout 30 seconds in the future so further calls will just return the old value while this request is regenerating the new value. **warning** Don't use both cache template tags!

  • template
  • cache
  • memcached
Read More

Reshape list for table, flatten index in nested loops

Sometimes we want to render items as cells in table with fixed row-count and computable col-count shape and vice versa. It's not difficult to do it with compute odd and even row, col index, but more common way is to use some reshape function. Theare are simple TAG for it: "table", with use reshape function and FILTER "flatindex" wich can use to get flat index in nested loops (may use with table like in this example). Example of usage: `{# List filials must exists in context! #} {% load table %} <table border="0" width="100%"> {% table filials "3x?" %} {% for row in table_obj %} <tr> {% for record in row %} {% if record %} <td class="mf_table_cell" onclick="selcell('filial_{{forloop|flatindex}}')"> <img src="/art/filial.gif" style="margin-bottom: 4px;"/><br/> <span id="filial_{{forloop|flatindex}}" class="mf_table_unselcell">{{ record }}</span> </td> {% else %} <td class="mf_table_cell"> &nbsp; </td> {% endif %} {% endfor %} </tr> {% endfor %} {% endtable %} </table>` /best regards Yosifov Pavel

  • table
  • flatindex
Read More

UserForeignKey

Many models are tightly coupled to the default Django `User` model (`django.contrib.auth.models.User`). Sometimes this user model just doesn't fit everyone's needs. By using `UserForeignKey` it is possible to make the `User` model configurable, encouraging loose coupling. Additionally, this can help to prevent circular imports between `User` and another model. Use it like a standard `ForeignKey`... it accepts all the same arguments. If you want to use a `User` model other than the default, just add `USER_MODEL` to your settings file.... it uses dotted notation (`app_label.model_name`). Example: class BlogPost(models.Model): user = UserForeignKey(related_name="blog_posts") title = models.CharField(...) content = models.TextField(...)

  • foreignkey
  • user
  • auth
Read More

Colorize Filter

I had a need to colorize the nicks for the new DjangoBot Logger. Instead of managing a collection of names and corresponding colors we decided it would be more simple to just "hash" the nickname using a colorize filter. This causes the same nickname to always appear in the same color.

  • filter
  • colorize
Read More

extend tag with cache

By default extend tag don't cache parents template. This is extend tag with patch. Workaround for bug: http://code.djangoproject.com/ticket/6586

  • cache
  • extend
Read More

Search djangosnippets.org

I was tired browsing via tag to find snippets I saw a while ago. So I created a custom search engine with Google. To try it out go to [http://henning.cco-ev.de/django/djangosnippets.html](http://henning.cco-ev.de/django/djangosnippets.html)

  • snippets
  • search
  • google
  • snippet
  • djangosnippets
  • cse
Read More

Boxes as template tags

It's a template tag used to create boxes with nested divs (useful to keep the templates DRY). For example: {% menubox titlevar %} Content here {% endmenubox %} will generate the html with the nested divs div class=box div class=box-outer div class=box-inner Headline Content /div /div /div [more detail on this blog post](http://pedro.valelima.com/blog/2007/sep/26/boxes-template-tags/)

  • template-tag
  • box
Read More

Table Creation Using ORM Standalone

I love the Django templates and ORM, but I prefer to use CherryPy as my web server. So I want to be able to do the equivalent of "python manage.py sql" but without actually needing to have a Django application. So I stick all of my models in a file named "models.py" and then run this script and it prints out all of the CREATE TABLE statements for my database.

  • orm
Read More

Extended Profiling Middleware

Modified version of [Profiling Middleware](http://www.djangosnippets.org/snippets/186/) Prints profile results for method, additionally groups results by files and by modules (for django uses top level modules as groups). Works for Windows. Usage: append ?prof or &prof= to any URL pointing to django application after adding ProfileMiddleware to middlewares in yours settings.py. NOTICE: ProfileMiddleware uses hotshot profiler which is not thread safe.

  • middleware
  • profile
  • hotshot
Read More

Generate newforms-admin admin.py file

This is a utility script that scans a models.py file and automatically outputs the corresponding newforms-admin source code - the code that goes into the admin.py file. The purpose is to simplify the migration to newforms-admin. Here is what it outputs: * an import line that lists only the needed classes from the model. * inline editing classes - inheriting from either `admin.TabularInline` or `admin.StackedInline` * admin options classes containing any original `Admin` class contents (`'fields'` is replaced by `'fieldsets'` and the value of `'classes'` is made into a tuple), plus the following fields whose values are determined automatically: `inlines`, `prepopulated_fields`, `filter_horizontal`, `filter_vertical` and `raw_id_fields` * invokations of `admin.site.register` for the generated admin options classes. Example usage of the script (this will generate the admin.py file for the models.py file in the satchmo.product module): >./new-forms-gen.py satchmo.product > admin.py

  • newforms-admin
Read More
Author: NL
  • 16
  • 21

Specify a manager for the Admin

This example shows how you can easily limit the objects in the admin by specifying which Manager the admin should use. I haven't seen this documented anywhere (perhaps I've missed it), but it's proven extremely useful to me. The example here will limit objects to those that are attached to the current Site, but you can use any Manager you want (for example, a Manager that shows only published Articles). Finally -- not that I'm suggesting this -- but you *could* combine this with the ThreadLocals trick to show only objects that have been created by that user.

  • managers
  • models
  • admin
  • sites
Read More

3110 snippets posted so far.