Login

All snippets written in Python

Snippet List

Expose the 404/500 views during development

A simple addition for the urls.py that exposes the 404/500 templates during development. This way you can test how those look. They're mounted under /404/ and /505/ respectively. Add this at the bottom of your main urls.py.

  • development
  • debug
  • urlsconf
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

Require login by url

An example of using it in your settings.py: MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', 'util.loginmiddleware.RequireLoginMiddleware', ) LOGIN_REQUIRED_URLS = ( r'/payment/(.*)$', r'/accounts/home/(.*)$', r'/accounts/edit-account/(.*)$', ) In a nutshell this requires the user to login for any url that matches against whats listing in LOGIN_REQUIRED_URLS. The system will redirect to [LOGIN_URL](http://www.djangoproject.com/documentation/settings/#login-url)

  • middleware
  • authentication
  • url
  • login
  • auth
Read More

ImageFSStorage

A custom FileSystemStorage made for normalizing extensions. It lets PIL look at the file to determine the format and append an always lower-case extension based on the results.

  • storage
  • images
Read More

DualPasswordForm

DualPasswordForm is a simple form that contains two password fields and validation to ensure that the two passwords match. A minimum password length of 7 characters is imposed, but feel free to change that.

  • form
  • password
  • match
  • dual
  • dualpasswordform
Read More

RequestFactory: Easily create mock request objects, for use in testing

Django's testing framework assumes you will be running your tests against "live" views that have been plugged in to your site's URL configuration - but sometimes you might want to run a test against a view function without first wiring it in to the rest of the site. This class makes it easy to do that by providing a "factory" for creating mock request objects, re-using the existing test Client interface (and most of the code). Once you've created a request object in your test you can use it to call your view functions directly, then run assertions against the response object that gets returned.

  • testing
  • httprequest
Read More

auto image field w/ prepopulate_from & default

Given such code: class ProductImage(models.Model): fullsize = models.ImageField(upload_to= "products/%Y/%m/%d/") display = AutoImageField(upload_to= "products/%Y/%m/%d/",prepopulate_from='fullsize', size=(300, 300)) thumbnail = AutoImageField(upload_to="products/%Y/%m/%d/",null=True,default='/media/noimage.jpg')) display will be automatically resized from fullsize, and thumbnail will default to /media/noimage.jpg if no image is uploaded Note: At some point the code broke against trunk, which has now been updated to work properly

  • image
  • models
  • db
  • field
Read More

MODPYTHON Sample Site Logging

This sample site_logging.py module uses the [MODPYTHON Logging snippet](http://www.djangosnippets.org/snippets/627/). It assigns the ApacheLogHandler class to the main logging object, when Django is run inside MODPYTHON. You must have the MODPYTHON Logging snippet, and name it modpython_logging.py for this to work. Apache will write to virtual host-specific logs only with Python 2.5. Users are encouraged to change the two logging settings. Log Level: handler.setLevel(logging.WARNING) Log Format: logging.Formatter(...)

  • logging
  • mdpython
Read More

HTML to text filter

This filter converts HTML to nicely-formatted text using the text-browser W3M. I use this for constructing e-mail bodies, since it means I don't have to have two templates, one HTML and one plain-text, for each detailed e-mail I want to send. Besides the obvious maintenance benefits, this is nice because Django's templating system isn't well-suited to plain-text where whitespace and line-breaks are significant. I chose W3M because it renders tables nicely and can take in HTML from STDIN (which Lynx can't do). An alternative is ELinks; to use it, change "cmd" to the following: `elinks -force-html -stdin -dump -no-home`

  • filter
Read More

Automatic stripping textual form fields

