Login

All snippets

Snippet List

improved generic foreign key manager

This is an improvement on [snippet 984](http://www.djangosnippets.org/snippets/984/). Read it's description and [this blog post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) for good explanations of the problem this solves. Unlike snippet 984, this version is able to handle multiple generic foreign keys, generic foreign keys with nonstandard ct_field and fk_field names, and avoids unnecessary lookups to the ContentType table. To use, just assign an instance of GFKManager as the objects attribute of a model that has generic foreign keys. Then: MyModelWithGFKs.objects.filter(...).fetch_generic_relations() The generic related items will be bulk-fetched to minimize the number of queries.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

Session Wizard

This a wizard tool similar to the one in django.contrib.formtools, but it uses a session. I hope to eventually get this into shape and contribute it to the formtools package, but for right now, here it is. The wizard steps are broken into 2 categories: Show Form and Submit Form Each category has it's own hooks for manipulating the process, for instance you can short-circuit a process_submit_form() and go straight to done() via a return from preprocess_submit_form(). Sorry for the lack of documentation on this. Here's an example urls.py entry : `(r'^estimate/(?P<page0>\d+)/$', EstimateWizard([EstimateCustomer, EstimateJob, EstimateRoom]))` where EstimateCustomer, Job, and Room are Form classes and EstimateWizard extends SessionFormWizard

  • session
  • form
  • wizard
Read More

SignedForm: CSRF-protect forms with a hidden token field

This form subclass helps protect against cross-site request forgery by adding a hidden field named `csrf_token` to forms. The form must be initialized with the request as a keyword argument, both with and without POST data: my_form = MySignedForm(request=request) ... my_form = MySignedForm(request.POST, request=request) Upon validation, a `PermissionDenied` exception will be raised if forgery is detected. If any security details have been overlooked in this recipe, please leave a comment.

  • forms
  • csrf
Read More

FormHandler - take the legwork out of form processing

Take the legwork out of processing forms. Most people have a very specific structure to how they process forms in views. If the request method is "GET", then some HTML (with the blank form) is rendered. If the method is "POST", then the form is validated. If the form is invalid, some other HTML is displayed. If valid, the data is submitted and processed in some way. In order to do this all in a much nicer way, simply subclass `FormHandler`, define three methods (`valid`, `invalid` and `unbound`), point to the form, and use the subclass as your view in the URLconf.

  • views
  • forms
  • view
  • form
  • view-as-a-class
  • formhandler
  • form-handler
Read More

A Django image thumbnail filter

I've gotten this code originally from Dan Fairs. I've edited it a bit to make it do what I wanted it to do. I've sent a mail and the original can be considered public domain code. The same is true for this

  • image
  • resize
Read More

Resource

The `Resource` class is a way of writing a Django view as a class. I've done this as part of an effort to write easier-to-understand RESTful apps, as this allows the grouping of similar views as different types of operation on a resource. Essentially, the solution goes something like this: * Views have to be callables which return HttpResponse objects. * The problem with views as classes is that calling a view class returns an instance of the view class, not HttpResponse. * Solution: have the VC (view class) a subclass of HttpResponse. This way, 'calling' the class will return a HttpResponse instance. The `Resource` class performs a dispatch on the request method, so that a resource can be retrieved, created/updated and deleted by writing 'get', 'put' and 'delete' methods on a subclass of `Resource`. A general `Book` class shows how this might work for the case of 'books' in a system: class Book(Resource): def get(self, request, book_name): book = myapp.models.Book.objects.get(name=book_name) return render_to_response('book_template.html', {'book': book}) def put(self, request, book_name): new_book, created = get_or_create(myapp.models.Book, name=book_name) new_book.data = request.raw_post_data if created: return HttpResponse(status=201) return HttpResponse(status=200) def delete(self, request, book_name): book = myapp.models.Book.objects.get(name=book_name) book.delete() return HttpResponse() As you can see, classes can return responses, and these will be merged back into the returned response by the `Resource._update` method.

  • rest
  • resource
  • view-class
  • view-as-a-class
Read More

RestView - class for creating a view that dispatches based on request.method

Sometimes it's useful to dispatch to a different view method based on request.method - e.g. when building RESTful APIs where GET, PUT and DELETE all use different code paths. RestView is an extremely simple class-based generic view which (although it's a stretch to even call it that) which provides a simple mechanism for dividing up view logic based on the HTTP method.

  • rest
  • view
  • classbasedgenericviews
