An example of how to select the "default" database based on the request URL instead of the model. The basic idea is that the middleware `process_view` (or `process_request`) function sets some context from the URL into thread local storage, and `process_response` deletes it. In between, any database operation will call the router, which checks for this context and returns an appropriate database alias.
In this snippet, it's assumed that any view in the system with a `cfg` keyword argument passed to it from the urlconf may be routed to a separate database. Take this urlconf for example:
`url( r'^(?P<cfg>\w+)/account/$', 'views.account' )`
The middleware and router will select a database whose alias is `<cfg>`, or "default" if none is listed in `settings.DATABASES`, all completely transparent to the view itself.
- multidb database router url
The code was placed inside a helper file without using a class. The Django validator was not designed to work with validator classes, it would appear, so retrieving the value from the field proved to be a hassle. Just create a helper file, import it on your model, and use the validator in the standard way, as such:
cnpj = models.CharField(unique=True, max_length=14, validators=[validate_CNPJ])
cpf = models.CharField(unique=True, max_length=14, validators=[validate_CPF])
- model
- validation
- cnpj
- cpf
Ticket [#2070](http://code.djangoproject.com/ticket/2070) allows you to create your own file upload handlers. Here's an example handler that tracks a file's upload so you might display a progress meter after form submission.
The snippet has two parts, the upload handler which tracks progress, and an upload_progress view used to report back to the browser.
The upload handler uses [django's cache framework](http://www.djangoproject.com/documentation/cache/#the-low-level-cache-api) to store the data, which can then be retrieved by the view to send back to the browser.
Note: Your form's http post request must have a query parameter (X-Progress-ID) sent along with it, which should contain a unique key to identify the upload. That key will also be sent with your ajax requests to the upload_progress view to retrieve the progress data.
Setup: place the UploadProgressCachedHandler anywhere you like on the python path, and add to your settings.py:
from django.conf import global_settings
FILE_UPLOAD_HANDLERS = ('path.to.UploadProgressCachedHandler', ) + \
global_settings.FILE_UPLOAD_HANDLERS
Set up the upload_progress view in any of your apps along with a corresponding entry in your urlconf.
Here's some javascript example code to make the ajax requests and display the progress meter: <http://www.djangosnippets.org/snippets/679/>
.