Login

All snippets written in Python

2956 snippets

Snippet List

Real shuffle function

This function solve the issue of random.shuffle that is based only on randomized shuffling (that's not a real shuffling, because many times items returned aren't shuffled enough). This function make a randomized shuffle and after this loops long the list resorting to avoid two items with a same value in a given attribute. When shuffling is over and there are duplicates, they are leftover to the end (and you can remove them if you set 'remove_duplicates' to True) Run it in a separated file to see it in action.

  • shuffle
Read More

Filter by first letter inclusion tag

My first snippet ;] It's a simple inclusion tag for filtering a list of objects by a first letter using [django-filter](http://github.com/alex/django-filter) after having this "installed" you can use it in your template like this: {% load my_tags %} <div class="letter_filter"> Filter by first letter: {% letters_filter "MyNiceModel" %} </div> for information how to use django-filter in your view go to [docs](http://github.com/alex/django-filter/blob/master/docs/usage.txt) you should probably cache this inclusion tag since it makes 45 queries to the db (.count() > 0) Enjoy and improve ;] PS. some parts of this code are in Polish

  • filter django-filter inclusion tag first-letter
Read More

Class Feeds DRY TemplateTag

I'm using the Django Feeds Framework and it's really nice, very intuitive and easy to use. But, I think there is a problem when creating links to feeds in HTML. For example: <link rel="alternate" type="application/rss+xml" title="{{ feed_title }}" href="{{ url_of_feed }}" /> Link's `HREF` attribute can be easily found out, just use `reverse()` But, what about the `TITLE` attribute? Where the template engine should look for this? Even more, what if the feed is build up dinamically and the title depends on parameters (like [this](http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#a-complex-example))? This is the solution I came up with. However, as you can see, there is some caveats: * Requires Django 1.2 Class Feeds, don't know exactly how to do this with the old way of feeds. * If the feed class uses the request object, the `request` [context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request) must be configured, since `None` is passed if it isn't present in the context. * There's an oddity with Feed.__get_dynamic_attr(). The Feed subclass instance doesn't have this method; instead, it appears with another name. Don't know how to figure the name out at runtime... I've posted this problem on [StackOverflow](http://stackoverflow.com/questions/2784659/django-dry-feeds), but didn't get a better answer.

  • Feeds DRY templatetag HTML LINK
Read More

Bitwise operator queryset filter

This snippet for django-1.2 allows you to use bitwise operators without using QuerySet.extra() from django.db.models import * from somewhere import FQ class BitWise(Model): type = CharField(max_length=8) value = IntegerField() def __unicode__(self): return '%s - %d' % (self.type, self.value) >>> BitWise.objects.create(type='django', value=1) <BitWise: django - 1> >>> BitWise.objects.create(type='osso', value=3) <BitWise: osso - 3> >>> BitWise.objects.create(type='osso', value=7) <BitWise: osso - 7> >>> BitWise.objects.filter(FQ(F('value') & 1, 'gt', 0)) [<BitWise: django - 1>, <BitWise: osso - 3>, <BitWise: osso - 7>] >>> BitWise.objects.filter(FQ(F('value') & 2, 'gt', 0)) [<BitWise: osso - 3>, <BitWise: osso - 7>] >>> BitWise.objects.filter(FQ(F('value') & 1, 'gt', 0) & Q(type='django')) [<BitWise: django - 1>]

  • filter
  • queryset
  • bitwise
  • operator
Read More

Vertical and Horizontal Line to geraldo report

It's fixed the right and bottom for each use. A vertical line is a line with the same right and left, so it fixed the right attribute to be the same value of the left attribute. A horizontal line is a line with the same bottom and top, so it fixed the bottom to be the same value of the top attribute.

  • geraldo
  • report
Read More

strip_tags like php one

