Login

Most bookmarked snippets

Snippet List

ActiveManager: filter objects depending on publication and/or expiration dates

This manager is intended for use with models with publication and/or expiration dates. Objects will be retrieved only if their publication and/or expiration dates are within the current date. Use is very simple: class ExampleModel(models.Model): publish_date = models.DateTimeField() expire_date = models.DateTimeField(blank=True, null=True) objects = models.Manager() actives = ActiveManager(from_date='publish_date', to_date='expire_date') ExampleModel.actives.all() # retrieve active objects according to the current date The manager works correctly with nullable date fields. A null publication date means "*always published (until expiration date)*" and a null expiration date means "*never expires*". Most models should define the `objects` manager as the default manager, because otherwise out of date objects won't appear in the admin app.

  • model
  • manager
  • active
  • publication
  • expiration
  • date-filter
Read More

WithTag Tag

Set a context variable with the returned value by any templatetag. Useful for example in order to use url templatetag inside blocktrans: ` {% withtag url my_app.views.my_view as my_view_url %}` ` {% blocktrans %}` ` Click <a href="{{ my_view_url }}">here</a>` ` {% endblocktrans %}` ` {% endwithtab %}` Or with include templatetag: ` {% withtag include "js_template.js" as js_template %}` ` {{ js_template }}` ` {% endwithtab %}` It works properly with your own custom templatetags.

  • templatetag
  • with
  • withtag
  • with_tag
Read More

Create breakpoints to time code at

Include in your code like this: t=Timer() Then use it like this: t.tick('Some optional description') It will output the time spent between the tick and the previous tick (or inception) and the total time spent since it began tracking time. Can be placed multiple times in a long segment of code. Can be used to break out the amount of time being spent on various parts of your code so you can focus on optimizing those sections.

  • time
  • high-performance
  • profiling
  • timer
  • optimize
Read More

Mail logged errors to administrators

Activate this middleware and define `LOG_FORMAT` & `LOG_ROOTS` in your `settings.py`. Then you can use Python's `logging` module for easy logging within your application.

  • middleware
  • email
  • logging
Read More

Automate unique slug (again)

This takes the "easier to ask forgiveness than permission" approach to making sure your model's slug is unique. If the model's slug is empty, make a slug from the model's 'name' field. We assume that it is a conflicting slug that is throwing the IntegrityError, in which case if the slug does not end with '-' followed by a number then append '-2'. If the slug does end with '-' followed by a number then capture that final number, increment it by one, save the new slug value and try savin g again.

  • slug
  • save
Read More

Callable Class View

Instead of using a function for your views, this allows you to use a class. For your urls definition it works just as it normally does.

  • view
  • callable
  • response
Read More

Nested set abstraction for hierarchical data

The nested set abstraction is a very nice way to store hierarchical data, for example places, in a database. It provides an easy way to say that Melbourne is within Victoria, which is within Australia, etc.</p> The calls to addChild() are expensive, so this model is slow to build, and bad if you do frequent updates. If you're building a read-only model though, it's much faster than ForeignKey('self') for determining ancestor/descendent relationships.

  • tree
  • hierarchy
  • nested-set
Read More

Variable inspect filter

This module has two template filters allowing you to dump any template variable. Special handling for object instances. Pretty output. Usage: {% load dumper %} ... <pre>{{ var|rawdump }}</pre> or {% load dumper %} ... {{ var2|dump }} How to install: As usual, put into `<your-proj>/<any-app>/templatetags/dumper.py`.

  • template
  • filter
  • dump
  • variable
  • inspect
Read More

get_queryset_or_404

Sometimes we want to get a queryset or 404, for example, if we're passing our queryset to a subclassed generic view. This is identical to get_list_or_404 but returns a queryset.

  • shortcut
  • template
  • queryset
  • get_queryset_or_404
  • get_list_or_404
Read More

Template Filter attr

You can add this code to a file named "field_attrs.py" in a templatetags folder inside an application. To use it, remember to load the file with the following template tag: {% load field_attrs %} And for each field you want to change the widget's attr: {{ form.phone|attr:"style=width:143px;background-color:yellow"|attr:"size=30" }}

  • template
  • filter
  • newforms
  • forms
  • form
  • field
  • attr
Read More

Character encoding fix

There is a commonly encountered problem with Django and character sets. Windows applications such as Word/Outlook add characters that are not valid ISO-8859-1 and this results in problems saving a Django model to a database with a Latin 1 encoding. These characters should also be converted to avoid any display issues for the end users even if you are using a UTF-8 database encoding. The topic is well covered at [Effbot](http://effbot.org/zone/unicode-gremlins.htm) and contains a list of appropriate conversions for each of hte problem characters. Correcting this for all of your Django models is another issue. Do you handle the re-encoding during the form validation? The save for each model? Create a base class that all your models need to inherit from? The simplest solution I have created leverages [Signals](http://code.djangoproject.com/wiki/Signals) Combining the re-encoding method suggested at Effbot and the pre_save signal gives you the ability to convert all the problem characters right before the save occurs for any model. **kill_gremlins method replaced with Gabor's suggestion**

  • django
  • python
  • unicode
  • latin1
  • character
  • encoding
Read More

A dict template tag

When you need to include a specific javascript file/code snippet in your page, it's always better to do it at the bottom of your page to avoid to block the rendering too soon. This tag provide you a nice way to include and launch only what is needed: Example in an included template that need to display google maps: {% dict js_file google_api %} <script src="http://www.google.com/jsapi?key={{ MAPS_API_KEY }}" type="text/javascript" charset="utf-8"></script> <script src="{{MEDIA_URL}}js/map.display.js" type="text/javascript">...</script> {% enddict %} {% dict js_code link_map %} $('.show-map').click(function() { ... }); $('.hide-map').click(function() { ... }); {% enddict %} Finaly you just have to add this to the very bottom of your base.html file: .... </body> {% for k,v in js_file.items %} {{v}} {% endfor %} <script type="text/javascript"> /* <![CDATA[ */ {% for k,v in js_code.items %} {{v}} {% endfor %} /* ]]> */ </script> </html>

  • template
  • javascript
  • dict
  • stack
Read More

Control FCGI processes through management

Add fcgi to settings.INSTALLED_APPS then you can start and stop FCGI through manage.py >python manage.py startfcgi >python manage.py stopfcgi In settings define runfcgi arguments using **FCGI_*** in settings For example: >FCGI_SOCKET='/var/tmp/project.sock' >FCGI_PIDFILE='/var/run/project.pid' One of **FCGI_SOCKET** or **FCGI_HOST**/**FCGI_PORT** will need to be defined, but if you forget they will error out. **FCGI_PIDFILE** is required to be defined to allow the process to be terminated.

  • management
  • fcgi
Read More

Restrict Flatpage To Group

Simple little flatpage wrapper view that lets you easily block off certain areas of flatpages to only a certain user group. Allows superuser in as well.

  • flatpages
  • groups
  • restricted
Read More

3110 snippets posted so far.