Login

All snippets written in Python

Snippet List

Handy tag for generating URLs to media files

Returns an absolute URL pointing to the given media file. The first argument is the path to the file starting from MEDIA_ROOT. If the file doesn't exist, empty string '' is returned. For example if you have the following in your settings: MEDIA_URL = 'http://media.example.com' then in your template you can get the URL for css/mystyle.css like this: {% media 'css/mystyle.css' %} This URL will be returned: http://media.example.com/css/style.css.

  • template
  • tag
  • media
Read More

Truncate Characters Filter (simple)

Super stripped down filter to truncate after a certain number of letters. Ex: {{ long_blurb|truncchar:20 }} will display 20 characters of the long blurb followed by "..."

  • filter
  • letters
  • characters
Read More

Compact idiom for legacy URLs in URLconfs

Taken from the [longer description on my blog][1]: > One of the great things about Django is its simple and flexible URL handling. If your Django work, like mine, includes converting existing sites, you’ll probably be doing some URL cleanup along the way... Just plug your old/new URL pairs into `redirects`. [1]: http://e-scribe.com/news/290

  • urlconf
  • redirect
Read More
Author: pbx
  • 6
  • 9

Filter to resize a ImageField on demand

A filter to resize a ImageField on demand, a use case could be: ` <img src="object.get_image_url" alt="original image"> <img src="object.image|thumbnail" alt="image resized to default 200x200 format"> <img src="object.image|thumbnail:"200x300" alt="image resized to 200x300"> ` The filter is applied to a image field (not the image url get from *get_image_url* method of the model), supposing the image filename is "image.jpg", it checks if there is a file called "image_200x200.jpg" or "image_200x300.jpg" on the second case, if the file isn't there, it resizes the original image, finally it returns the proper url to the resized image. There is a **TODO**: the filter isn't checking if the original filename is newer than the cached resized image, it should check it and resize the image again in this case.

  • filter
  • models
  • thumbnail
  • resize
  • imagefield
Read More

New forms signup validation

This snippets provide username availability, double email and password validation. You can use it this way : f = SignupForm(request.POST) f.is_valid()

  • newforms
  • email
  • clean
  • signup
  • password
Read More

Find nearby objects

This code assumes a) that you are using PostgreSQL with PostGIS and b) that the geometry column in your model's table is populated with points, no other type of geometry. It also returns a list instead of a QuerySet, because it was simpler to sort by distance from the given point and return that distance as part of the payload than to muck around with QuerySet. So bear in mind that any additional filtering, excluding, &c., is outside the scope of this code. 'Distance' is in the units of whatever spatial reference system you define, however if you do not intervene degrees decimal is used by default (SRID 4326, to be exact). To get distance in units a little easier to work with, use a spatial ref close to your domain set: in my case, SRID 26971 defines a projection centered around Illinois, in meters. YMMV.

  • gis
  • postgis
  • geography
  • geometry
  • nearby
  • nearest
  • distance
Read More

Month list for a select drop down

month_ids is a list of months like this... [('Apr07', 'April 2007'), ('Mar07', 'March 2007'), ('Feb07', 'February 2007')] which can be used in a select box like this.. month = forms.ChoiceField(choices=(months))

  • months
  • select
Read More

Profiling Middlware

Displays hotshot profiling for any view. http://yoursite.com/yourview/?prof Add the "prof" key to query string by appending ?prof (or &prof=) and you'll see the profiling results in your browser. It's set up to only be available in django's debug mode, but you really shouldn't add this middleware to any production configuration. * Only tested on Linux * You should probably use this one instead: http://djangosnippets.org/snippets/2126/

  • middleware
  • profile
  • debug
  • stats
  • performance
  • hotshot
Read More

SmartyPants Filter

Really simple filter for using Smartpants in your template -- placed in your custom filters file. Requires python smartypants to be installed.

  • filter
  • typography
  • smartypants
Read More

filter dates to user profile's timezone

