Login

Top-rated snippets

Snippet List

CSV serializer

CSV serialization for models. Can be used via the dumpdata/loaddata management commands or programmatically using the django.core.serializers module. Supports multiple header lines and natural keys. Add the following to settings.py: SERIALIZATION_MODULES = { 'csv' : 'path.to.csv_serializer', } Examples of usage: $ python manage.py dumpdata --format csv auth.user > users.csv from django.core import serializers csvdata = serializers.serialize('csv', Foo.objects.all()) To run the regression tests distributed with the Django tarball: $ cd /path/to/Django-1.2.x/tests $ PYTHONPATH=/path/to/myproject ./runtests.py --settings=myproject.settings serializers_regress

  • csv
  • serializer
Read More

HTML Email with Inline Attachments (images)

This will allow you to attach HTML multipart emails (HTML/text) and use inline images. In my example, I'm attaching an image that's stored as an 'attachment' to an 'event.' The file name of the attachment is called "inline.jpg" and I'm referencing it in my HTML message. I'm also attaching a VCAL file (.ics) file that has some information about an associated event.

  • email
  • html
  • related
  • mixed
  • images
  • inline
  • multipart
Read More

Silk icon tags

This simple template tag can be used to add famfamfam's silk icons easily to any element in your template.

  • templatetags
  • icons
  • silk
Read More

Limit queryset to objects related to parent in ManyToMany fields within admin inlines

`formfield_for_manytomany` allows you to limit the choices/queryset for a ManyToManyField, but without direct access to the parent object. This snippet stores a reference to the parent object in `get_formset` and allows limiting of `ManyToManyField`s to objects related to the same parent object. See `ExampleInline` for example usage. If for some reason you have a `ManyToManyField` in a `TabularInline`, just change the `template` in the subclass.

  • limit_choices_to ManyToMany ManyToManyField admin inline formfield_for_manytomany
Read More

Generate Model Data. Lots of Options.

Generate model data with this django management command! Data is generated based off of the model field types. And will also correctly generate foreign key's to other randomly generated records for join tables. And generate images with random colors and random words in the image - for image fields. You can supply quite a few parameters that control how the data is generated. And you can control it per field, per model. Or you can supply your own callable function which you can return your own random data. **SEE THE DOCS / EXAMPLE IN THE CODE SNIPPET FOR AVAILABLE OPTIONS, AND HOW TO CONTROL GENERATED DATA PARAMETERS** You can generate data that looks like real content, without having to write fixtures and such. Just generate it! It can generate data for these types of fields: EmailField SlugField BooleanField DateField DateTimeField TimeField IntegerField DecimalField TextField CharField IPAddressField URLField SmallIntegerField PositiveSmallIntegerField PositiveIntegerField ImageField There are also a few callables included that you can use to generate this kind of data: zip, extended zip, hashkey and uuid It's also worth noting that I keep this project up to date on my own git repository. There are a few fonts you'll need if you want to generate imaages, included in my git repo. http://gitweb.codeendeavor.com/?p=dilla.git;a=summary

  • model
  • random
  • data
  • management
  • command
  • lipsum
Read More

Complex Formsets, Redux

Background ========== Two years ago, Malcolm Tredinnick put up an excellent post about doing dynamic Django forms. There have been several excellent write-ups on it since - Google is your friend. One year ago, I attempted to make a dynamic Formset - see [this snippet](http://www.djangosnippets.org/snippets/1290/). Malcolm posted a cleaner solution two weeks later, and I liked his solution better. Some time after that happened, his site tanked. I'm re-posting my snippet using his technique, so that everyone can see how it is done. Credit to goes to Malcolm - I'm just the messenger. If his site ever comes back up , check out his complex formset post [here](http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/). I'll use Malcolm's example code, with as few changes as possible to use a formset. The models and form don't change, and the template is almost identical. I won't reproduce all of Malcolm's code - I'm just show the form setup. There are no models here - you'll have to use your imagination for Quiz, Question, and Answer models. He did some fancy validation as well - I'm not going to here. Problem ======= Build a formset based on dynamically created forms. Solution ======== The core idea in this code is found in the `_construct_form` method. Typically, this is where a formset makes new forms - it handles indexing them so that everything is nice and unique. We can take advantage of this by overriding the method and inserting a `kwarg` that will be passed on to our form class, then calling the parent `_contruct_form` method to let it finish doing everything else for us. This is what Malcolm, a core Django developer, knows about, and I, a random Django user, typically do not. Code ==== This pattern greatly simplifies building formsets dynamically, and it really only requires a few bits of knowledge. 1. If we `pop()` special arguments out of `kwargs` dictionaries, we then can pass the remaining `kwargs` along to parent methods and let them do the rest of the setup for us. See code tricks #1 and #3. 2. If we have a form and need to add dynamic fields that we didn't declare the usual way, we can just add them to the `self.fields` dictionary. See code trick #2. 3. If we need to add forms dynamically to a formset, we can use the `self.extra` variable to specify how many we want, based on the length of a custom queryset. See code trick #4. 4. If we want to pass some special arguments to a form that will be part of a formset when it is constructed, we can add them to the `kwargs` dict in `_construct_form`, taking advantage of the `index` variable to track which object from our queryset we wanted. See code trick #5.

  • dynamic
  • formset
  • complex
Read More

SearchableManager

A drop-in chainable manager for providing models with basic search features such as +/- modifiers, quoted exact phrases and ordering by relevance.

  • search
  • model
  • manager
  • queryset
Read More

Get admin url for a model

Add this to your model to be able to get their admin change link from anywhere Useful if you want to jump to the admin screen of an object you are looking at on the front end

  • admin
  • url
Read More

Dynamically create Django admin actions

With this snippet, I made a set of admin actions for assigning `Quality` objects to `Package` objects. The Django docs for [ModelAdmin.get_actions][1] explain the dictionary of tuples that is returned. [1]: http://docs.djangoproject.com/en/1.1/ref/contrib/admin/actions/#django.contrib.admin.ModelAdmin.get_actions

  • admin
  • admin-actions
  • closures
Read More

Technical 500 by group membership

Based loosely on [Eric's middleware](http://ericholscher.com/blog/2009/sep/5/debugging-django-production-revisited/), this middleware will show the technical 500 page (which you'd get if DEBUG == True) to any user who is (1) superuser and (2) a member of the settings.TECHNICAL_500_GROUP_NAME group. (If no setting exists, 'Technical Errors' is the presumed group name. I agreed with the comments that caching should be unnecessary given the (presumptive) edge case of exception + superuser. Assuming you don't have tons of superusers, this code is a good bit simpler.

  • admin
  • user
  • auth
  • debugging
  • 500
Read More

Persistent connection to PostgreSQL database

Hi, I made some small custom psycopg2 backend that implements persistent connection using global variable. With this I was able to improve the amout of requests per second from 350 to 1600 (on very simple page with few selects) Just save it in the file called base.py in any directory (e.g. postgresql_psycopg2_persistent) and set in settings DATABASE_ENGINE to projectname.postgresql_psycopg2_persistent This code is threadsafe, however because python don't use multiple processors with threads you won't get bit performance boost with this one. I really recommend using it in daemon mode. In apache mod_wsgi just set processes=8 threads=1

  • database
  • connection
  • persistent
Read More

3110 snippets posted so far.