Login

Most bookmarked snippets

Snippet List

Auto HTML Linebreak filter

This custom filter is helpful if you want to convert plain text to include html line breaks but you aren't sure if the text is actually plain text or if it already contains html line breaks. First the filter looks for if the text contains any br, p, or table tags, if it does the text is returned as is. If it doesn't then the same functionality as the [linebreaks](http://www.djangoproject.com/documentation/templates/#linebreaks) filter is applied to the text.

  • filter
  • html
  • linebreaks
  • custom-filter
Read More

newforms-admin edit callback-url hook

NOTE: this is for **newforms-admin** I need edit links for items on my site, outside of the django admin -- however, I'm lazy, and don't want to build my own edit forms when there's a perfectly nice admin already there. Trick is, I need to be able to click a link to the django admin edit page for an item, and have it return to the calling page after saving. This chunk of code does the trick (the "real" version extra cruft, naturally) -- the links will bring up the django admin editor, then return to the calling page after saving.

  • newforms
  • admin
  • url
  • newforms-admin
  • newformsadmin
  • edit
  • callback
  • hook
Read More

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

A action decorator for URLs

This decorator handle a extra "action" parameter from an url and call this desired action in the provided views module. Example: from posts import views urlpatterns = patterns('posts.views', ... url(r'^(?P<id>\d+)/(?P<action>delete|publish|edit)/$', action(views), name="posts-action"), ... ) In templates: {% url posts-action id=post.id,action="delete" %}

  • rest
  • url
  • decorator
  • action
  • crud
Read More

FormMail Clone

A quickie clone of good old fashion [Formmail.pl](http://www.scriptarchive.com/formmail.html) any form that is a subclass of FormMail will have its conents emailed to all staff members on the site.

  • newforms
  • email
  • formmail
Read More

Colorize Filter

I had a need to colorize the nicks for the new DjangoBot Logger. Instead of managing a collection of names and corresponding colors we decided it would be more simple to just "hash" the nickname using a colorize filter. This causes the same nickname to always appear in the same color.

  • filter
  • colorize
Read More

Autoescape Migration Helper

In the process of adapting to the new autoescaping thing, I've occasionally run into the sad situation where my development Django instance needs autoescape template tags in order to work, but when that code goes into production, I'm on a pre-autoescape Django revision. Hilarious hijinx ensue. This snippet will attempt to load the new safe and force_safe filters and the autoescape template tag - failing the imports, it'll safely do nothing. The effect is that if you write templates for post-autoescape, but you still need them to work in pre-autoescape, this'll prevent the new filters and tags from causing errors in your older Django instances.

  • autoescape
Read More

Hyperlink list filter

This is a simple filter that takes an object list and returns a comma-separated list of hyperlinks. I use it to display the list of tags in my blog entries. The function assumes the object has a `get_absolute_url()` method that returns the URL. In your template, write `{{ obj_list|hyperlink_list:"slug" }}` where `obj_list` is your object list and `"slug"` is the object's attribute that returns the link text.

  • filter
  • templatetag
  • links
  • template-tag
  • link
  • hyperlink
Read More

Field map for models

It seems like one way or another I always need to get access to a specific field of a Model object. The current way to do this is to iterate through the object's _meta.fields list, comparing with the `name` attribute. Why not just have a lookup of fields? If you paste this code at the bottom of your models.py file it will add a `field_map` attribute to the meta options. For example: `profile = User.objects.get(id=1).get_profile()` `upload_to = profile._meta.field_map['image_icon'].upload_to` ...

  • models
  • fields
  • meta
Read More

BirthYearField

A form field to prompt for a year of birth with suitable sanity checks. Usage eg: yob = BirthYearField(label="What year were you born?")

  • form
  • field
  • year
  • birth
Read More

Check Size of Object in memcached

I've been working with a data set where a single object won't fit into memcached's 1 Mb slab limit. The two functions have been useful to me for debugging the size of the data structure once pickled, and if said pickled data structure is greater than 1 Mb. These functions assume CACHE_BACKEND is memcached, obviously.

  • memcache
  • cache
  • memcached
Read More

Obfuscator for django project sources

This script can be useful if you want to obfuscate your django project sources. I use the [pyobfuscate](http://freshmeat.net/projects/pyobfuscate/) tool, a little bit patched, the patch you can get [here](http://farid.adigamov.com/files/pyobfuscate.patch). The patch switchs off the classes and methods obfuscation as they could be imported from other files. The **pyobfuscate** util can obfuscate only one file at once. This script can obfuscate all .py files from the specified path (src_dir), at the end of the obfuscation it compiles them using **compileall** module. Set the **src_dir** and the **dst_dir** variables. Note: remove original **settings.py** and **urls.py** from the **src_dir** cause **pyobfuscate** util raises an error trying to encode them. The decorators are not handled correctly by pyobfuscate tool. I'm using django for about year and i didn't use the decorators except the '@transaction' decorators. I replace them from the sources at the beginning of the obfuscation and put them at their places in encoded file. In case of using other decorators you should make some changes in code ( line # 64 ).

  • obfuscate
  • sources
  • hide
  • obfuscator
Read More

Table of Contents

Simple template filter that extracts from a text ids, replaces '_' with spaces and produces hyperlinked Table of Contents. More info and usage example please see at [http://www.mysoftparade.com/blog/autogenerated-toc/](http://www.mysoftparade.com/blog/autogenerated-toc/)

  • toc
  • table-of-contents
Read More

3110 snippets posted so far.