I have users in many timezones and I let them set their preferred display timezone in their user profile as a string (validated aginst the pytz valid timezones). This is a filter that takes a datetime as input and as an argument the user to figure out the timezone from. It requires that there is a user profile model with a 'timezone' field. If a specific user does not have a user profile we fall back on the settings.TIME_ZONE. If the datetime is naieve then we again fallback on the settings.TIME_ZONE. It requires the 'pytz' module: [http://pytz.sourceforge.net/](http://pytz.sourceforge.net/) Use: `{{ post.created|user_tz:user|date:"D, M j, Y H:i" }}` The example is assuming a context in which the 'user' variable refers to a User object.

  • filter
  • timezone
  • userprofile
Read More

Roman Numeral Filter

Template filter to convert integer or long integer into roman numeral with support for upper and lower case numerals. Requires python-roman package on Debian which apparently comes from http://www.diveintopython.org/

  • django
  • python
  • roman-numerals
Read More

fancy_if

I am working on some apps that use row level permissions. For many permission tests I intend to make custom tags so I can locate the permission test used by the template and by the view in a common module. However, frequently, before I decide what the actual end-tag is going to be I need a way to expression a more powerful 'if' structure in the template language. Frequently the existing if and if_has_perm tags are just not powerful enough to express these things. This may make the template language unacceptably more like a programming language but it has helped me quickly modify complex permission statements without having to next and repeat four or five clauses. As you can see this is intended to work with django off of the row level permissions branch. Here is an example of a template that is using the 'fancy_if' statement: ` {% fancy_if or ( and not discussion.locked not discussion.closed "asforums.post_discussion" discussion ) "asforums.moderate_forum" discussion.forum %} <li><a href="./create_post/?in_reply_to={{ post.id }}">{% icon "comment_add" "Reply to post" %}</a></li> {% end_fancy_if %} {% fancy_if or "asforums.moderate_forum" discussion.forum ( and not discussion.closed ( or eq post.author user eq discussion.author user ) ) %} {% fancy_if or "asforums.moderate_forum" discussion.forum eq post.author user %} <li><a href="{{ post.get_absolute_url }}update/">{% icon "comment_edit" "Edit Post" %}</a></li> {% end_fancy_if %} <li><a href="{{ post.get_absolute_url }}delete/">{% icon "comment_delete" "Delete Post" %}</a></li> {% end_fancy_if %} `

  • row-level-permissions
  • compound-conditional
Read More

autotranslatslugify

Changes **all slugify calls** to support translat automatically, behind the scenes. Using this one doesn't have to change any models or code to make it work everywhere. Create new project, I call it myself *autoslugifytranslat*, and add the following to project's `__init__.py` file. It will automatically add translat slugify support for all default slugify calls. This script is depending on the fact that slugify function in Django is always in *django.template.defaultfilters.slugify*. **Note:** The snippet is supposed to have "ä","Ä" and "ö","Ö" in the `char_translat` list, but djangosnippets does not let me put ä's and ö's to the code part!

  • i18n
  • slugify
  • translat
  • internal
Read More

Referer-checking view decorators

Here are a couple of Django decorators for limiting access to a view based on the request's `HTTP_REFERER`. Both raise a Django `PermissionDenied` exception if the referer test fails (or a referer simply isn't provided). The first, `referer_matches_hostname`, takes a hostname (and port, if specified) and matches it against the referer's. If multiple arguments are supplied a match against any of the hostnames will be considered valid. The second, `referer_matches_re`, takes a regex pattern (like Django's urlpattern) and tests if it matches the referer. This is obviously more flexible than `referer_matches_hostname` providing the ability to match not just the hostname, but any part of the referer url. Finally there's an simple example decorator, `local_referer_only`, that limits a view to the current site by using Django's `django.contrib.sites` to look up the current hostname.

  • view
  • referer
  • decorator
  • http_referer
  • request
Read More

2955 snippets posted so far.