Login

Most bookmarked snippets

Snippet List

Default URL handler

Default URL handler allows views to be loaded without defining them in the urls.py. Views will therefore be loaded based on the pattern of the browser url. For example http://host/app_name/view_name will load project_name.app_name.views.view_name. Though I would not used this in production, it can be used to speed-up development.

  • url
Read More

JSON Decimal encoder

Python json module or simplejson don't support Decimals out of the box. Here's an encoder that casts Decimals into floats and then displays them in desired format.

  • json
  • decimal
  • encoder
Read More

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

astimezone template tag

should probably be migrated to an inclusion tag to allow a source timezone that isn't the site specific TIME_ZONE. This code assumes that your database stores dates according to the django.conf.settings.TIME_ZONE variable. Yes.. this assumes that dates are stored in the database according to system time. On my systems the system time of a server is always UTC therefore avoiding problems with datetime (no tz info) columns in backend databases having no timezone information and stored according to the database or system timezone information. I find it a good practice to always use UTC for any stored information and always retrieve information as UTC and localize the date during display.

  • templatetag
  • datetime
  • timezone
  • pytz
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

RandomObjectManager

Manager Mixin to implement get_random() in your models. You can override get_objects to tune the queriset To use, define your class: class MyManager(models.Manager, RandomObjectManager): DEFAULT_NUMBER = 5 # I can change that def get_objects(self): return self.filter(active=True) # Only active models plz class MyModel(models.Model): active = models.BooleanField() objects = MyManager() Now you can do: MyModel.objects.get_random()

  • random
  • manager
Read More

ModelList class

This class makes easier the job of rendering lists of model instances in django templates. It's intended to mimic the behavior of the Model Forms in that it contains the code needed to render it as an HTML table and makes it easy to handle all the model lists from a single view (as it's usually done with the generic views for creating and updating model instances). It also supports pagination and provides hooks for subclassing and customizing the rendered fields, column titles and list order. Basic example: `class Account(Model):` `name = models.CharField(max_length=MAX_LENGTH)` `responsible = models.CharField(max_length=MAX_LENGTH)` `email = models.EmailField()` `class AccountModelList(ModelList):` `class Meta:` `model = Account` `fields = ['name', 'responsible'] #email won't get a column` The model list would be instantiated with something like: `model_list = AccountModelList(instances=account_queryset)` Then a table header can be rendered with model_list.as_table_header(), while the table rows can be rendered calling as_table() on each model_list.items element.

  • model
  • pagination
  • table
  • list
  • model list
  • order by
  • render table
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

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

login_required decorator that doesn't redirect

A login_required decorator that wraps the login view instead of redirecting to it. This prevents your site from leaking login information with HTTP status codes as explained [here](https://grepular.com/Abusing_HTTP_Status_Codes_to_Expose_Private_Information). This is the way Django's admin is protected, the difference being that it checks for is_active and is_staff instead of is_authenticated. With this decorators, users directly see a login form (no redirect), post it to LOGIN_URL and are redirected to the page they first tried to see.

  • redirect
  • login_required
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

Class-Based AJAX fallback view

If you're used to auto_render like I am (and think it's an awesome way to DRY code) and you want to support users with and without javascript enabled, this class is perfect. You will need to provide the format requested, either through adding "(\.format)?" at the end of the url or through some middleware, but once you've done so this class will take care of rendering through the given template for normal users, JSON or JSONP for AJAX users. From [fahhem.com](http://fahhem.com/) and [Recrec Labs](http://recreclabs.com/)

  • ajax
  • view
  • json
  • class
  • fallback
  • class-based
Read More

3110 snippets posted so far.