Login

All snippets

Snippet List

Model manager with row caching

RowCacheManager is a model manager that will try to fetch any 'get' (i.e., single-row) requests from the cache. ModelWithCaching is an abstract base model that does some extra work that you'll probably want if you're using the RowCacheManager. So to use this code, you just need to do two things: First, set objects=RowCacheManager() in your model definition, then inherit from ModelWithCaching if you want the invalidation for free. If you are unusually brave, use the metaclass for ModelWithCaching and you won't even need the "objects=RowCacheManager()" line.

  • get
  • model
  • manager
  • model-inheritance
  • caching
Read More

Model with random ID

An abstract model base class that gives your models a random base-32 string ID. This can be useful in many ways. Requires a Django version recent enough to support model inheritance.

  • model
  • random
  • model-inheritance
  • id
  • primary-key
Read More

401 HttpResponse

This is a HTTP response is use in my application when I want to return a 401. It's pretty simple, but effective for my needs.

  • 401
  • httpresponse
Read More

RecaptchaForm

There already is a [snippet on here](http://www.djangosnippets.org/snippets/433/) that shows how to use reCAPTCHA with Django, but being the lazya-- that I am, I wanted the form to: * display the captcha when as_table is used * handle captcha validation for me So RecaptchaForm does the trick. Just subclass from it and voila, your form will include reCAPTCHA validation. Other than that, you need to * be on Django trunk version (or use clean_data instead of cleaned_data for 0.96) * set RECAPTCHA_PRIVATE_KEY and RECAPTCHA_PUBLIC_KEY in your settings.py * make sure that the [captcha module](http://pypi.python.org/pypi/recaptcha-client) is available somewhere (i.e. that "import captcha" works)

  • captcha
  • recaptcha
Read More

Disable fields in oldforms admin using jQuery

This snippet shows how to disable fields in a edit page in the oldforms admin using jquery. The idea is to add the javascript to the edit page using the `js` attribute of the model's `Admin` class. In this case jQuery and a custom javascript file are added. The javascript sets the `disabled` attribute of the `name` field to `true` as soon as the document is ready.

  • admin
  • jquery
  • oldforms
  • disable
Read More

Custom optional abstract base attributes

I needed an abstract base class that can add attributes to the child classes based on the child's name. The attributes had to be implicit, but overridable, so all derived classes would get them by default, but they could be easily overriden in the child definition. So, the code code I came up with basically consists of a customized metaclass used by the abstract model.

  • model
  • abstract
Read More
Author: tie
  • 0
  • 2

Creating MySQL Alter table commands for Foreign Keys

When using mysql the sql that is generated by syncdb doesn't create the foreign key relationship in all cases. This code will run through a file called create_table.sql in which you store all your create sql statements ( use "python manage.py sqlall app1 app2 > create_table.sql" ) and outputs all the neccesary alter table scripts that add the foreign key. Its not 100% proof since the generated names can end up being more than 40 characters. Need to work on that. I have [written](http://vidyanand.wordpress.com/2008/06/16/is-it-a-mysql-or-django-fault/) about it a little more in detail.

  • mysql
  • foreign-keys
Read More

Templatetag startswith + message tuned

Template: `<div id="messageBox_{{ forloop.counter0 }}" style="border:1px solid #ccc;background-color:white" onclick="document.getElementById ('messageBox_{{ forloop.counter0 }}').style.display = 'none';"> {% ifstartswith message "#ok#" %} <font color="green"> {% endifstartswith %} {% ifstartswith message "#error#" %} <font color="red"> {% endifstartswith %} {{ message|cut:"#ok#"|cut:"#error#" }} </font> </div>` In a view you can now do something like that: ` request.user.message_set.create(message="#ok#Hello User, this is a ok message!")`

  • template
  • templatetags
  • message
Read More

Use django-admin.py instead of manage.py

A lot of people new to Django don't realize that `manage.py` is [just a wrapper](http://www.djangoproject.com/documentation/django-admin/) around the `django-admin.py` script installed with Django and isn't needed. (You may need to symlink `django-admin.py` to someplace in your system `PATH` such as `/usr/local/bin`.) The most important thing it does is to set your `PYTHONPATH` and `DJANGO_SETTINGS_MODULE` environment variables before calling `django-admin.py`. Those same settings are needed when you move your site on to a production server like Apache, so it is important to know how they work. This shell function sets those variables for you. Put it in your `.zshrc` or bash startup script. It works for both the monolithic project style and the lightweight app style of Django development [[1](http://www.pointy-stick.com/blog/2007/11/09/django-tip-developing-without-projects/)], [[2](http://www.b-list.org/weblog/2007/nov/09/projects/)]. This function isn't fancy; drop a comment if you have an improvement. Written for zsh and tested with bash 3.1.17.

  • bash
  • shell
  • zsh
Read More

Ajax API class

Whip up an AJAX API for your site in a jiffy: class MySite(AJAXApi): @AJAXApi.export def hello(request): return {'content': self.get_content()} def get_content(self): return 'Hello, world!' urlpatterns += MySite().url_patterns() (the example needs the JSON encoding middleware of [snippet 803](http://www.djangosnippets.org/snippets/803/) to work.) The secret is that bound instance methods are callable too, so work as views. (Most Django people only use functions, or sometimes classes with `__call__`, as view functions.) You get implicit type dispatch off that `self` object. So you could subclass `MySite`, change `get_content`, and still use the same `hello` method. See (django-webapp)[http://code.google.com/p/django-webapp/] for a REST-ish Resource class using this same idea. You can clearly do better than my `func_to_view`, and also make a better decorator than `exported` (so you can actually say `@exported('name') def function()` etc.). This is more of a proof of concept that should work for most people. Caveat: I've changed a few things since I last really tested this. (psst, this also works for non-AJAX views too.)

  • ajax
  • api
  • instance-view
Read More

JSON encoding middleware

Makes it really easy to return JSON from your views: just return a dict. (Also from [django-webapp](http://code.google.com/p/django-webapp/).)

  • middleware
  • serialize
  • json
  • encode
  • encoding
  • serializer
Read More

Ajax error handling

Handles exceptions from AJAX code, giving more useful errors and tracebacks. (By the way, all these new snippets are extracts from [django-webapp](http://code.google.com/p/django-webapp/).) This exact code is not well tested, but it's refactored from some code we use in production.

  • middleware
  • ajax
  • error
  • exception
Read More

Another JsonResponse

Another `JsonResponse` class, including comment wrapping. Extensions to other kinds of CSRF protection should be obvious. Good explanations of why such protections are needed would make excellent comments on this snippet. This depends on the `json_encode` method in [snippet 800](http://www.djangosnippets.org/snippets/800/).

  • json
  • response
  • jsonresponse
Read More

3109 snippets posted so far.