Login

All snippets written in Python

Snippet List

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

Email Attachment

Django documentation is lacking in giving an example for sending an email with attachment. Hopefully this code helps those who are trying to send email with attachments

  • email
  • attachment
  • fileinput
Read More
Author: sri
  • 2
  • 12

Frequently used tags/filters for Jinja2

Some frequently used filters and global functions: **url** - same as django url tag **nbspize** - replace all spaces with nbsp **get_lang** - get current language code **timesince** - converted django timesince tag **timeuntil** - converted django timeuntil tag **truncate** - tag that truncates text call it with an str argument like '20c' or '5w', where the number provides the count and c stands for charachters and w stands for words

  • tags
  • jinja
  • jinja2
Read More

Jinja2 Django integration

Integration of django and Jinja2. Just import render_to_response from this file and you are ready. This file automatically adds template search path from yout TEMPLATE_DIRS and from each installed application. You can also use several variables in your settings.py to add filters, tests and global functions to the default context. This can be done by using JINJA_GLOBALS, JINJA_FILTERS and JINJA_TEST e.g. `JINJA_FILTERS = ( 'myapp.filters.myfilter', 'myapp.filters.myfilter2', )`

  • templates
  • jinja
  • jinja2
Read More

Timedelta Database Field

This subclass of django.models.Field stores a python datetime.timedelta object as an integer column in the database. It includes a TimedeltaFormField for editing it through djangos admin interface. Feedback welcome. 2011-04-20: TimedeltaField can now be (de)serialized. Tested with JSON. 2009-11-23: `_has_changed()` added. Before form.changed_data contained timedelta FormFields, even if nothing changed.

  • datetime
  • timedelta
  • dbfield
Read More

CheckedField

Here's a snippet to pair an arbitrary form Field type (the "target field") with a checkbox. If the checkbox is not selected, the cleaned_data value for the field will be None. If the checkbox is selected, it will return the target field's cleaned value.

  • checkbox
  • forms
  • combining
Read More

DRY custom ModelAdmin.list_display methods with a decorator

If you add a lot of custom `ModelAdmin` methods to `list_display` like I do, you know it can require a lot of repetition. Notice how adding 'checkbox' to `list_display` requires typing the method name 4 times: class ExampleAdmin(admin.ModelAdmin): list_display = ['checkbox', '__str__'] def checkbox(self, object): return '<input type="checkbox" value="%s"/>' % object.pk checkbox.short_description = mark_safe('&#x2713;') checkbox.allow_tags = True Using this decorator, the name only needs to be typed once: class ExampleAdmin(admin.ModelAdmin): list_display = ['__str__'] @add(list_display, mark_safe('&#x2713;'), 0, allow_tags=True) def checkbox(self, object): return '<input type="checkbox" value="%s"/>' % object.pk

  • admin
  • modeladmin
  • list_display
Read More

2955 snippets posted so far.