Login

Most bookmarked snippets

Snippet List

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

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

models with order (+admin editing)

Use this abstract model if you want to add "order" to a given model. Once you do, you will get automatic "up" and "down" links for each model row. One problem is that if the user sorts by another row, the up and down links are still there, but now don't make a lot of sense.

  • models
  • admin
  • order
Read More

SOAP views with on-demand WSDL generation

Optio's [soaplib](http://trac.optio.webfactional.com/wiki/soaplib) makes it really straightforward to write SOAP web service views by using a decorator to specify types. Plus it's the only Python library, as of today, which is able to generate WSDL documents for your web service. You can test it with a soaplib client: >>> from soaplib.client import make_service_client >>> from foo.views import HelloWorldService >>> client = make_service_client('http://localhost:8000/hello_world/', HelloWorldService()) >>> client.say_hello('John', 2) ['Hello, John', 'Hello, John'] And get an WSDL document: >>> client.server.wsdl('') '<?xml version=\'1.0\' encoding=\'utf-8\' ?><definitions name="HelloWorldService" ... </definitions>'

  • soap
  • soaplib
  • wsdl
Read More

Excel Spreadsheet Export

This is an example of a view that returns an Excel spreadsheet; the last ~7 lines are the relevant ones. It relies on Excel's ability to automatically import HTML (see http://support.microsoft.com/kb/165499 for more info). The spreadsheet.html template is just has one big `<table>` tag with all the data as table cells (no `<html>` or other surrounding tags are necessary).

  • export
Read More

SSL Redirect Middleware

Snippet 240 is great, but it does not handle flatpages since flatpages are not technically a view. This operates on the request level, not the view level so it will handle flat pages. **Step 1** Add this class to your MIDDLEWARE_CLASSES **Step 2** Add an entry in settings.py which is a list of regex to match against urls that u want to have ssl: SSL_URLS = ( r'/login/', r'/home/', r'/super-sensitive-information/', )

  • middleware
  • ssl
  • redirect
Read More

Last.fm Charts

This will fetch the Top Artists List for the given username from Last.fm. It makes use of the django.cache Framework. I use it with django 0.96.2. Enjoy! Usage: ` {% load lastfm %} {% lastfm_topartists YourName as topartists %} {% for artist in topartists %} {{ artist.thumbnail }}, {{ artist.name }}, {{ artist.url }}, {{ artist.playcount }} and so on {% endfor %} `

  • template
  • chart
  • lastfm
Read More

Transparent encryption for model fields

Here's a simple way to transparently encrypt a field (just repeat the idiom for more than one) so that it is not stored plaintext in the database. This might be useful for social security numbers, etc. The storage size for the ciphertext depends on which algorithm you use. Blowfish here requires 32 characters to store an encrypted 16 characters. Note also that Blowfish requires a block size of a multiple of 8, so that is what the repeat in the _set_ssn() is all about. The Crypto module is from http://www.amk.ca/python/code/crypto.html I make no claims as to how secure this scheme is overall, comments on this are welcome.

  • database
  • encryption
Read More

Render specific blocks from templates (useful for AJAX)

