Login

Most bookmarked snippets

Snippet List

Google map on admin address field

Who never wished to have valid address data by showing a little google map with a marker near the address input text ? Using js only it gets quite easy.

  • gmap
  • address
  • googlemap
Read More

Memory efficient Django Queryset Iterator

While checking up on some cronjobs at [YouTellMe](http://www.youtellme.nl/) we had some problems with large cronjobs that took way too much memory. Since Django normally loads all objects into it's memory when iterating over a queryset (even with .iterator, although in that case it's not Django holding it in it's memory, but your database client) I needed a solution that chunks the querysets so they're only keeping a small subset in memory. Example on how to use it: `my_queryset = queryset_iterator(MyItem.objects.all()) for item in my_queryset: item.do_something()` [More info on my blog](http://www.mellowmorning.com/2010/03/03/django-query-set-iterator-for-really-large-querysets/)

  • queryset
  • iterator
  • memory
  • gc
Read More

Strip Google Analytics cookies for caching middleware purposes

You may notice that using Google Analytics's 'urchin' with the CacheMiddleware and SessionMiddleware or AuthenticationMiddleware middleware classes means that nothing is ever cached. Google Analytics updates its cookies with every page view, and the Auth/Session middlewares add cookies to the caching engine's 'Vary' list. This means every page view is given a unique cache key. This middleware class will remove urchin's '__utmX' cookies from the request object before it hits the caching middleware. Put it at the top of your MIDDLEWARE_CLASSES in settings.py. nf / [email protected]

  • middleware
  • cache
  • google
  • analytics
Read More
Author: nf
  • 7
  • 13

A view for downloading attachment

This view snippet is a helper for implementing file download handlers. There is a standard to encode Unicode filenames properly, but many browsers have different protocols. The default encoding is assumed to be UTF-8.

  • view
  • attachment
  • send-file
  • download-file
  • mimetype
Read More

Absolute URL Templatetag

The {% url %} templatetag is awesome sometimes it is useful to get the full blown URL with the domain name - for instance for links in emails. The **{% absurl %}** templatetag mirrors the behaviour of {% url %} but inserts absolute URLs with the domain of the current Site object. Usage: {% absurl viewname %} >>> http://www.example.org/my/view/

  • url
  • templatetags
  • absolute
  • uri
Read More

Smart i18n date diff (twitter like)

This snippet display a human readable date diff. You give it the your date in parameter and the diff with datetime.datetime.now() is returned. The diff must be positive to be more accurate (future dates are not supported) Usage: {{ status.created_at|date_diff }} Will give something like: less than 1 minute ago 13 minutes ago 1 hour ago etc. Based on [Fuzzy Date Diff Template Filter](http://www.djangosnippets.org/snippets/1347/)

  • datetime
  • i18n
  • date
  • diff
Read More

Load template from specific app

You can use this template loader if you want to use template specifically from one app. Useful mainly in overriding admin templates - just make your own `admin/change_form.html` and have it extend `admin:admin/change_form.html` withou creating any symlinking or copying django admin's templates to alternate location. Part of the [ella project](http://www.ellaproject.cz/).

  • template
  • loader
  • app
Read More

Signal to post new saved objects to Twitter

Post new saved objects to Twitter. **Example:** from django.db import models class MyModel(models.Model): text = models.CharField(max_length=255) link = models.CharField(max_length=255) def __unicode__(self): return u'%s' % self.text def get_absolute_url(self): return self.link # the following method is optional def get_twitter_message(self): return u'my-custom-twitter-message: %s - %s' % (self.text, self.link) models.signals.post_save.connect(post_to_twitter, sender=MyModel)

  • twitter
  • signal
Read More

Full-Text Searchable Models

A drop-in module to allow for full-text searchable models with very little effort. Tested with PostgreSQL 8.3, but should work on earlier versions with the tsearch2 module installed.

  • models
  • search
  • full-text
  • tsearch2
Read More

ImageWithThumbsField

Easy way to generate image thumbnails for your models. Works with any Storage Backend. From: [http://code.google.com/p/django-thumbs/](http://code.google.com/p/django-thumbs/) **Usage example:** ============== photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(300,200),) To retrieve image URL, exactly the same way as with ImageField: my_object.photo.url To retrieve thumbnails URL's just add the size to it: my_object.photo.url_125x125 my_object.photo.url_300x200 Note: The 'sizes' attribute is not required. If you don't provide it, ImageWithThumbsField will act as a normal ImageField **How it works:** ============= For each size in the 'sizes' atribute of the field it generates a thumbnail with that size and stores it following this format: available_filename.[width]x[height].extension Where 'available_filename' is the available filename returned by the storage backend for saving the original file. Following the usage example above: For storing a file called "photo.jpg" it saves: photo.jpg (original file) photo.125x125.jpg (first thumbnail) photo.300x200.jpg (second thumbnail) With the default storage backend if photo.jpg already exists it will use these filenames: photo_.jpg photo_.125x125.jpg photo_.300x200.jpg **Note:** It assumes that if filename "any_filename.jpg" is available filenames with this format "any_filename.[widht]x[height].jpg" will be available, too.

  • image
  • models
  • fields
  • thumbnail
  • field
  • thumbnails
  • thumbs
Read More

FieldAccessForm (per-field user access for forms derived from models)

=== version 2 === > Parts of this code are based off of source from *davidcramer* on #django and I'd like to thank him for his assistance. Example: # forms.py ... class ForumPostForm(FieldAccessForm): class Meta: model = ForumPost class FieldAccess: moderator = FieldAccessLevel( lambda user, instance: user.get_profile().is_moderator, enable = ('approve', 'delete', 'edit') member = FieldAccessLevel( lambda user, instance: user.is_active, enable = ('edit',), exclude = ('approve', 'delete') ... # template ... <form action="" method="POST"> <table> {% for field in form %} <tr><th>{{ field.label_tag }}</th><td> {% if not field.field.disabled %} {{ field }} {% else %} {{ field.field.value }} {% endif %} </td></tr> {% endfor %} </table> <p><input type="submit" value="Update" /></p> </form> ... This class will grant or deny access to individual fields according to simple rules. The first argument must be a user object, but otherwise, this class is instantiated the same as a ModelForm. To utilize this code, inherit your form from FieldAccessForm, and create an inner class on your form called FieldAccess. Variables added to this inner class must have the same structure as that provided by the FieldAccessLevel class, which defines an access level, and the fields which apply to that access level. FieldAccessLevel takes as it's first argument a callable rule that validates this access level. That rule will be called with two arguments: 'user' (current user requesting access) and 'instance' (model instance in question). The keyword arguments to FieldAccessLevel are field groups which are used to determine which fields on this form are to be enabled and/or excluded, when the current user matches this access level. The term exclude indicates fields which are not to be rendered in the form at all. Any fields not grouped in either 'enable' or 'exclude' will be disabled by default. Superusers are always assumed to have full access. Otherwise, if a field is not specified with the FieldAccess inner class, then it is disabled by default. In other words, all users (except superusers) are denied access to all fields, unless they are specifically given access on a per-field basis. It is worth mentioning that multiple access levels can apply simultaneously, giving a user access to fields from all levels for which he matches the rule. If a user is denied access to a field, then the widget for that field is flagged as disabled and readonly. The field is also given two new attributes: a boolean 'disabled', and a 'value' containing the instanced model field. These two attributes allow a template author to have great control over the display of the form. For example, she may render the plain text value of a field instead of the disabled widget. The FieldAccess inner class also allows one to conditionally exclude fields from being rendered by the form. These exclusions operate very similarly to the standard Meta exclude option, except that they apply only to the access level in question. Note: The FieldAccess inner class may be used on both the form and the model; however, generally it makes more sense on the form. If you do use FieldAccess on both the form and model, be aware that both definitions will apply simultaneously. All access levels for which the user passes the rule will be processed, regardless of whether they were found on the form or the model.

  • form
  • field
  • permission
  • modelform
  • access
Read More

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

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

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

3110 snippets posted so far.