Here is a class decorator that allows not to bother with stripping leading and trailing white space from user input provided via forms. This could be a temporary solution for an issue addressed in the ticket [#6362](http://code.djangoproject.com/ticket/6362). The documentation is provided in the form of doctest. The decorator works with `ModelForm`'s just as well as with ordinary forms. Note however that this is not a 100% panacea. Your models still could become malformed if theirs data is obtained from another source, not forms.

  • newforms
  • forms
  • strip
  • auto
Read More

[UPDATE]Filter to resize a ImageField on demand

A filter to resize a ImageField on demand, a use case could be: <img src="{{ object.image.url }}" alt="original image"> <img src="{{ object.image|thumbnail }}" alt="image resized to default 104x104 format"> <img src="{{ object.image|thumbnail:200x300 }}" alt="image resized to 200x300"> Original http://www.djangosnippets.org/snippets/192/

  • template
  • image
  • thumbnail
Read More

Smarter USPhoneNumberField

The original USPhoneNumberField only validates xxx-xxx-xxxx values. This field validates... > (xxx) xxx xxxx > xxx-xxx-xxxx > (xxx)-xxx-xxxx > many others. **Explanation of the regular expression:** 1. Accepts either (xxx) or xxx at the start of the value. 2. Allows for any amount of dashes and spaces (including none) before the next set of digits. 3. Accepts 3 digits 4. Allows for any amount of dashes and spaces (including none) before the next set of digits. 5. Accepts 4 digits, finishing the value. This field saves in the same format that the original USPhoneNumberField does (xxx-xxx-xxxx). Enjoy!

  • forms
  • validation
  • field
  • phone
Read More

Minify JS template tag

Uses JSMin. Python version available from [http://www.crockford.com/javascript/jsmin.py.txt](http://www.crockford.com/javascript/jsmin.py.txt) Provides template tags to minify JavaScript on the fly. `{% minifyjs %}[code]{% endminifyjs %}`

  • template
  • tag
  • javascript
  • js
  • minify
Read More

Refactor template files to use {% block %} tags.

Refactors two similar django template files to use `{% block %}` tags. Takes two template files, where one is a modified version of the other, and looks for differences and similiarities between the two. It then generates refactored (and renamed) versions of each file and a third 'base' file, adding an `{% extends %}` tag as appropriate. Block tags are named with matching numbers in all 3 files, making it easy to do a search and replace with more meaningful labels. `sample_data_in_base` controls whether or not the content from file 1 is copied into place in the base file as an example. Problems: it doesn't identify open `{% for %}` or `{% if %}` tags, so this needs some manual fixing (moving the `{% endfor %}` and `{% endif %}` tags into the proper blocks). It doesn't add the correct path for the `{% extends %}` tag either (ie. `"app/base.html"`). `collapse_whitespace` is not working at all.

  • template
  • refactor
Read More

Multiple-Submit-Button Widget for Choice Field

Django administration provides three buttons for submitting the currently edited object. Each of them has a unique name and depending on the name that is sent to the server, the specific action is performed. I see this as an ugly solution and prefer to have a choice field in the form which would render as submit buttons with different values. Then the values would be checked instead of the names. Therefore, I created the `MultipleSubmitButton` widget. When `<input type="submit" value="Go" />` is used, the value sent to the server always matches the text on the button, but if `<button type="submit" value="go">Go</button>`, the value and the human representation might differ. To use the `MultipleSubmitButton` widget, pass it to the widget parameter of a `ChoiceField` like this: SUBMIT_CHOICES = ( ('save', _("Save")), ('save-add', _("Save and Add Another")), ) class TestForm(forms.Form): do = forms.ChoiceField( widget=MultipleSubmitButton, choices=SUBMIT_CHOICES, ) When you print `{{ form.do }}` in the template, the following HTML will be rendered: <ul> <li><button type="submit" name="do" value="save">Save</button></li> <li><button type="submit" name="do" value="save-add">Save and Add Another</button></li> </ul> When you submit this form and check the validity of it, `form.cleaned_data['do']` will return "save" or "save-add" depending on the submit button clicked.

  • forms
  • widget
  • submit
Read More

2955 snippets posted so far.