Allows getting the rendered content of a specific block tag. Useful if you want to send just a part of a template back for an AJAX request. Works for arbitrary template inheritance, even if a block is defined in the child template but not in the parent. Example: In `test1.html`: {% block block1 %}block1 from test1{% endblock %} {% block block2 %}block2 from test1{% endblock %} In `test2.html`: {% extends 'test1.html' %} {% block block1 %}block1 from test1{% endblock %} And from the Python shell: >>> from django.template import loader, Context >>> from template import render_block_to_string >>> print render_block_to_string('test2.html', 'block1', Context({})) u'block1 from test2' >>> print render_block_to_string('test2.html', 'block2', Context({})) u'block2 from test1' UPDATE: See also [zbyte64](http://www.djangosnippets.org/users/zbyte64/)'s implementation in snippet [#942](http://www.djangosnippets.org/snippets/942/)

  • template
  • block
  • templates
  • render
  • context
  • blocks
Read More

Multiple inheritance of newforms and modelforms

If you try to use multiple inheritance with a modelform (to mix in some fields from an already existing form class for example) you'll get the following rather terrifying error: > "Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases" The solution is to first create the ModelForm, then create a NEW class that inherits from both the ModelForm and the form you want to mixin, then finally apply the recipe from here: [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197](http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197)

  • newforms
  • inheritance
  • modelforms
  • multipleinheritance
  • metaclasses
  • metaclass
Read More

filtered ModelChoiceField queries

ModelChoiceField allows you to use filtered queries to simplify your forms. This is great for adding objects but can fall down when you edit an existing object and the original query no longer contains the referenced field (e.g. I like to use an "active" field in several objects). The fix is simply to include an extra param: Q(pk=object_id). You have to do this in the __init__ method to get the object_id. A nice thing about this is that it works for ModelForms as well as custom Forms.

  • newforms
  • modelchoicefield
  • modelform
Read More

Manager introspecting attached model

[A comment on a recent blog entry of mine](http://www.b-list.org/weblog/2008/feb/25/managers/#c63422) asked about a setup where one model has foreign keys pointing at it from several others, and how to write a manager which could attach to any of those models and query seamlessly on the relation regardless of what it's named. This is a simple example of how to do it: in this case, both `Movie` and `Restaurant` have foreign keys to `Review`, albeit under different names. However, they both use `ReviewedObjectManager` to provide a method for querying objects whose review assigned a certain rating; this works because an instance of `ReviewedObjectManager` "knows" what model it's attached to, and can introspect that model, using [Django's model-introspection API](http://www.b-list.org/weblog/2007/nov/04/working-models/), to find out the correct name to use for the relation, and then use that to perform the query. Using model introspection in this fashion is something of an advanced topic, but is extremely useful for writing flexible, reusable code. **Also**, note that the introspection cannot be done in the manager's `__init__()` method -- at that point, `self.model` is still `None` (it won't be filled in with the correct model until a bit later) -- so it's necessary to come up with some way to defer the introspection. In this case, I'm doing it in a method that's called when the relation name is first needed, and which caches the result in an attribute.

  • managers
  • models
  • introspection
Read More

Add special field lookups to the Admin list_filter display

Ever wanted to add an atypical [field lookup](http://www.djangoproject.com/documentation/db-api/#field-lookups) to the Django Admin list_filter filters, like `__isnull` or `__in`? This jQuery snippet allows you to do just that. Since you can access those additional filters by directly typing them into in the Admin URL, the tricky part is to add those to the regular list_filter display. A lot of this code is spent checking on querystring matches which is ugly and error-prone -- if you see any problems or room for improvement, drop me a comment! A suggestion of where to place this code is in `templates/admin/yourapp/yourmodel/change_list.html`. Mine kinda looks like this: {% extends "admin/change_list.html" %} {% block content %} <script src="/static/js/jquery-1.2.2.min.js" type="text/javascript"></script> <script type="text/javascript"> // the JavaScript posted in this snippet </script> {{ block.super }} {% endblock %}

  • admin
  • jquery
Read More

Export Database and Media_Root via Admin Interface

This is the view-code to export a database-dump (hardcoded for mysql) or a media_root dump via the admin interface. just add 2 urls patterns to call the views and a small template with a simple form to send a http-post to the views. Note: The downloads are sort of streaming. I have successfully exportet a 2GB media_root as tar-ball without major increase of ram-usage of the django-process.

  • admin
  • export
  • database
  • media-root
Read More

Color SQL logging middleware

Yet another SQL logger, this time with color and tresholds. By default it will only print a summary line (total time, query count) unless one of the tresholds (total time, query count, individual query time) was exceeded. You may use LOG_COLORSQL_VERBOSE = True to get the raw SQL for all requests regardless of any configured tresholds. In either case the middleware will highlight problematic areas in yellow or red. If you don't like the colors you can either set your tresholds to really high values, edit the code, or use a different middleware. :-)

  • sql
  • middleware
  • log
Read More
Author: moe
  • 4
  • 13

3110 snippets posted so far.