Login

All snippets written in Python

2956 snippets

Snippet List

Template filter for formatting negative numbers

I have a need to conditionally format a negative number, a hedgefund's daily price change, Excel style. i.e. show a negative number as a parenthesized number instead of a negative sign. Here is a filter that will do that and more, solving a more general case. See the doctest for examples.

  • template
  • filter
  • format
  • currency
  • math
Read More

Page numbers with ... like in Digg

Digg-like page numbering using inclusion tag. Usage in template: {% load pagination %} {% pagination yourpage %} Inclusion template `pagination.html`: {% load i18n %} <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}" class="previous">{% trans "previous" %}</a> {% endif %} {% for pnum in begin %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% if middle %} <span class="continue">...</span> {% for pnum in middle %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% endif %} {% if end %} <span class="continue">...</span> {% for pnum in end %} {% ifequal page.number pnum %} <span class="current">{{ pnum }}</span> {% else %} <a href="?page={{ pnum }}">{{ pnum }}</a> {% endifequal %} {% endfor %} {% endif %} {% if page.has_next %} <a href="?page={{ page.next_page_number }}" class="next">{% trans "next" %}</a> {% endif %} </span> </div> Produces: previous 1 2 ... 4 5 6 7 **8** 9 10 11 12 ... 17 18 next Or: **1** 2 3 4 5 6 7 8 ... 17 18 next Or: previous 1 2 ... 10 11 12 13 14 15 16 **17** 18 next

  • tag
  • django
  • templatetag
  • pagination
  • digg
  • pages
Read More

nofollow filter for external links

Based on [svetlyak](http://www.djangosnippets.org/users/svetlyak/)'s [nofollow filter](http://www.djangosnippets.org/snippets/312/). This one processes only external URL's. Links with internal URL's will be returned unmodified. There's one gotcha; I preferred to have false positives instead of false negatives. So, it will nofollow `href="some/relative/path/"` for example. If you must do relative paths do it like this: <a href="./some/relative/path">link text</a>

  • filter
  • nofollow
Read More

Improved YAML serializer for large databases

I needed the ability to serialize and deserialize my database, which contains millions of objects. The existing XML serializer encountered spurious parse errors; the JSON serializer failed to handle UTF-8 even when it was asked to; and both the JSON and YAML serializers tried to keep all the representations in memory simultaneously. This custom serializer is the only one that has done the job. It uses YAML's "stream of documents" model so that it can successfully serialize and deserialize large databases.

  • serialize
  • database
  • yaml
Read More

Debug view: show available named URL patterns

Hook the show_url_patterns view function in to your URLconf to get a page which simply lists all of the named URL patterns in your system - useful for if your template developers need a quick reference as to what patterns they can use in the {% url %} tag.

  • urlconf
  • debug
  • debugging
  • urlpatterns
  • documentation
  • docs
Read More

wordbreak filter

usage: {{ object.content|wordbreak:"10" }} This means if any word is 10 characters or longer, a `&shy;` will be placed every 10 characters. This is to break long words which may break the appearance of a page. The output of this is HTML safe as the content has been conditionally escaped.

  • filter
  • custom-filter
  • wordbreak
  • word-break
  • long-words
Read More

Built-in Slugify with filtering.

This is based on snippets 29 and 43, both of which had good ideas, and I thought, "why not combine them?" Given the new_topic string above, the resulting slug will be: "test-long-string-which-has-many-words-here" John Crawford Note - requires python 2.5, for list comprehensions. Otherwise you could just use a for loop to build the clean_list.

  • django
  • slugify
Read More

simple DomainsAliasMiddleware

Permit to redirect desired domain name to the 'domain' of Site app. Useful if you have different domains name for the same website. #1. Add to your settings DOMAINS_ALIAS like this: DOMAINS_ALIAS = ( 'my-second-domain.com', 'www.my-second-domain.com', 'third-domain.com', 'www.third-domain.com', ) notice: all these domains are redirected to the **domain** db entry of Site ID. #2. add all these domains to ServerAlias directive in your vhost apache configuration. #3. enable the middleware by adding to your MIDDLEWARE_CLASSES: MIDDLEWARE_CLASSES = ( ... 'utils.middleware.domainsalias.DomainsAliasMiddleware', ... )

  • middleware
  • redirect
  • domain
Read More

streaming serializer

Trying `./manage.py dumpdata` on a huge database and getting `MemoryError`s? Here's part of your solution. [Snippet 1400](http://www.djangosnippets.org/snippets/1400/) provides a queryset_foreach utility that we've found very useful. This snippet uses it on a serializer that can output to a stream, such as the XML serializer. Management command coming momentarily...

  • dumpdata
  • large
  • memoryerror
Read More

Create multiple related objects at once

The following code takes two related models and creates one user interface to for create and update operations that handles them both. It enables the creation or update of instances from both models in one shot, without having to create very complex forms. As I could not find examples for creation of related objects together, I thought this might be useful for someone.

  • forms
  • object-creation
  • related-objects
Read More

Seconds-to-Duration Template Tag

Does exactly what it says on the tin! This template tag, when implemented, converts a duration (in seconds) to a more meaningful format. It has a short and long setting, which is easy to manipulate for your needs. Apologies if something already exists like this, however I felt that writing this would be quicker than trying to find it online. As an example, given the duration 84658: Short (default): 23 hrs 30 mins 58 secs Long: 23 hours, 30 minutes and 58 seconds All the best, [Dan Ward](http://d-w.me).

  • template
  • tag
  • seconds
  • to
  • duration
Read More

Authenticate against Active Directory - LDAP (my version)

This is based on [snippet 501](http://www.djangosnippets.org/snippets/501/), with some corrections: 1. if user doesn't exist and AD.authenticate passes, then create new user - don't store password - prevent default django auth backend authentication 2. if user exists and AD.authenticate passes - django User object is updated 3. various error handling 4. fixes (some mentioned in original snippet) 5. some settings removed from settings to backend module 6. other changes (ADUser class, re-indent, logging etc.) 7. ignores problem with search_ext_s (DSID-0C090627) 8. caching connection - when invalid then re-connect and try again Note that there is also ldaps:// (SSL version) django auth backend on [snippet 901](http://www.djangosnippets.org/snippets/901/). Possible improvements: 1. define new settings param - use secured - then LDAPS (snippet 901) 2. define new settings extra ldap options - e.g. protocol version 3. fetch more data from AD - fill in user data - maybe to make this configurable to be able to update user.get_profile() data too (some settings that has mapping AD-data -> User/UserProfile data)

  • auth
  • ldap
  • active-directory
  • backend
Read More