Usage: `clean_html = strip_tags(html, {'a': ['href'], 'p': ['class']})` Based on [another snippet](http://www.djangosnippets.org/snippets/205/).

  • tags
  • html
Read More

Quick script to convert json data to csv

I often need to dump data from a database to csv. This little snippet should make it easy enough to do without having to worry too much about character encodings, though it does assume you want your csv file to be utf-8 encoded. Note that this dumps just one table from the database. Trying to dump all the tables in your app will raise an exception.

  • json
  • csv
  • utility
Read More

Dojo Helper

This module contains functions and classes that help integrate the Dojo Toolkit javascript library with Django. Supports defining theme, stylesheets, required modules, and addOnLoad functions from Django. Django form fields can be instrumented to be instantiated as Dijit form objects programmatically. Full instructions on [limscoder.com](http://www.limscoder.com/2010/04/django-dojo.html).

  • ajax
  • javascript
  • dojo
Read More

datetime.time/datetime.datetime to Unix Epoch (with microsecond support)

This is useful when you need to convert a datetime.datetime.now() or datetime.date.today() into a unix epoch seconds, with microsecond precision (precision only applies to datetime.datetime, as datetime.date won't have any microseconds). I have found this is necessary for when storing the DateTime in the models as a FloatField, in order to keep the usec/microsecond precision. At some point, I will probably create a custom model field called DateTimeWithUSec or something like that, but for now, this will do :)

  • datetime
  • date
  • time
  • epoch
  • convert
  • unix
  • usec
  • precision
  • microsecond
Read More

ISBN model field: displays 10- and 13-digit variants and external links

Requires [PyISBN](http://pypi.python.org/pypi/pyisbn/0.5.2). Use like so: class Book(models.Model): title = models.TextField() isbn = ISBNField() ... the link in the widget can be changed to amazon, borders, you name it. If the DB version is a 13-digit ISBN, the display box contains the 10-digit, labeled; and vice-versa.

  • django
  • model
  • python
  • widget
  • modelfield
  • isbn
  • books
Read More

Easier prefix handling for forms

**autoprefixed** is a decorator for Form classes that simplifies prefix handling by storing it in a hidden field. Thus when the form is posted, the prefix can be extracted from the posted data instead of having to pass it explicitly when instantiating the form.

  • form
  • prefix
Read More

Dynamically change admin widgets at runtime

django-adminwidgetswap =============== adminwidgetswap is used for dynamically swapping out widgets from django's generated admin. This allows applications to be packaged generically without the need for WYSIWYG dependencies editors- giving the application consumer the freedom to chose admin widgets without modifying original app source. Author ====== [David Davis](http://www.davisd.com) (http://www.davisd.com) [dynamically change django admin widets at runtime (django-adminwidgetswap) blog post](http://www.davisd.com/blog/2010/04/17/dynamically-change-django-admin-widgets-at-runtime/) Usage =============== To change a widget in django's admin, just put adminwidgetswap.py on the python path, import adminwidgetswap.py and use: adminwidgetswap.swap_model_field(model, field, widget) ...to change a widget for a direct model admin's field --- adminwidgetswap.swap_model_inline_field(model, field, widget) ...to change widgets for inlines of a specific model and field --- adminwidgetswap.swap_model_and_inline_fields(model, field, widget) ...to change both the widget for the direct model admin's field as well as all inline usages for the model and field --- I usually have a project-level application called website, and I put this initialization code inside the website app's __init__.py Usage - parameters =============== model is the Model class (eg. models.GalleryImage) field is the field name you're looking to swap (eg. 'image') widget is the widget you're going to swap for (eg. widgetlibrary.ThumbnailWidget())

  • admin
  • widgets
  • abstraction
Read More

immitating 'real' post_syncdb signal

I did not like the idea of having to load fixtures by creating a huge initial_data.json file. I also did not want to store my initial data in a bunch of <modelname>.sql files. Django has post_syncdb signal which fires when model(s) for an application are installed, but I needed something that would run only *once* at the end of syncdb command, at least after all of the models are installed, and here's what I've come up with. The code basically checks if the current callback is for the last app in your INSTALLED_APPS, and if so, executes some fixture loading code.

  • signals
  • post_syncdb
Read More

Excel Date

This allows you to just call excel_date and it will convert any dates between excel and python datetime.

  • date
  • excel
Read More