Login

Most bookmarked snippets

Snippet List

Rate Limiting Decorator

This is a small and useful decorator that you can use to protect yourself from bad users or bots hitting your site.

  • security
  • cache-based-rate-limiting
  • protection
  • rate limiting
Read More

CheckboxSelectMultiple that renders in columns

This is a CheckboxSelectMultiple widget that will render its choices divided evenly into multiple ul elements that can be styled nicely into columns. Pass in a css class to the constructor to be assigned to the ul's. See also: http://code.djangoproject.com/ticket/9230

  • checkbox
  • columns
Read More

X-Sendfile static file serve view

This view has the same functionality as Django's builtin static view function but when the configuration option `USE_XSENDFILE = True` is specified in the settings it returns the absolute path of the file instead of its contents. This allows the mod_xsendfile module in Apache or Lighttpd to take care of efficiently serving the file while still allowing for Django to take care of other processing of the request, like access control or counting the amount of downloads.

  • static
  • xsendfile
Read More

Link raw_id_fields (both ForeignKeys and ManyToManyFields) to their change pages

**UPDATE: Now works in Django 1.4** Based on luc_j:s snippet (http://djangosnippets.org/snippets/2108/) to show values in ManyToManyFields in the admin. This snippets does that, but also links each value to its corresponding admin change page. To use, just set the raw_id_fields to the value you want, and let your form inherit from ImproveRawIdFieldsForm.

  • admin
  • widget
  • django-admin
  • raw_id_fields
  • ManyToManyField
  • ForeignKey
Read More

Decouple 'help_text' attribute from field definition

I found model definitions with large number of fields with long help_text unreadable and feel that help_text doesn't really belong to field definition. With this snippet help_text attributes can live outside field definitions in inner HelpText class so field definitions become shorter and more readable. Usage: from django.db import models import readable_models class MyModel(models.Model): __metaclass__ = readable_models.ModelBase name = models.CharField('Name', max_length=30) address = models.CharField('Address', max_length=255) # ... long list of fields class HelpText: name = 'The name ...' address = 'Example: <very verbose example is here>'

  • models
  • help_text
Read More

Twitter template tags and filters

A simple template filter for parsing tweets (linking @ replies, hashtages and standard URLs whilst stripping out links to yFrog and TwitPic images), and two simple tags for displaying the yFrog and TwitPic images linked to in tweets. If you put the snippet in a file called tweets.py, as long as it lives in an app's templatetags directory, you should be able to do the following (where `text` refers to the text of a tweet): {% load twitter %} <p>{{ text|tweet }}</p> {% yfrog_images text 1 'fancybox' %} {% twitpic_images text 1 'fancybox' %} The first argument in the two tags controls how many images to render. Set this to -1 for an unlimited number, per tweet. Thumbnail images are displayed, and you can specify the class that is applied to the `<a>` tags rendered. Here I've used 'fancybox', and I would normally include jQuery code to turn the images inside the `<a>` tags into lightboxes.

  • twitter
Read More

Drag and drop admin list items

Using jQuery UI (with Grappelli in use) to add "drag and drop" reordering of items in the admin list view. The model must have an "order" field to store the order value in.

  • admin
  • jquery
  • order
  • drag-and-drop
  • grappelli
  • ui
Read More

Current Page Middleware

This module provides a middleware that implements a mechanism to highlight a link pointing to the current URL. Every link on the rendered page matching the current URL will be highlighted with a 'current_page' CSS class. The name of the CSS class can be changed by setting `CURRENT_PAGE_CLASS` in the project settings. Originally done by Martin Pieuchot and Bruno Renié, thanks @davidbgk and @samueladam for improvements & optimizations.

  • middleware
  • current-page
Read More

Mobile Device Middleware

Middleware class that checks the user agent against a known list of strings found in mobile devices, and if matched it then tries to determine the name of the template being rendered based on the convention of having every view use a keyword arg called "template". It then adds "mobile" to the template name and if the mobile template exists, it will override the "template" arg for the view with the mobile template name.

  • middleware
  • template
  • mobile
Read More

Mobile browser detection middleware

This middleware adds a "is_mobile" (boolean) to the request object if the user's browser is a mobile browser (iPhone, Nokia, etc). **Example of use inside a view:** `request.is_mobile` **Example of use inside a template:** *You must activate the template processor "django.core.context_processors.request" in your settings. (see TEMPLATE_CONTEXT_PROCESSORS at djangoproject.com)* `{{ request.is_mobile }}`

  • middleware
  • detect
  • browser
  • detection
  • mobile
Read More

RML2PDF with Django

This is a django view that can return a PDF made using rml2pdf from reportlab. This RML is written with django templating system, to view the rml code and download a fully working version visit [reportlab](https://www.reportlab.com/software/documentation/sample-projects/rml-with-django/)

  • django
  • pdf
  • rml
  • reportlab
Read More

Output sql_queries in Firebug console when in debug mode

Add this code to the end of the `<body>` of your main template and it will print out all your SQL queries with timings in the Firebug console. This uses the "django.core.context_processors.debug" template context processor, which requires that DEBUG=True and that your IP address is listed in INTERNAL_IPS.

  • sql
  • debug
  • console
  • firebug
  • sql_queries
Read More

Multiple querysets

This is an upgrade of snippet [1103](http://www.djangosnippets.org/snippets/1103/). Exemplary usage: class Blog(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50) blog = models.ForeignKey(Blog) def __unicode__(self): return self.title class Meta: abstract=True class Article(Post): text = models.TextField() class Link(Post): url = models.URLField() blog = Blog(name="Exemplary blog") blog.save() Article(title="#1", text="Exemplary article 1", blog=blog).save() Article(title="#2", text="Exemplary article 2", blog=blog).save() Link(title="#3", url="http://exemplary.link.com/", blog=blog).save() qs1 = Article.objects.all() qs2 = Link.objects.all() qsseq = QuerySetSequence(qs1, qs2) # those all work also on IableSequence len(qsseq) len(QuerySetSequence(qs2, qs2)) qsseq[len(qs1)].title # this is QuerySetSequence specific qsseq.order_by('blog.name','-title') excluded_homo = qsseq.exclude(title__contains="3") # homogenic results - returns QuerySet type(excluded_homo) excluded_hetero = qsseq.exclude(title="#2") # heterogenic results - returns QuerySetSequence type(excluded_hetero) excluded_hetero.exists() You can implement more `QuerySet` API methods if needed. If full API is implemented it makes sense to also subclass the `QuerySet` class.

  • queryset
  • chain
  • iterable
  • indexable
Read More

3110 snippets posted so far.