Login

All snippets written in Python

2956 snippets

Snippet List

Workaround Firefox bug 553888

Firefox transparently follows redirects when AJAX calls return 3xx code. And it drops additional headers, X-Requested-With among them. Server treats redirected HTTP requested as non-AJAX. JS libraries has nothing to do here. At 16.03.11 bug https://bugzilla.mozilla.org/show_bug.cgi?id=553888 has status "NEW" being reported at 21.03.10. Workaround is following: - in process_response(): if request.is_ajax() and response has status_code 3xx then put response["Location"] to session, otherwise unset session stored value (if it is there). - in process_request(): if not request.is_ajax() and request.path equals to stored session value then monkeypatch request.is_ajax() return True (before any views come into play). This results in smooth transparent redirects in Firefox, all treated as AJAX calls.

  • ajax
  • redirect
  • headers
Read More

Finding related objects for instances in a queryset

When deleting objects in Django's admin interface, it lists other objects which would be deleted and asks for confirmation. This snippet does the same programmatically. The snippet works in Django 1.3 (more specifically, revision 14507 or later). It uses Django internals which are not a part of the public API, so this might not work with future versions. Usage: `polls/models.py`: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) def __unicode__(self): return '%s %s' % (self.poll, self.choice) `$ ./manage.py shell` >>> from polls.models import Poll, Choice >>> from datetime import datetime >>> from pprint import pprint >>> poll1 = Poll.objects.create(question='Me?') >>> Choice.objects.create(poll=poll1, choice='Yes') >>> Choice.objects.create(poll=poll1, choice='No') >>> poll2 = Poll.objects.create(question='Really?') >>> Choice.objects.create(poll=poll2, choice='Yes') >>> Choice.objects.create(poll=poll2, choice='No') >>> pprint(get_related(Poll.objects.all())) {<class 'polls.models.Poll'>: [<Poll: Me?>, <Poll: Really?>], <class 'polls.models.Choice'>: [<Choice: Me? Yes>, <Choice: Me? No>, <Choice: Really? Yes>, <Choice: Really? No>]}

  • db
  • orm
  • related
Read More

Keep Me Logged In for Django

Very simple middleware to implement "remember me" functionality. Updates the session once per day to keep user logged.

  • django
  • session
  • keep
  • logged
  • middlware
Read More

restrict user access to modeladmin via metaclass

* Include `__metaclass__ = user_lock` to your ModelAdmin class * Add `__target__ = path_to_user_field` somewhere in the ModelAdmin * done! `__target__` is what will be used in the `filter` call. examples `'user'` or `'author'` or `'message__user'` e.t.c. The result of `__target__` is the field that is then checked against `request.user`

  • admin
  • user
  • restrict
  • model-admin
Read More

currency filter without using locale

This snippet is a combination of the existing currency snippets I found and some modifications to use your own settings without the need to have the locale installed on the system. You can define in settings.py: DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' CURRENCY_SYMBOL = u'€' With the above settings, using `{{ 1234.30|currency }}` on a template would result in `€1.234,30`

  • template
  • filter
  • currency
Read More

Group sequence into rows and columns for a TABLE

Two template tag filters that can be used to create a table from a sequence. <table> {% for row in object_list|groupby_columns:3 %} <tr> {% for obj in row %} <td>{{ obj }}</td> {% endfor %} </tr> {% endfor %} </table> The example above would create a table where items read from top to bottom, left to right, in 3 columns. "Empty" cells are added to the sequence by the filter so that your rows balance.

  • filter
  • templatetag
  • table
  • groupby
Read More

IP Authorization Decorator with IP list

Improved version of http://djangosnippets.org/snippets/2205/ Example simple code: ` from django.http import HttpResponse IP_LIST = ['192.168.101.100', '192.168.101.220', '127.0.0.1', '127.0.1.1'] @ip_auth(IP_LIST) def get_parameter(request,name): parameter = get_object_or_404(Parameter,short_name=short_name) return HttpResponse(parameter.value) `

  • IP
  • Authorization
  • Decorator
Read More

Compact list_filter with counter

This is an extension of the fantastic snippet "Compact list_filter" written by **onlinehero**. Follow his instructions for the installation. My version add the number of filtered objects beside the label of the filters defined by the list_filter property.

  • admin-interface
  • compact
  • list_filter
Read More

Django Number Input

This will give you a <input type='number'> field. This is helpful when you want to use HTML5 for newer browsers. Older browsers will just interpret this as <input type='text'>

  • django
  • django-forms
  • input-types
Read More

SQL Log Middleware - with multiple databases

This is an improvement of [joshua](http://djangosnippets.org/users/joshua/)'s [SQL Log Middleware](http://djangosnippets.org/snippets/61/). If you have more than one database connection, then all queries are logged, grouped by connection. If a connection has no queries, then it's not shown.

  • sql
  • middleware
  • log
  • multiple-databases
Read More

Google Analytics noscript tracking

Method which gets a chunk of HTML to perform standard Google Analytics tracking as well as a noscript version. Very useful for finding out what percentage of your users do not have JavaScript support. This is Python port of the PHP example here: [http://andrescholten.net/google-analytics-zonder-javascript/](http://andrescholten.net/google-analytics-zonder-javascript/) To use, you need to put the following into your settings file: GOOGLE_ANALYTICS_ID = 'UA-1234567-1' GOOGLE_ANALYTICS_DOMAIN = 'example.com'

  • google-analytics
  • noscript
Read More

Latest tweets Templatetag

Based on [http://djangosnippets.org/snippets/1615/](http://djangosnippets.org/snippets/1615/) Added tweets cache. Cache time is configurable through project settings: TWITTER_TIMEOUT=300. Default time is 300 seconds = 5 minutes. This improve performance by reducing the twitter api queries interval.

  • templatetag
  • twitter
  • social
Read More