Login

All snippets written in Python

Snippet List

OrderField

OrderField for models from http://ianonpython.blogspot.com/2008/08/orderfield-for-django-models.html and updated to use a django aggregation function. This field sets a default value as an auto-increment of the maximum value of the field +1.

  • models
  • fields
  • field
  • order
  • orderfield
  • integerfield
Read More

Decorate Template Tag (In-Line include and extend with local context)

I had an issue with the django templating system, where by if I included several different files at the same level on one template.. and all the included templates extended the same base template. It would render the defined blocks for the first inclusion for all. i.e. everything in the parent that is being extended would be not updated for the subsequent inclusion. So, if anyone else has this problem. I have a solution that I sorta wanted for other reasons anyway. It's called a decorator tag, you can include and extend a template at the same time - in-line, with local context scoping so it only affects that tag. This is also a nice way to avoid creating .html files for simple extending purposes.

  • templatetags
  • extend
  • include
  • decorate
Read More

AntiSpamModelForm

A general AntiSpamModelForm using some tricks to prevent spam based on current [django.contrib.comments.forms](http://code.djangoproject.com/browser/django/trunk/django/contrib/comments/forms.py). It uses a timestamp, a security hash and a honeypot field. See [AntiSpamForm](http://www.djangosnippets.org/snippets/1925/) too.

  • forms
  • spam
  • form
  • antispam
Read More

Choices

This allows you to access the choices (and their respective values) you create as a dictionary. It works great within django and it allows you to reference the choices as a dictionary (CHOICES[CHOICE1]) instead of CHOICES[0][0]... it is a tuple... but I mean, come on... what if you change the order? If you need the tuple just call CHOICES.choices and it will return the standard tuple.

  • choice
  • choices
  • input
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

Override QuerySet.delete() (one way of preventing cascading deletes)

We needed to override the default QuerySet delete function to deal with a client problem that we were facing Yes This is monkey-patching, and probably bad practice but if anyone needs to conditionally override the cascading delete that django does at the application level from a queryset, this is how to do it

  • queryset
  • delete
  • monkey-patch
Read More

Model Hooks

Runs model methods on save, create, update, delete Similar to Rails hooks **Usage:** *in models.py* from myproject.hooks import connect_hooks class MyModel(models.Model): #... # only on first save of a newly created object def before_create(self): print self def after_create(self): print self # not on first save of a newly created object def before_update(self): print self def after_update(self): print self # any save, new object or update def before_save(self): print self def after_save(self): print self # delete, self is still available after delete def before_delete(self): print self def after_delete(self): print self **connect_hooks(MyModel)**

  • model
  • hooks
Read More

Anonymous required decorator

A decorator that allows the programmer to restrict access to some views only to non logged-in users. For instance, if an user in logged in, it should be denied access to views like /accounts/register or /accounts/login.

  • decorators
  • acl
Read More

jinja2 csrf_token extension

init env `env = Envoriment(extensions=('youproject.app.extensions.csrf_token'), loader=loader)` or see [http://www.djangosnippets.org/snippets/1844/] and in settings.py: `JINJA_EXTS=('jinja2.ext.i18n','youproject.app.extensions.csrf_token',)` use this extension in jinja2 template just like django template: `<form ...>{% csrf_token %}...</form>`

  • template
  • jinja2
  • csrf
Read More

simplified render_to_response with RequestContext

manything need to do with RequestContext, but it's too tedious. use `render_to_response("/my.html", {'key':value,},request)` instead of `render_to_response("/my.html", {'key':value,},new RequestContext(request)) ` and you can also use `render_to_response("/my.html", {'key':value,},new RequestContext(request))`

  • shortcuts
  • simplified
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

2956 snippets posted so far.