Login

All snippets written in Python

Snippet List

Copy a model instance

Create a copy of a model instance. Works in model inheritance case where ``instance.pk = None`` is not good enough, since the subclass instance refers to the parent_link's primary key during save. M2M relationships are currently not handled, i.e. they are not copied. See also Django #4027.

  • model
  • copy
Read More

Remove quotes from bits in a custom tag

A simple function that will remove the quote marks from every string in a list - if and only if the quote marks are the first and last character of the string, regardless of whether they are single or double quotes. Useful when parsing the arguments of a custom tag.

  • quotes
  • parse
  • custom-tags
  • tokens
Read More

server with debugging backdoor

this starts up two servers - HTTP serving the django application on port 8000 and a port 8001 server that will start an interactive interpreter with any incoming connections. this enables you to have an interpreter in the same process as your server. $ wget http://localhost:8000/someurl/ (...) $ nc localhost 8001 Python 2.5.2 (r252:60911, Jul 8 2008, 21:21:10) [GCC 4.3.1 20080626 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.db import connection >>> connection.queries [ ... ]

  • debugging
Read More

ParentModel and ChildManager for Model Inheritance

This is the approach I've taken to access instances of child models from their parent. Functionally it's very similar to snippets [1031](http://www.djangosnippets.org/snippets/1031/) and [1034](http://www.djangosnippets.org/snippets/1034/), but without the use of `django.contrib.contenttypes`. Usage: class Post(ParentModel): title = models.CharField(max_length=50) objects = models.Manager() children = ChildManager() def __unicode__(self): return self.title def get_parent_model(self): return Post class Article(Post): text = models.TextField() class Photo(Post): image = models.ImageField(upload_to='photos/') class Link(Post): url = models.URLField() In this case, the `Post.children` manager will return a queryset containing instances of the appropriate child model, rather than instances of `Post`. >>> Post.objects.all() [<Post: Django>, <Post: Make a Tumblelog>, <Post: Self Portrait>] >>> Post.children.all() [<Link: Django>, <Article: Make a Tumblelog>, <Photo: Self Portrait>]

  • model
  • manager
  • queryset
  • inheritance
Read More

Easy file upload handler

This function emulates the file upload behaviour of django's admin, but can be used in any view. It takes a list of POST keys that represent uploaded files, and saves the files into a date-formatted directory in the same manner as a `FileField`'s `upload_to` argument.

  • image
  • forms
  • view
  • upload
  • imagefield
  • filefield
  • file
Read More

Overriding Third-party Admin

With the advent of newforms-admin it's now possible to override admin interfaces without having to change any code in third-party modules. This example shows how to enable a rich-text editor for `django.contrib.flatpages` without touching Django's code at all. (Actual embedding of the editor via Javascript left as an exercise for the reader – plenty of examples of that elsewhere.)

  • admin
  • newforms-admin
  • custom
  • contrib.admin
  • override
  • rich-text
Read More

Model inheritance with content type and inheritance-aware manager

inspired by crucialfelix's [inheritance hack](http://www.djangosnippets.org/snippets/1031/), which was a far better method of fetching a model's subclassed version from an instance than my own, i decided to bake his snippet in to my own inheritance hack, which i think benefits both. the result is a query set that returns subclassed instances per default. So - in the snippet's example, querying `Meal.objects.all()[0]` will return a salad object, if that instance of Meal happens to be the parent of a Salad instance. To my mind this is closer to the 'intuitive' way for a query set on an inheriting model to behave. **Updated:** added subclassing behaviour for the iterator access as well. **Updated:** incorporated carljm's feedback on inheritance

  • manager
  • inheritance
Read More

DebugFooter middleware with textmate links

a minor remix of simon's debug footer: <http://www.djangosnippets.org/snippets/766/> > Adds a hidden footer to the bottom of every text/html page containing a list of SQL queries executed and templates that were loaded (including their full filesystem path to help debug complex template loading scenarios). This version adds TextMate links : if you are working on your local machine and using TextMate you can click on the template paths and they will be opened in TextMate. This speeds up development time considerably ! also, this works with django 1.0 (simon's version got broke by the 'connect' refactor) update: the view function is now linked > To use, drop in to a file called 'debug_middleware.py' on your Python path and add 'debug_middleware.DebugFooter' to your MIDDLEWARE_CLASSES setting.

  • middleware
  • debug
  • textmate
Read More

Model inheritance with content type

Contact is a parent class. Subclasses might be Company, Person, Artist, Label etc. Basic address, email etc. fields can be added to the parent class and all subclasses will have those. Having searched your database for contacts (undifferentiated by class) you then want to reload the chosen object as the subclass that it really is : ``thing.as_leaf_class``

  • inheritance
Read More

Chaining select boxes in admin with MooTools

This code will allow you to use chained select boxes in the django automatic admin area. For example, you may have a product, then a category and subcategory. You'd like to create a product, and then choose a category, and then have a chained select box be filled with the appropriate subcategories.

  • ajax
  • admin
  • select
  • mootools
Read More

breadcrumbs

With this script you can create a simple breadcrumbs line for navigation: Home >> Page >> Subpage ...

  • breadcrumbs
Read More

Moving items up/down from the admin interface

Move Items up and down from the admin interface. Like phpBB does it with its forums. An additional select field is added to the admin form. After the model has been saved, a model method is called (with the value of the new field), which handles the reordering. A more detailed description and a screenshot can be found [here](http://blog.vicox.net/2008/09/04/ordering-in-django-10/).

  • admin
  • ordering
  • moving
  • up/down
Read More

Model dependency graph using graphviz (script)

Instructions: Set your environment variables, install graphviz, and run. Finds all models in your installed apps and makes a handsome graph of your their dependencies based on foreignkey relationships. Django models have green outlines, yours have purple. The edge styling could be changed based on edge type.

  • models
  • graph
  • graphviz
Read More

Integer Currency Input

This accepts values such as $1,000,000 and stores them to the database as integers. It also re-renders them to the screen using the django.contrib.humanize.intcomma method which takes 1000000 and turns it into 1,000,000. Useful for large currency fields where the decimals aren't really necessary.

  • newforms
  • currency
  • field
  • integer
  • input
Read More

render_with decorator

Automatically render your view using render_to_response with the given template name and context, using RequestContext (if you don't know what this is you probably want to be using it). For example: @render_with('books/ledger/index.html') def ledger_index(request): return { 'accounts': ledger.Account.objects.order_by('number'), }

  • render_to_response
  • requestcontext
  • decorator
  • rendering
Read More

2955 snippets posted so far.