Login

Top-rated snippets

Snippet List

Soft-wrap long lines

This filter naively parses HTML content, and inserts <wbr/> tags in lines with unbroken strings longer than max_line_length characters. It leaves content inside tags alone, so that things like urls are unaltered. XHTML entities are treated as atomic, and whitespace is determined with a regex. It assumes well formed HTML.

  • filter
  • line-break
  • wbr
  • softwrap
Read More

PK->objects in view signature

Let's suppose you have a view that fetches an object and renders a template with it. def show_blog_post(request, post_id): post = Post.objects.get(pk=int(post_id)) return render_to_response("show_post.html", dict(post=post)) That's all well and good. This decorator just lets you move one statement into what is essentially a declaration at the top of the function: "this is a view, that gets passed a primary-key ID, which I want to get the Post object for." @sigtransform([Post, int]) def show_blog_post(request, post): # post is actually the Post instance now! return render_to_response("show_post.html", dict(post=post)) If you want to leave an argument alone, pass None as that positional argument (excluding `request`.) @sigtransform(None, [MyModel, str]): def show_mymodel_stuff(request, leave_me_alone, model_obj): # ...etc... Internally, this just calls get_object_or_404 with the pk kwarg, which means it's not limited to integer keys. However, Model.objects.get requires that the pk arg be of the correct type, hence why the arguments are 2-element lists or tuples: the first is the actual model, the second is what cleaner function to apply to the passed in argument.

  • decorator
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

Middleware to remove the WWW from the URL

Works like the [PREPEND_WWW](http://www.djangoproject.com/documentation/settings/#prepend-www) setting but, instead of adding, it removes the www. Usage: In the settings file add the UrlMiddleware to the middleware list and set REMOVE_WWW = True

  • middleware
Read More

Passing values to a method from a template

A simple trick to let a function be called with exactly ONE argument from a Django template, by passing it via an attribute. Example: class SearchResult(object): @template_callable def highlighted(self, field): return self._xappy_result.highlight(field) result = SearchResult() result.highlighted.title {{ result.highlighted.title }}

  • template
  • templates
  • method
  • call
  • arguments
Read More

Log errors to a file

This is another example use of the [exception middleware](http://www.djangosnippets.org/snippets/638/). It shows how to log exceptions to a file. Someone wanted to do this to avoid DOS-ing the email server in case of a silly error. (untested.)

  • middleware
  • log
  • error
  • exception
  • file
Read More

create_update for newforms (ModelForm)

Based on [danjak's](http://www.djangosnippets.org/users/danjak/) [snippet](http://www.djangosnippets.org/snippets/99/) but updated to use ModelForms - so can easily handle generic CRUD operations. A replacement create_update.py for use with ModelForm create_object and update_project modified to handle newforms (including FileFields) with ModelForm - it also had delete_object as well for completeness. In addition, it has some extras: * extra_fields - this is a dict or callable that contains additional fields to be passed to the form, for example stuff that is in the session. * on_success - callback called if form is valid and object created/updated, if this is not set the default behaviour is to send a redirect * on_failure - callback called if form is invalid, the default is to redisplay the form. Note that once newforms are finally done these functions are likely to be redundant, as generic views will be updated to use the newforms API, so use with caution!

  • newforms
  • forms
  • generic-views
  • modelform
Read More

MODPYTHON logging

A MODPYTHON Apache Log Handler This module provides a logging Handler class to a MODPYTHON Apache server. Python's standard [logging API](http://www.python.org/doc/2.5/lib/module-logging.html) explains how to [use a handler](http://www.python.org/doc/2.5/lib/multiple-destinations.html). The handler, by default, writes entries to the Apache error_log using the standard Python logging API. VIRTUAL HOSTS (Python 2.5) This handler also supports Apache Virtual Hosts where the mp_server object is available. Then, it writes entries to the specific virtual-host server's error_log. To get the mp_server object out of Django, you need the **log_extras()** function in your logging call (See the source comments). This module must be bound to the Python logging API. Use a site_logging.py module to do that as this [related example](http://www.djangosnippets.org/snippets/960/) shows.

  • logging
  • modpython
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

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

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

Convert CamelCase to lowercase_with_underscores

Just a simple regex function to convert a camel case string ("ClassName") to a lower case string with underscores ("class_name"). Came across a need for this when I was trying to add properties to a model at runtime using `object.__class__.__name__`. This is a modification of the function "get_verbose_name" found in django.db.models.options.

  • utilities
  • formatting
  • one-liners
Read More

Generic Views for newforms

Two common generic views to be used with newforms in similar way django.views.generic.create_update views, but adapted to the newforms library.

  • newforms
  • view
  • generic
Read More

SimpleMachines forum authentication backend

Authentication backend for Simple Machines Forum user database. Needs one setting in `settings.py`: SMF_PREFIX = 'smf' This is prefix of SMF tables. This shippet assumes that they are in the same database. There is one more optional setting: SMF_GROUP = 1 If set, will allow only users from group with given id. May be used to allow access to admin page only for moderators.

  • authentication
  • backend
  • smf
Read More

3110 snippets posted so far.