Login

All snippets written in Python

Snippet List

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

Deep package test runner

**NOTE: This is modified from 1.0's test runner and has only been tested on Django 1.0 + Python 2.5** This is a test runner that searches inside any app-level "tests" packages for django unit tests. Modules to be searched must have names that start with "test_" (this can be changed by modifying `get_multi_tests()`, [`mod.startswith('test_') and mod.endswith('.py')`]). It also allows for arbitrarily nested test packages, with no restrictions on naming, so you could have: myapp/ +- tests/ +- __init__.py +- test_set1.py +- category1/ +- __init__.py +- test_something.py +- subcat/ +- __init__.py +- test_foobar.py +- category2/ +- __init__.py +- test_other.py and "manage.py test myapp" would pick up tests in all four test_*.py test modules. Searching the modules in this way, instead of importing them all into the top-level `__init__.py`, allows you to have "name collisions" with TestCase names -- two modules can each have a TestFooBar class, and they will both be run. Unfortunately, this snippet doesn't allow you to specify a full path to a specific test case or test module ("manage.py test myapp.category1.test_something" and "manage.py test myapp.test_set1.TestFooBar" won't work); using "manage.py test myapp.TestFooBar" will search out all test cases named "TestFooBar" and run them. "manage.py test myapp.TestFooBar.test_baz" will work similarly, returning the test_baz method of each TestFooBar class. To use, put this code in "`testrunner.py`" in your project, and add `TEST_RUNNER = 'myproject.testrunner.run_tests'` to your `settings.py`.

  • tests
  • test-runner
  • package
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

Other approach of making middleware (by decorators)

Other approach of making middleware. Advantage of is to specify, which middleware is used for which view function and in what order. Middleware function gets all arguments, that are passed to view function. **Example usage** @RequestMiddleware def print_params_middleware(request, *args, **kwargs): print 'GET params:', request.GET @ResponseMiddleware def modify_headers_middleware(request, response, *args, **kwargs): response['Content-Type'] = 'text/html' @ExceptionMiddleware def catch_error_middleware(request, e, *args, **kwargs): return HttpResponse('catched error %s' % e ) @modify_headers_middleware @catch_error_middleware @print_params_middleware def some_view(request, *args, **kwargs): print 'someview' return HttpResponse()

  • middleware
  • decorator
  • exception
Read More

Truncate text to length up until the nearest space

This will truncate a long character based on the given length parameter. If the word is cut-off, it will return the string up until the next space. If there are no spaces in the next 5 characters, that should mean a very long word and we should truncate right away.

  • template
  • string
  • truncate
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

Server Side Cursors for Django's psycopg2 Backend

Based on discussion on [http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/](http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/) and [http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/](http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/) but instead implements them via extending the psycopg2 backend which allows you to use all of django's machinery without having to resort to using raw cursors. Usage: qs = Model.objects.all() with server_side_cursors(qs, itersize=100): for item in qs.iterator(): item.value if random_reason_to_break: break Setup: In your own project create the package hierarchy myproject.db.backends.postgresql_psycopg2 and place the code in base.py. In your settings.py set the database ENGINE to be 'myproject.db.backends.postgresql_psycopg2'. If you using south you'll have to let it know its a postgresql_psycopg2 backend by adding to SOUTH_DATABASE_ADAPTERS (see south documentation). Note: Make sure your using psycopg >= 2.4 for efficient named (server side) cursor iteration.

  • django
  • server
  • backend
  • cursors
  • named
  • psycopg2
  • side
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

Better Django Model Field Choices

Nice to name your constant multiple choice fields in models, this is one way of doing that. Sorry I haven't looked into existing alternatives. But this approach worked for me.

  • choice
  • choices
  • model
  • field
Read More

Get default form data

Given an unbound form, determine what data would be generated from POSTing the form unchanged. The goal is to end up with a dict such that, passed into another form constructor as its data kwarg, form.changed_data == [].

  • forms
  • widgets
Read More

shuffle templatetag

This is useful for randomizing an iterable of objects in place in a django template. Usage: {% load shuffle %} {# now some_list is ordered #} {% shuffle some_list %} {# now some_list is randomized #}

  • template-tag
  • iterable
  • shuffle
Read More

2955 snippets posted so far.