Expanded version of [snippet 715](http://www.djangosnippets.org/snippets/715/ "Django snippets: Simple View Middleware to allow a Prefilter") to be more flexible.
Updates:
* 2009-04-24: Multiple filters now work correctly
* 2009-03-22: Fixed bug
* 2009-02-03: Simplified process.
This blog post outlined how to get the user from the session key:
http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/
Unfortunately, it assumes DB-backed session and auth backends. This isn't required, so this snippet provides a backend-agnostic way to do the same thing.
>>> skey = 'ea0ed02d35d43aeaf20b3ef516f51396'
>>> user_from_session_key(skey)
<User: jeremyd>
While django provides the `django_admin.py cleanup` script, if sessions get out of control sometimes you have to go lower level to get everything cleaned up. If the problem gets out of hand and you hit the resource limits of the machine, it is very difficult to get anything done in the database.
Attached is SQL code which was used to cleanup 27GB of expired session data in 3h. Run it like this to make sure it runs to completion:
`nohup mysql --user=username --password=password --host=hostname database < delete_expired_sessions.sql`
nohup causes the script to run detached from a terminal, so if your session gets disconnected it will keep running.
Easy way to generate image thumbnails for your models. Works with any Storage Backend.
From: [http://code.google.com/p/django-thumbs/](http://code.google.com/p/django-thumbs/)
**Usage example:**
==============
photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(300,200),)
To retrieve image URL, exactly the same way as with ImageField:
my_object.photo.url
To retrieve thumbnails URL's just add the size to it:
my_object.photo.url_125x125
my_object.photo.url_300x200
Note: The 'sizes' attribute is not required. If you don't provide it,
ImageWithThumbsField will act as a normal ImageField
**How it works:**
=============
For each size in the 'sizes' atribute of the field it generates a
thumbnail with that size and stores it following this format:
available_filename.[width]x[height].extension
Where 'available_filename' is the available filename returned by the storage
backend for saving the original file.
Following the usage example above: For storing a file called "photo.jpg" it saves:
photo.jpg (original file)
photo.125x125.jpg (first thumbnail)
photo.300x200.jpg (second thumbnail)
With the default storage backend if photo.jpg already exists it will use these filenames:
photo_.jpg
photo_.125x125.jpg
photo_.300x200.jpg
**Note:** It assumes that if filename "any_filename.jpg" is available
filenames with this format "any_filename.[widht]x[height].jpg" will be available, too.
simple search with Q object you just pass a list of fields and the search string then it will come up with a object to use in a filter. This snippet is thanks to Julien Phalip
at [julienphalip.com](http://www.julienphalip.com/blog/2008/08/16/adding-search-django-site-snap/)
I updated [MarkdownTextField](http://www.djangosnippets.org/snippets/882/) to have some choices in markup. It currently support for Markdown, Textile, Plain Text, and Plain HTML. It will add `%s_html` for the complied HTML and `%s_markup_choices` for a drop down of markup choices.
Usage:
class MyModel(models.Model):
description = MarkupTextField()
Request-phase cache middleware that checks to make sure the Cache server is running. Starting it if it is not. This is run for every request, it checks to see if it can get a defined item out of the cache, if that fails it tries to set it. Failing that it decides the server is probably crashed, so goes though and attempts to connect to the server. Failing a connection it will launch a new server.
This is probably not useful on large scale multi server deployments as they likely have their own testing for when services crash, but I am using it in a shared hosting environment where I have to run my own copy of memcache manually and cannot setup proper services testing, so I use this to just make sure the cache server is still running.
This GeoDjango subclass substitutes in the Google Maps base layer instead of the default one provided by Open Street Map. Requires the [google.html](http://www.djangosnippets.org/snippets/1145/) and [google.js](http://www.djangosnippets.org/snippets/1146/) templates (must be placed in `gis/admin` somewhere in your template path).
Requires a Google Maps API key -- please abide by Google's [terms of service](http://code.google.com/apis/maps/terms.html).
Sample jQuery javascript to use this view:
$(function(){
$("#id_username, #id_password, #id_password2, #id_email").blur(function(){
var url = "/ajax/validate-registration-form/?field=" + this.name;
var field = this.name;
$.ajax({
url: url, data: $("#registration_form").serialize(),
type: "post", dataType: "json",
success: function (response){
if(response.valid)
{
$("#"+field+"_errors").html("Sounds good");
}
else
{
$("#"+field+"_errors").html(response.errors);
}
}
});
});
});
For each field you will have to put a div/span with id like fieldname_errors where the error message will be shown.
Sometimes it is desirable to use values like the primary key when naming `FileField` and `ImageField` files, but such values are only available after saving the model instance. This abstract class implements a two-phase save in order to make this case easy. See the example in the docstring.
Another solution would be to write a `save()` that requires `upload_to` to be a callable that checks for `instance.pk`, then calls it again after saving. However, this would require more work from the developer for simple cases.
This middleware redirects the request for yoursite.com/feed/whatever/onefeed to your feedburner *onefeed* feed.
Having
``FEEDBURNER = ('SomeName', ('blog', 'comments', 'tag1'))``
will use the feedburner feeds at
http://feedproxy.google.com/SomeName/blog
http://feedproxy.google.com/SomeName/comments
http://feedproxy.google.com/SomeName/tag/tag1
you can add more tags, or even intersection and union of them the same way
(thanks to piranha for the idea of a middleware)
**Update:** now it works for tags as well
The `Resource` class is a way of writing a Django view as a class. I've done this as part of an effort to write easier-to-understand RESTful apps, as this allows the grouping of similar views as different types of operation on a resource. Essentially, the solution goes something like this:
* Views have to be callables which return HttpResponse objects.
* The problem with views as classes is that calling a view class returns an instance of the view class, not HttpResponse.
* Solution: have the VC (view class) a subclass of HttpResponse. This way, 'calling' the class will return a HttpResponse instance.
The `Resource` class performs a dispatch on the request method, so that a resource can be retrieved, created/updated and deleted by writing 'get', 'put' and 'delete' methods on a subclass of `Resource`.
A general `Book` class shows how this might work for the case of 'books' in a system:
class Book(Resource):
def get(self, request, book_name):
book = myapp.models.Book.objects.get(name=book_name)
return render_to_response('book_template.html', {'book': book})
def put(self, request, book_name):
new_book, created = get_or_create(myapp.models.Book, name=book_name)
new_book.data = request.raw_post_data
if created:
return HttpResponse(status=201)
return HttpResponse(status=200)
def delete(self, request, book_name):
book = myapp.models.Book.objects.get(name=book_name)
book.delete()
return HttpResponse()
As you can see, classes can return responses, and these will be merged back into the returned response by the `Resource._update` method.
I needed a quick way to send e-mails to other people involved in a project when I committed code - so that designers would know that templatetag *x* was available (or fixed), etc - and am really fond of how [unfuddle](http://unfuddle.com/) handles their subversion notifications. This isn't nearly as polished as theirs, but I figured it was a good place to start.
Hope someone else finds this as handy as I have.
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.