Login

All snippets written in Python

Snippet List

Get stories by category and some date range

Removed for now... Not sure where to share new Ellington snippets due to the gray-area of it being proprietary. It's an awesome package but it's hard to find any good help with Django 91 code. Good luck ellingtoners!

  • date
  • stories
  • category
Read More

direct to template from a subdir

I needed a way to quickly get a direction of html pages templated such that another person could drop new templates in to a subdirectory and without modifying urls.py or views.py get them up and being displayed. Now, the direct_to_template view provided django.views.generic.simple can sort of do this with a urlpattern like: `url(r'^(?P<template>.*\.html)$', direct_to_template)` But that means your templates, no matter what level in the url hierarchy they are reached at, have to be defined at the root of a template directory. I wanted them retrieved from a specific subdirectory instead so I could provide a little wall for them. Hence this snippet. To use you would have url pattern that looked like: `url(r'^foo/(?P<template>.*\.html)$', direct_to_template, {'subdir' : 'subdir/'}),` Which will template any url that matches <parent url>/foo/bar.html for any 'bar'. The problem is if this is a sub-url pattern match this is going to look for the template "bar.html" when we may actually want it to get the template "<parent url>/foo/bar.html"

  • templating
  • wildcard
  • subdir
Read More

Google Analytics Templatetag

This template tag allows easy inclusion of google analytics script. If Google changes the script in the future, it remains easy to update the template tag with the the new code. This script is tested against Django 1.0 trunk Oct 9 2008. **Readme** After signing up for a Google Analytics account for your domain, define ANALYTICS_ID = "UA-XXXXXXX-X" in your settings.py with the supplied code. Include {% load analytics %} at the top of your base.html and {% analytics %} tag at just before the closing 'body' tag of the base template. Make a template to hold the analytics script. templates/analytics/analytics_html

  • templatetag
  • google-analytics
  • django-1.0
Read More

Prefill ForeignKey caches

Provides an efficient means of looking up multiple related model instances for a range of objects by pre-filling the cache attribute used by `SingleRelatedObjectDescriptor` with either complete model instances or a dict containing only specified fields, looking up all required data with a single query. Example usage: C:\django_projects\soclone>django-admin.py shell >>> from soclone.models import Question >>> from soclone.views import populate_fk_caches >>> from django.db import connection >>> from django.contrib.auth.models import User >>> q = Question.objects.get(id=1) >>> a = list(q.answers.all()) >>> connection.queries = [] >>> populate_fk_caches(User, ( ... ((q,), ('author', 'last_edited_by', 'closed_by')), ... (a, ('author', 'last_edited_by')), ... ), ... fields=('username', 'gravatar', 'reputation', 'gold', 'silver', ... 'bronze')) >>> connection.queries [{'time': '0.000', 'sql': u'SELECT "auth_user"."id", "auth_user"."username", "au th_user"."gravatar", "auth_user"."reputation", "auth_user"."gold", "auth_user"." silver", "auth_user"."bronze" FROM "auth_user" WHERE "auth_user"."id" IN (1, 2)' }]

  • foreignkey
  • cache
  • prefill
Read More

Twisted protocol for receiving logging module messages over a socket

When using Python's logging module in a concurrent environment (e.g. mod_python), messages get dropped by the standard file-based handlers. The [SocketHandler](http://www.python.org/doc/2.5.2/lib/node414.html) allows you to send logging messages to a remote socket. This snippet provides code for listening for such messages and writing them out to a log file. The final log file is configured as a standard logging file-based handler.

  • logging
  • twisted
Read More

Convert numbers in USA notation to brazilian notation

**This is the converter, just put it as a filter and call it with a float number.** * So, if you have a template variable **{{ my_number }}** that is "3096.44". * It will convert to "3.096,44" using the filter **{{ my_number|numBR }}**.

  • convert
  • float
  • usa
  • br
  • brazil
Read More

update_or_create

Django provides a `get_or_create` helper method in the `models.Manager` class which looks up an object for the given `kwargs`, creating one if necessary. But sometime you need a method which updates the object with given `kwargs` or creates it if it's not found. This snippet provides the helper for that purpose. Use the snippet like this: from django.db import models class PersonManager(models.Manager): update_or_create = _update_or_create class Person(models.Model): first_name = models.CharField() last_name = models.CharField() city = models.CharField() objects = PersonManager() person, created, updated = Person.objects.update_or_create(first_name="John", last_name="Smith", defaults=dict(city="London")) The method returns a tuple of (`object`, `created`, `updated`), where `created` and `updated` are booleans specifying whether an `object` was created or updated respectively. Both `created` and `updated` are `false` if `object` is neither created nor updated (that is `object` has just been fetched "as is" from db). This happens if the update fails.

  • model
  • helper
  • update
  • create
Read More

Jinja2 integration + application specific functions/filters/tests

Jinja2 is an alternative template system that can be plugged into django. It offers greator flexibility in presentation logic; if you find the django template system too restrictive, you should have a look at Jinja2 (The syntax is very similar). In Jinja, you don't need costum tags (most of the time), because you can call functions and pass them parameters too! The only problem is that you cannot "load" functions from the template, this "loading" must be done by the code that renders the template. Same goes for filters and tests. If you need only two or three functions/filters, no problem, you can manually add them to the Environment object; but this method doesn't really scale with real-life webapps. This module/snippet offers a solution by allowing the user to define application-specific functions and filters and load them into the jinja2 environment automatically. Here's how to use this: 1. Install Jinja2 (for a quick & dirty installation, you can just put the jinja2 folder in a folder that's in PYTHONPATH) 2. Save this python module somewhere and call it something meaningful (I have it as jinja.py in my project directory) 3. Whenever you need to respond (an HttpResponse) with a template that's rendered by jinja, import this module and call `return jrespond( template_name, context )` 4. Any filters or functions you define in any of your applications will be readily available inside the template (see the documentation in code)

  • template
  • templates
  • jinja
  • template-tags
  • jinja2
Read More

Session-backed FormWizard

A rewrite of the django.contrib.formtools.FormWizard class to be session-based instead of saving state in hidden form variables. It started out as a simple port of the standard FormWizard class, and much of the original behavior was unchanged because I wanted to limit the scope of the "rewrite". Along the way I think I made it a bit more OO, and a bit more flexible, but there are still warts. I threw this code up here before I was completely happy with it just to take part in the discussion around [this ticket][http://code.djangoproject.com/ticket/9200 "Django Ticket #9200]. There's certainly a few things that the patch on that ticket does that I'd like to incorporate into my Wizard, whenever time allows.

  • forms
  • session
  • wizard
  • formtools
Read More

2955 snippets posted so far.