Login

Most bookmarked snippets

Snippet List

DRY template rendering decorator update

Based fully on [snippet 1929](http://www.djangosnippets.org/snippets/1929/) **The update is:** It checks to see the view returns an instance of HttpResponse and returns that rather than trying to render it. This allows you to return something like `HttpResponseRedirect('/')`, or use a normal `render_to_response` to use a different template. *Also updates cleandict as per comment on original snippet* In this case the 'render_template' decorator assumes there is a myview.html template. this keeps things simple and you DRY. Hope it helps.

  • template
  • decorator
  • rendering
  • dry
Read More

External service Test Client

The inbuilt test client can be used to only test single domain applications ie no support for supplying absolute URLs. But there are cases where one might like to test against URL rewrites, external domains/services like OpenID, OAuth etc. This client has an external dependency on httplib2, to maintain the sessions (cookie-based). The API is exactly similar to the inbuilt test client. >>> from client import TestClient >>> c = TestClient() >>> resp = c.get("http://www.google.com/") >>> resp.status_code 200 **Note**: Unlike the built-in test client, this test client cannot access the template and context attributes from the response even if testing a local application.

  • test
  • client
  • httplib2
Read More

Forcing Right-Hand Rule (Counter Clockwise) Polygons in GeoDjango for Google Earth / KML

According to the KML Specification, Polygons must be oriented according to the Right-Hand Rule (Counter Clockwise orientation) for them to display correctly in Google Earth. Since not all Polygons are defined according to the Right-Hand Rule, you can use this code to orient them correctly when using GeoDjango. Thanks goes to jbronn of #geodjango on irc.freenode.net for this!

  • geodjango
  • kml
  • google-earth
  • polygon
  • orientation
  • right-hand-rule
Read More

register.tag as a class decorator

Defining a custom template tag consists of three parts: a compiling function, a rendering `Node` subclass and a tag registration with `register.tag()`. The latter can be used as a (function) decorator on the compiling function, simplifying things into two parts. A neat fact is that `register.tag()` can actually be used as a class decorator in Python 2.6+ to condense all steps into the `Node` subclass. The compiling function simply becomes the `__init__()`. Below are two variants of the 'current_time' tag example from the Django docs: the first passing an explicit tag name and the second using the class name instead.

  • template-tags
  • class-decorator
Read More

decorators for creating paramaterized decorators and easy monkeypatching

as with all things related to monkeypatching, the caveat is to use things like these for good, and not for evil. I wrote these decorators because I did not want to rewrite all of [PyAWS](http://github.com/IanLewis/pyaws) -- instead I use these to add some standard/useful methods to the Bag collection that PyAWS uses internally. AN EXAMPLE: class PatchMyMonkey: pass @monkeypatch(PatchMyMonkey) def throwfecesat(self, who="nobody"): print "Throwing Feces At: %s" % who @monkeypatch(PatchMyMonkey) def nicoderm(self, why="no reason"): print "Trying To Quit Because: %s" % why return {'why':str(why)} trampstamp = PatchMyMonkey() trampstamp.throwfecesat(who="another monkey") print trampstamp.nicoderm(why="cigarettes are pricey") A LESS SILLY EXAMPLE: from pyaws import ecs @monkeypatch(ecs.Bag, fname='get') def get(self, param, *args, **kw): return self.__dict__.get(param, *args, **kw) @monkeypatch(ecs.Bag, fname='clearurls') def clearurls(self, *args, **kw): for k, v in self.__dict__.items(): if isinstance(self.__dict__[k], ecs.Bag): self.__dict__[k].clearurls(*args, **kw) if type(v) == type([]): [ii.clearurls() for ii in self.__dict__[k]] if type(v) == type(u''): if self.__dict__[k].count(u'http://') > 0: self.__dict__[k] = "<URL>" (amazon's URLs are extremely long, and can muddle your test/log output, hence that last function.) based on sample code from [here](http://pypi.python.org/pypi/decorator) and [here](http://mail.python.org/pipermail/python-dev/2008-January/076194.html).

  • decorator
  • monkeypatch
  • decoratordecorator
  • functionalprogramming
  • usewithcare
Read More

Anticollate? Disinterleave?

This is yet another partitioning filter, but I wanted to be able to distribute my objects across two columns, and have them read from left to right, top to bottom. So if n = 2 this would return every other object from a queryset. With gratitude to the author of snippet 6.

  • filter
  • partitioning
  • every-other
Read More

Simple Paginator Function

This is very simple Paginator function built over Django's Paginator. Just pass following:- 1. request object 2. object list - This is a list of object you want to paginate 3. per page - how many items you need per_page 4. paginator_range - Specify how many links you want on either side of current page link. Refer to Paginator reference [here](http://docs.djangoproject.com/en/dev/topics/pagination/)

  • paginator
  • page-range
Read More

Extended db cache backend with 'filter() / LIKE' support (and now scheduled cache clean!)

Because the db caching doesn't support atomic operations, it was unsafe to store a list of 'keys' in a single key. So, rather than store the list, I just append each key with a specific tag, and then filter for it later. This means I don't need to worry too much about atomic usage with lists (i.e. queued requests). However - I still can think of many instances where I would need atomic usage, so I will probably implement this later on down the line. Hopefully, the atomic modifications will be accepted by the core devs. This also contains threaded cache cleaning, which means you no longer need to rely on requests to clean the cache (which would have potentially slowed the user query down), and will remove any cache entries past their expiry date every 3 minutes. Enjoy! Cal

  • filter
  • cache
  • db
  • backend
  • like
Read More

Dynamic Test Loading

Ok... this is really a hack. But I love it. I hate setting up all of my test cases into suites, and making sure that I remember to add them each time I add a new python file... annoying! This allows me to have a tests package and then just add python files and packages to that test package (mirroring my app setup). Each of the files are then dynamically imported and every test case is automatically executed. If you don't want one to execute, add it to the ignore list. If you add 'views' to the ignore list, it will ignore all views, otherwise you would have to specify 'package.views' if it is in a package. So... in short this is a bit ghetto, but it saves me a lot of time just setting up all my tests... now I can just write them! Hope it's useful to someone. Greg

  • dynamic
  • unittest
  • load
  • test
  • loader
  • loading
  • unit
Read More

integrated jinja2 which could use generic view ,my djangojinja2.py

I tried a few snippets of integrated jinja2 in django, which provided ?.render_to_string and ?.render_to_response in the way of jinja2. **But those snippets could not use the generic view**, because of the generic views is use default django template. so i write this snippet which could use generic view, and use the basic django.shortcuts.render_to_string, django.shortcuts.render_to_string. #in yourproject/urls.py : #install default environment is very simple djangojinja2.install() #install environment of specified Environment class from jinja2.sandbox import SandboxedEnvironment djangojinja2.install(SandboxedEnvironment) #alternative you can install sepcified environment env=Environment(...) ... djangojinja2.install(env) #something could be set in settings.py TEMPLATE_DIRS = (path.join(path.dirname(__file__),"templates"),) JINJA_GLOBALS=['myapp.myutil.foo',] JINJA_FILTERS=['django.template.defaultfilters.date',] JINJA_TESTS=('foo.mytest',) JINJA_EXTS=['jinja2.ext.i18n'] #there is no change need for app.views from django.shortcuts import render_to_response def foo(request): return render_to_response('/myjinja2.html',{'request':request}) test in django development version of r12026 , jinja2 2.2.1, python 2.5

  • template
  • generic
  • jinja2
  • generic-view
Read More

a simple tag with context

simple_tag is nice, but it would be useful if it had a "as variable" clause at the end. This little bit of code factors out the reusable parts and makes a tag almost as simple as simple_tag. Now you can create tags like the following: {% some_function 1 2 as variable %} {% some_function db person %} To add a new function, just do: register.tag("new_function", make_tag(new_function)) (I think you have to take the quotes off a string.)

  • context
  • simple_tag
  • as
Read More

3110 snippets posted so far.