Read More

Unfuddle-style post-commit emails - tied to a specific Django project.

I needed a quick way to send e-mails to other people involved in a project when I committed code - so that designers would know that templatetag *x* was available (or fixed), etc - and am really fond of how [unfuddle](http://unfuddle.com/) handles their subversion notifications. This isn't nearly as polished as theirs, but I figured it was a good place to start. Hope someone else finds this as handy as I have.

  • email
  • svn
  • subversion
  • post-commit
Read More

collectmedia command: Copy or link media files from installed apps

This management command discovers media files from all `INSTALLED_APPS` (or the apps you specify) and copies or links them to `MEDIA_ROOT`. Put this code in a file like so: yourapp/management/commands/collectmedia.py ...and don't forget the necessary `__init__.py` files. This command includes an interactive mode (`-i` or `--interactive`) and a dry run mode (`-n` or `--dry-run`) for previewing what will happen. See `manage.py help collectmedia` for more options.

  • media
  • management
  • command
Read More

EncryptField

I was trying to create a custom field to use the mysql encrypt() function on some data I wanted to store in the DB. initcrash on IRC pointed me to [this code](https://tracpub.yaco.es/cmsutils/browser/trunk/db/fields.py?rev=66) which I butchered as best as my little brain could. Amazingly enough I got it working (thanks to a couple answers from initcrash). If anyone can clean this up that would be great. I'm also trying to figure out how I can a) create password reset link in the admin interface for this field without displaying the field or b) decrypt it so that the password field is pre-populated with the decrypted password. Otherwise it is submitting the encrypted string as a new password. Anyways, I'm only a week or two into Django with no python experience so any suggestions are very welcome. Hope this helps someone!

  • mysql
  • crypt
  • custom-field
  • encrypt()
Read More

Link Media Command

A command for manage.py which scans through installed applications the way admin.autodiscover does, just looking for media folders. It then creates a symbolic link to the media under MEDIA_ROOT/app_name. Usage: save in an apps management/commands folder and run with "python manage.py linkmedia" Only works on *nix systems, but there should be an equivilent way to do this with windows using .lnk files.

  • manage.py
  • media
  • command
  • symlink
Read More

Cookie based flash errors and notices (a la Rails)

This is a light-weight flash implementation. Instead of hitting the database it uses cookies. The messages are shown to the user only once, after that the cookies are deleted. I tested it on Google App Engine, but it should work on vanilla Django as well, there's no GAE specific code. To set up, add `"path.to.flash.Middleware"` to the `MIDDLEWARE_CLASSES` list. Also add `'path.to.flash.context_processor'` to the `TEMPLATE_CONTEXT_PROCESSORS` list. In your views, import and call `flash_error(msg)` and `flash_notice(msg)` passing the message that you want to show. In your base template use this mark up: {% if flash.notice %} <div id="flash_notice"> <p>{{ flash.notice }}</p> </div> {% endif %} {% if flash.error %} <div id="flash_error"> <p>{{ flash.error }}</p> </div> {% endif %} And finally, add this to your CSS file changing colours as necessary: #flash_error { margin-top: 30px; padding: 20px; background-color: #FFCCCC; border: solid 1px #CC0000; } #flash_notice { margin-top: 30px; padding: 20px; background-color: #CCFFCC; border: solid 1px #00CC00; } #flash_error p, #flash_notice p { margin: 0px; } Please comment if you notice any FUs. I'm new to Django and will appreciate any feedback.

  • error
  • flash
  • rails
  • notification
  • notice
Read More

3110 snippets posted so far.