Login

All snippets written in Python

Snippet List

roman numbers template filter

dirt and simple template filter to convert a number to its roman value. taken from dive into python http://www.diveintopython.org/unit_testing/stage_5.html

  • template
  • filter
  • filters
  • roman
  • numbers
Read More

Currency Fields with newforms

The newforms package allows you to simply add new field types to your forms. This snippet shows the addition of a new type of field, to make sure the user enters sensible currency values (either with no decimal, or two-decimal places), and a custom widget to make sure that the value is displayed correctly when the user sees the form. The CurrencyInput widget simply tries to display the current value in floating point 2-decimal places format (and gives up if it can't). The CurrencyField makes sure that the input value matches a regular expression, and when it is asked to clean the value it converts it to a float. The regex here limits the amount to 99,999.99 or less. This is within the bounds of accuracy of python's float value. If you want to use truly huge values for the amount, then you'll face problems with the floating point not being able to represent the values you enter, and so the conversion to floating point in the field will fail. In this case it would be better to use python longs, and used a fixed point interpretation.

  • newforms
  • validation
  • currency
  • form
  • widgets
Read More

Save disk space by hard-linking multiple Django installations

If you work with Django like I do, you have a separate installation or Subversion check-out of Django for each of your projects. Currently each one of them eats 22 MB of disk space. This utility hard-links all identical files between copies of Django. They can even be different versions or svn revisions, and you'll still be able to free a good amount of disk space. Run this every now and then if you update installed copies of Django or add new ones. This utility is available also [here](http://trac.ambitone.com/ambidjangolib/browser/trunk/hardlink_django_instances/hardlink_django_instances.py).

  • disk
  • disk-space
Read More

HttpMethodsMiddleware

This middleware allows developers to "fake" browser support for HTTP methods. Even though most modern browsers only support GET and POST, the HTTP standard defines others. In the context of REST, PUT and DELETE are used for client interaction with the server. For forms with a PUT or DELETE method, this middleware will change them to go through POST, and will include an invisible field called "method_middleware_transform" that carries the originally intended method. So, `<form method="PUT" ...>...</form>` More or less becomes `<form method="POST" ...><input type=hidden name="method_middleware_transform" value="PUT"></form>` (with a few other minor HTML modifications) The process is completely transparent to the developer... you never have to deal with the fact that browsers don't support the standard methods. **One caveat** is that server interaction via `XMLHttpRequest` (AJAX) requires special attention... this middleware won't properly setup your XMLHttpRequest to take advantage of this functionality. This is a combination of the work of Jesse Lovelace and the Django CSRF middleware.

  • middleware
  • rest
Read More

Import mail into a Django model

A mildly crufty script to slurp mail from an mbox into a Django model. I use a variant of this script to pull the contents of my scammy-spam mbox into the database displayed at <http://purportal.com/spam/>

  • email
  • faceless
  • utility
Read More
Author: pbx
  • 4
  • 11

prettify html

with this middleware you can use tidy to prettify your html, just add the class to the `MIDDLEWARE_CLASSES` setting. tidy has an enormous number of options, se [Tidy Options Reference](http://tidy.sourceforge.net/docs/quickref.html) . you must have [µTidylib](http://utidylib.berlios.de/) installed.

  • html
  • xhtml
  • tidy
  • standard
Read More

media_url context variable

with this you can have context variables which know the media url and the urls of all your applications, if you need it. save the code as myapp/context_processors.py and add the following line to `TEMPLATE_CONTEXT_PROCESSORS` setting "mysite.myapp.context_processors.url_info", For each application you need to know the url set `MYAPP_URL` and add it to dict.

  • url
  • media
  • context
Read More

render_markup filter, specify the markup filter as a string

Ever since django.contrib.markup appeared I've added a `markup_lang` field to my models where I want to support multiple input formats. This filter lets you pass the filter name as a string (from your model field, for example) and it will call the appropriate filter. I use None when the text is HTML, in which case it will return as-is. Example: class Article(models.Model): content = models.TextField(null=False, default="") markup_lang = models.CharField(maxlength=20, blank=True) a = Article(content="**Test!**", markup_lang='textile') b = Article(content="<h1>Hello!</h1>") And in a template: {% for article in article_list %} {{ article.content|render_markup:article.markup_lang }} {% endfor %}

  • filter
  • markup
Read More

Sanitize text field HTML (here from the Dojo Toolkit Editor2 widget)

When using a JavaScript WYSIWYG editor widget for text area content, the resulting HTML should be sanitized so no unallowed HTML tags (esp. script tags) are present. The [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library handles HTML processing in the solution presented above, so you should place it in the Python path. The snippet also assumes that you have [the Dojo Toolkit](http://dojotoolkit.org/) and its Editor2 widget loaded on your page. **Note**: this snippet was originally written for use with Dojo Toolkit 0.4, and it hasn't been updated for 0.9 or 1.0.

  • forms
  • html
  • wysiwyg
  • dojo
  • security
  • sanitize
Read More

Slugify alternative

I prefer to use this slugification function rather than the one included with Django. It uses underscores instead of dashes for spaces, and allows dashes and periods to occur normally in the string. I decided on this when considering reasonable slugified titles such as... object-relational_mapper_2.5 ten_reasons_web-2.0_rocks django-trunk_0.99_updated

  • filter
  • slugs
  • slug
  • slugify
Read More

Database migration and dump/load script

I once needed to convert a Django project from PostgreSQL to SQLite. At that time I was either unaware of manage.py dumpdata/loaddata or it they didn't yet exist. I asked for advice on the #django IRC channel where ubernostrum came up with this plan: simple process: 1) Select everything. 2) Pickle it. 3) Save to file. 4) Read file. 5) Unpickle. 6) Save to db. :) Or something like that. First I thought it was funny, but then started to think about it and it made perfect sense. And so dbpickle.py was born. I've used this script also for migrating schema changes to production databases. For migration you can write plugins to hook on dbpickle.py's object retrieval and saving. This way you can add/remove/rename fields of objects on the fly when loading a dumped database. It's also possible to populate new fields with default values or even values computed based on the object's other properties. A good way to use this is to create a database migration plugin for each schema change and use it with dbpickle.py to migrate the project. See also [original blog posting](http://akaihola.blogspot.com/2006/11/database-conversion-django-style.html) and [my usenet posting](http://groups.google.com/group/django-users/browse_thread/thread/6a4e9781d08ae815/c5c063a288483e07#c5c063a288483e07) wondering about the feasibility of this functionality with manage.py dumpdata/loaddata. See [trac site](http://trac.ambitone.com/ambidjangolib/browser/trunk/dbpickle/dbpickle.py) for version history.

  • dump
  • database
  • migration
  • load
  • pickle
Read More

Allow filtering and ordering by counts of related query results

I know you're thinking, *what the heck could that title mean?* I often find myself wanting to filter and order by the result of a COUNT(*) of a query using a method similar to the [entry_count example](http://www.djangoproject.com/documentation/db-api/#extra-select-none-where-none-params-none-tables-none). Writing this many times is tedious and hardcoding the table and column names made me cringe, I also wanted the counts to result from more complex queries. This is a method you can add to your custom Manager to do this easily. It's not an ideal syntax, but it's good for the amount of code required. Example: suppose we have some articles we want to filter and order by comments and visit logs to show the most popular... class ArticleManager(models.Manager): count_related = _count_related class Article(models.Model): pub_date = models.DateTimeField(auto_now_add=True) objects = ArticleManager() class Comment(models.Model): article = models.ForeignKey(Article) is_spam = models.BooleanField(default=False) class Visit(models.Model): article = models.ForeignKey(Article) referrer = models.URLField(verify_exists=False) search_query = models.CharField(maxlength=200) Notice how the ArticleManager is given the `count_related` method. Now you can find the most popular like so... Order by non-spam comments: Article.objects.count_related(Comment.objects.filter( is_spam=False)).order_by('-comment__count') Order by incoming non-search-engine links: Article.objects.count_related(Visit.objects.filter( referrer__isnull=False, search_query__isnull=True), 'links').order_by('-links') Order by total visits: Article.objects.count_related(Visit).order_by('-visit__count') Note: Doesn't work if `query` contains joins or for many-to-many relationships, but those could be made to work identically if there's demand.

  • sql
  • model
  • db
  • count
  • manager
Read More

use oldforms validators in newforms forms

Using the `run_oldforms_validators` function, you can run oldforms validators in your newforms `clean_XXX` methods. Usage example: class PasswordForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput()) def clean_password(self): validator_list = [ isStrongPassword, isValidLength, SomeValidators( num_required=3, validator_list=[hasLower, hasUpper, hasNumeric, hasSpecial], error_message="Password must contain at least 3 of: lowercase, uppercase, numeric, and/or special characters." ) ] run_oldforms_validators('password', self, validator_list) return self.clean_data['password'] Above, `isStrongPassword`, `isValidLength`, etc. are oldforms validators. If you are interested in seeing the implementation of `isStrongPassword`, please see my [Using CrackLib to require stronger passwords](http://gdub.wordpress.com/2006/08/26/using-cracklib-to-require-stronger-passwords/) blog post.

  • newforms
  • validators
  • oldforms
Read More

FieldsetForm

This is FieldsetForm for rendering forms with fieldsets. This is not in anyway final version of this snippet. This is preliminary version which just works. One can easilly implement the `as_ul`, `as_p` at the end with just looking the `as_table` definition. > Content developers should group information where natural and appropriate. When form controls can be grouped into logical units, use the FIELDSET element and label those units with the LEGEND element... - [Web Content Accessibility Guidelines 1.0](http://www.w3.org/TR/WCAG10-HTML-TECHS/#forms-grouping) **Notice**: Since this uses *real* fieldset elements of HTML we had to define `form.as_table` the way it *includes* the `table` element around it. **Usage in template** {{ form }} and **not** `<table>{{ form }}</table>` **Usage in view** Following usage example is for *django.contrib.flatpage*, but naturally you can use it to whatever you want. Example assumes user knows about newforms and basics to how to use `form_for_*` functions from THIS-SNIPPETS-POSITION-IN-PYTHON-PATH import form_fieldsets ... fieldsets = form_fieldsets( (None, {'fields': ('url','title','content',)} ), ("Advanced options", {'fields': ('sites', 'template_name', 'registration_required',), 'classes':'collapse'}) ) ... ... forms.models.form_for_instance(flatpage, **fieldsets) ... forms.models.form_for_model(FlatPage, **fieldsets) ... Above creates two fieldsets: 1. "None" named fieldset (meaning no name is given) with fields 'url', 'title' and 'content'. 2. "Advanced options" named fieldset with fields 'sites', 'template_name' and 'registration_required' and collapse class in place. Syntax of form_fieldsets function is identical with models `class Admin: fields = (...)`, actually you can use admins exact line here with adding it like `form_fieldsets(*FlatPage.Admin.fields)` if you prefer that, although it wrecks the point of having newforms admin, if one does identical forms as in admin part. Purpose of this is not to create identical forms as in admin but to provide easy fieldsets for all views and forms. To follow DRY principle this should be part of Django and Django's newforms-admin branch should start to use some subclassing of this. But even if the newforms-admin branch never take this in, it is more DRY than without to use this in own projects, with this in place you can forget all template hazzles defining fieldset manually. **Some "counter" statemets for having this** > **S**: "But I want to define the table tag myself in template!" **A**: Well, you understod something wrong; First of all, for example, if there is something missing from the output of this table tag, you can feel free and subclass from FieldsetForm and define own as_table. Second of all, for having own table tag there can be only one reason to that, you want extra arguments, and that is TODO, but it is also easy piece. I haven't just needed extra stuff yet so they are not implemented. > **S**: "But, oh my! (newforms) admin does this already!" **A**: For the **last time** this is not meant for only newforms admin, you can use this on **any** given view or form renderition, since currently django does not give a simple way to use that handy fieldset automation in own views. And currently (9th of April, 2007) newforms admin does not do it this way. > **S**: "But, I want to use as_p, as_ul ..." **A**: Go ahead and fix them below... Should be pretty easy stuff. > **S**: "Each model should have only one fieldsets setting." **A**: I don't believe that; even if I did that is not convincing, since there are views that are not based on models, just bunch of fields, how would you define their fieldsets if it is not defined in the form renderition at the first place? This is the right place to define fieldsets. And the point of *FieldsetForm* is not just having multiple fieldsets per model, it is about *where* and *how* to render them.

  • newforms
  • admin
  • fieldset
Read More

truncate

Truncates a string after a given number of chars

  • filter
  • templatetags
Read More

2955 snippets posted so far.