Login

All snippets written in Python

Snippet List

Incrementally Return CSV

The first function (ftype_batch) is a view that passes the first part of the CSV filename and a queryset intended to write out to the file. run_batch prepares the HttpResponse for incrementally writing, and write_batch actually writes out the data. The logic in write_batch is custom to what I need done, but as long as the csv writer receives a sequence to write, it should work.

  • csv
  • incremental
Read More

Drop down Datefield

Simple drop-down date field for use. You can specify date range by initiating new DateDropdownWidget. Welcome comments!

  • newforms
  • forms
  • dropdown
  • datefield
  • field
Read More

True links in the admin list

Usually, you can add links in the admin using such code: class Pingback(models.Model): #... target_uri = models.URLField( _('Target URI')) #... def admin_target(self): return '<a href="%(targ)s">%(targ)s</a>' % {'targ': self.target_uri} admin_target.short_description = _('Target URI') admin_target.allow_tags = True #... class Admin: list_display = ('id', 'admin_target') But when you have two or more url fields, such approach becomes to expensive. Follow the DRY principe and use my code in such way: # Just add this line instead of the ugly four lines **def blabla** admin_target = link('target_uri', _('Target URI'))

  • admin
Read More

Trigger a user password change

I would like to catch the raw plaintext password if a user created or change his password. First i tried to handle this with signals.post_save at the User class, like this: `dispatcher.connect(update, signal=signals.post_save, sender=User)` The problem is, in the User model exists e.g. 'last_login'. So the save method called every time, the user logged in :( And with post_save i get only the hashed password and not the plaintext source password. I found a simple way to trigger a user password change. I hacked directly into the django.contrib.auth.models.User.set_password() method. See the sourcecode. There exists a discussion in the [django-users thread](http://groups.google.com/group/django-users/browse_thread/thread/7c074e80a9cdcd21/) about this.

  • password
  • user-account
Read More

@url decorator - getting rid of urlpatterns

The rationale behind this decorator is described in django-users google group. Usage: === urls.py === urlpatterns = patterns('', (r'^', include('apps.app1.views')), (r'^app2', include('apps.app2.views')), ) === apps/app1/views/__init__.py === @url(r'^index/$') def index(request): ... @url(r'^news/$') def news(request): ... urlpatterns += include_urlpatterns(r'^members', 'apps.app1.views.members') === apps/app1/views/members.py === @url(r'^profile/$) def profile(request): .... @url(r'^secure/$) def secure(request): ... @url(r'^path1/$', '^path2/$') # you can specify several patterns def multipath_view(request): ... def helper(): # easily distinguishable - no @url! ... Summarizing, the benefits are: * no more creating and supporting urlpattern maps (less files, less code, more DRY) * have the url associated with a view in-place * easily see if a function is a view * fully compatible with other chained decorators

  • view
  • url
  • decorator
  • urlpatterns
Read More

Extended Paginator

Generate a list of page links like: First Prev 1 2 3 *4* 5 6 7 Next Last To use: 1. Put Paginator.py into your app directory 2. Copy pagination.html to your templates directory 3. pass a paginator object to your Context 4. include the pagination.html template on the page you wanted paginated Feel free to send ideas for improvement. If enough people ask, I'll package this as a single app and perhaps even make the template inclusion into a templatetag for even easier use.

  • pagination
  • paginator
  • paging
  • pager
Read More

simple string formatting filter

I use this filter quite a bit to keep my templates less cluttered. Instead of: {%if some_variable%}, {{some_variable}}{%endif%} I can write: {{some_variable|format:", %s"}} A common one I use is: {{some_variable|format:"<p>%s</p>"}}

  • filter
  • format
  • stringformat
Read More

YUI Autocomplete

This snippet allows you to use YUI's autocomplete widget in a easy way. 1. Download YUI (http://developer.yahoo.com/yui/) library and put it into MEDIA folder (in my case I put YUI/build/ directory as base/yui/ in my MEDIA folder) 2. Create lookup view for your autocomplete field. See 'test_ajax_ac' function to see how this lookup view may be built. You have to define JsonResponse somewhere in your files. JsonResponse is taken from: http://www.djangosnippets.org/snippets/154/ 3. Define url for newly created view in urls.py (in usual way) 4. Include necessary .js and .css files in your page (see example in test_ajax.html) 5. Assign widget to a field - see form's __init__ at UserForm in the example. Additional (optional) parameters are: format_result_fname (name of javascript function for formatting results - see YUI docs for examples)), item_select_handler_fname (name of javascript function for handling item select event (see YUI docs)). When using YUI take care about proper skin - you'll possibly need to define wrapper like: `<div class="yui-skin-sam">....</div>` around your html code.

  • javascript
  • yui
  • autocomplete
  • widget
Read More

Datetime widget

This widget uses: [DHTML Calendar Widget](http://www.dynarch.com/projects/calendar/). It is very simple implementation but may be easily extended/changed/refined. 1. Necessary files: First download calendar package and extract it to your MEDIA folder (MEDIA/calendar/...) You'll also need a small gif that will be shown as a button that allows user to display calendar. By default this 'gif' is searched at '[MEDIA]images/calbutton.gif' but you may change this path in the code (calbtn variable). You need to download or create callbutton.gif image by yourself (it is not included). 2. Include css and js files in your page (as shown in the comment in the code). 3. In form code assign a widget to a field as usual (see newforms documentation for more details). 4. It is possible to change date format by specifying different value for 'dformat' attribute of widget class. If you get javascript errors while trying to open calendar try to use english translation file (calendar-en.js). I've found that some translations, eg. Polish, are broken by default. In this case you should override your language translation with english one and translate it by yourself (it is easy).

  • datetime
  • date
  • calendar
  • widget
  • dhtml
Read More

Use crypt instead of sha1 as password hash algorithm

This snippet uses signals to replace the `contrib.auth.models.User.set_password()` function with one that uses *crypt* instead of *sha1* to hash the password. *Crypt* is of course cryptographically inferior to *sha1*, but this may be useful for interoperability with legacy systems e.g. when sharing a user authentication database with unix, a MTA etc. For some reason the `User` class doesn't emit a `class_prepared` signal, which would otherwise be a better choice here. That's why I had to resort to patching each `User` instance separately. A clean way to deploy this snippet is to place it in the `models.py` of an otherwise empty app, and add the app in `settings.INSTALLED_APPS`. The order of `INSTALLED_APPS` doesn't matter since we're patching instances, not classes.

  • password
  • hash
  • crypt
Read More

UTC DateTime field

A DateTime field extension that automatically stores the timezone, and the computed UTC equivalent. This field needs the pytz library. The field adds two new fields to the model, with the same name of the UTCDateTimeField field, and a suffix. For an UTCDateTimeField named 'updated', the model will contain * an 'updated' field, which holds the local datetime * an 'updated_utc' field, which holds the corresponding UTC datetime * an 'updated_tz' field, which holds the field timezone name The timezone can vary between model instances, just set the 'xxx_tz' field to the desired timezone before saving. UTCDateTimeField supports a single optional keyword argument 'default_tz', in addition to the DateTimeField standard ones, to let the user choose a provider for a default timezone when no timezone has been set. Its value can be * None (or the argument missing), in which case the default settings.TIME_ZONE will be used * a callable, which will be called when the 'xxx_tz' field is emtpy, which should return a timezone name * a string, which will be used to access a model attribute or call a model method, which should return a timezone name If the timezone name points to a non-existent timezone, a warning will be issued and the default settings.TIME_ZONE value will be used. The field will also add three properties to the model, to access the pytz timezone instance, and the offset aware datetimes for local time and UTC. For the same 'updated' field instance we used above, the three properties added to the model will be: * updated_timezone * updated_offset_aware * updated_utc_offset_aware A brief example on how to use UTCDateTimeField: class UTCDateTimeTest(models.Model): """ >>> import datetime >>> d = datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) # new instance, tz from model method >>> t = UTCDateTimeTest(updated=d) >>> t.save() >>> t.updated datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) >>> t.updated_utc datetime.datetime(2007, 8, 24, 14, 46, 34, 762627) >>> t.updated_tz 'Europe/Rome' >>> t.updated_timezone <DstTzInfo 'Europe/Rome' CET+1:00:00 STD> >>> t.updated_offset_aware datetime.datetime(2007, 8, 24, 16, 46, 34, 762627, tzinfo=<DstTzInfo 'Europe/Rome' CEST+2:00:00 DST>) >>> t.updated_utc_offset_aware datetime.datetime(2007, 8, 24, 14, 46, 34, 762627, tzinfo=<UTC>) >>> """ updated = UTCDateTimeField(default_tz='get_tz') def get_tz(self): return 'Europe/Rome'

  • models
  • fields
  • datetime
  • timezone
  • field
  • utc
Read More

Using reverse() to do redirects

When I initially set up my blog, I put together the archives with URL patterns like so: * `/weblog/2007/` goes to `archive_year` * `/weblog/2007/08/` goes to `archive_month` * `/weblog/2007/08/24/` goes to `archive_day` * `/weblog/2007/08/24/some-slug` goes to `object_detail` The same patterns held for links, only the prefix was `/links/` instead of `/weblog/`. For a forthcoming redesign/rewrite, I'm switching to using abbreviated month names (e.g., "aug", "sep", "oct", etc.) in the URLs, which means I need to redirect from the old-style URLs to the new. This snippet is the solution I hit upon. Two things are notable here: 1. Each one of these views uses [reverse()](http://www.djangoproject.com/documentation/url_dispatch/#reverse), called with the appropriate arguments, to generate the URL to redirect to. This means URLs don't have to be hard-coded in. 2. Each view takes an argument -- `object_type` -- which is used to generate the view name to pass to `reverse`, meaning that only one set of redirect views had to be written to handle both entries and links. This is just one of many handy tricks `reverse` can do :)

  • urls
  • reverse
  • redirects
Read More

2956 snippets posted so far.