Login

Top-rated snippets

Snippet List

Zope testing django layer

[zope.testing](http://pypi.python.org/pypi/zope.testing/) is a test framework and test runner, similar to the django test runner and nose. This snippet is a [Layer](http://pypi.python.org/pypi/zope.testing/3.5.1#layers) class which you can assign as a layer attribute of your test suite to initialise and clean up the django test environment appropriately and to reset the test database between tests. for example: tests/suite.py import unittest from zope.testing import doctest def test_suite(): suite = doctest.DocFileSuite("models.txt") suite.layer = DjangoLayer return suite runtests.py import os from zope.testing import testrunner os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' defaults = [ '--path', 'tests', '--tests-pattern', '^suite$', '-c' ] testrunner.run(defaults)

  • testing
  • tests
  • test
  • zope.testing
Read More

Cached lookup model mixin

This mixin is intended for small lookup-style models that contain mostly static data and referenced by foreign keys from many other places. A good example is a list of Payment options in an e-shop that is referenced from Orders and is hitting database `order.payment` at least one time for an order. The idea is to cache entire table in a dict in memory that will live for entire life of a whole process serving many requests. The downside is that you need to restart the server when a cached lookup table changes.

  • foreignkey
  • cache
  • lookup
  • parent
Read More

Autoescape Migration Helper

In the process of adapting to the new autoescaping thing, I've occasionally run into the sad situation where my development Django instance needs autoescape template tags in order to work, but when that code goes into production, I'm on a pre-autoescape Django revision. Hilarious hijinx ensue. This snippet will attempt to load the new safe and force_safe filters and the autoescape template tag - failing the imports, it'll safely do nothing. The effect is that if you write templates for post-autoescape, but you still need them to work in pre-autoescape, this'll prevent the new filters and tags from causing errors in your older Django instances.

  • autoescape
Read More

Debug-only static serving

A simple way to enable static serving while in development stage still - on release, simply set up the web server to serve the static content instead, and adjust `MEDIA_URL` accordingly.

  • static-serve
Read More

Hyperlink list filter

This is a simple filter that takes an object list and returns a comma-separated list of hyperlinks. I use it to display the list of tags in my blog entries. The function assumes the object has a `get_absolute_url()` method that returns the URL. In your template, write `{{ obj_list|hyperlink_list:"slug" }}` where `obj_list` is your object list and `"slug"` is the object's attribute that returns the link text.

  • filter
  • templatetag
  • links
  • template-tag
  • link
  • hyperlink
Read More

dumpdata/loaddata with MySQL and ForeignKeys

InnoDB tables within MySQL have no ability to defer reference checking until after a transaction is complete. This prevents most dumpdata/loaddata cycles unless the dump order falls so that referenced models are dumped before models that depend on them. This code uses [Ofer Faigon's](http://www.bitformation.com) topological sort to sort the models so that any models with a ForeignKey relationship are dumped after the models they reference. class Entry(models.Model): txt = .... class Comment(models.Model): entry = models.ForeignKey(Entry) This code will ensure that Entry always gets dumped before Comment. Fixtures are an important part of the django Unit Testing framework so I really needed to be able to test my more complicated models. **Caveats** 1. You use this snippet to dump the data and the built in manage.py loaddata to load the fixture output by this program. A similar solution could be applied to the XML processing on the loaddata side but this sufficed for my situations. 2. This code does not handle Circular or self-references. The loaddata for those needs to be much smarter.

  • mysql
  • loaddata
  • foreign-key
  • fixture
  • dumpdata
Read More

another render_to_response wrapper

Wrapper for render_to_response that allows you to pass in a optional preinitialized HttpResponse object. Helpful when you want to want to set cookies or just add some extra initialization to your HttpResponse. If no HttpResponse is passed in the normal render_to_response is called. It's called exactly like the normal render_to_response except that you can pass in a kwargs response pair if you wish. Like so: code render_response('index.html',{'aparam': val}, context_instance=RequestContext(request),response=my_response)

Read More

Easier tags with parameters as dictionary values

This is just an example, **NOT any particular tag**. I was just tiered in examining every bits in list. I converted list to dictionary for easier manipulation of parameters. You can use this keeping in mind syntax: {% tag_name 1_key 1_value 2_key 2_value %} and so on...

  • tag
Read More

Authenticate against a Windows domain controller

To activate, store this file as `mysite/winauth.py` and use in settings.conf: AUTHENTICATION_BACKENDS = ('mysite.winauth.DomainControllerAuthBackend',) Needs [pywin32 extensions](http://sourceforge.net/projects/pywin32/) installed (and obviously only runs on Windows).

  • authentication
  • domain
  • windows
  • controller
  • pdc
Read More

Little middleware that create a facebook user

**How to use**: 1. Install [**PyFacebook** package](http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial). 2. After make all steps in tutorial above, put this code in your app's models.py module (you maybe prefer split it and put the middleware class in some other file). 3. Put the FacebookUserMiddleware python-path in the MIDDLEWARE_CLASSES in your settings.py (after facebook.djangofb.FacebookMiddleware). You probably will add some fields to FacebookUser model class :)

  • middleware
  • user
  • facebook
Read More

BirthYearField

A form field to prompt for a year of birth with suitable sanity checks. Usage eg: yob = BirthYearField(label="What year were you born?")

  • form
  • field
  • year
  • birth
Read More

Pattern to integer list function

This function can be util for transform pattern strings like these to list: >>> pattern_to_list('42-45') [42, 43, 44, 45] >>> pattern_to_list('15,49-52') [15, 49, 50, 51, 52] >>> pattern_to_list('0-13') [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] You can use also the list to pattern function at [http://www.djangosnippets.org/snippets/496/](http://www.djangosnippets.org/snippets/496/)

  • list
  • integer
Read More

Cache decorator

You can use this cache all your functions' output, except dynamic things like connection.cursor.

  • django
  • cache
  • decorator
Read More
Author: xyb
  • 0
  • 9

Renderer decorator

You can use this as a decorator for your views, this way you can return a simple dictionary and the decorator will do the rest. **@TODO:** Automatically set the template based on the app/view request

  • shortcut
  • render
Read More

Check Size of Object in memcached

I've been working with a data set where a single object won't fit into memcached's 1 Mb slab limit. The two functions have been useful to me for debugging the size of the data structure once pickled, and if said pickled data structure is greater than 1 Mb. These functions assume CACHE_BACKEND is memcached, obviously.

  • memcache
  • cache
  • memcached
Read More

3110 snippets posted so far.