Wraps specified URL patterns with login_required decorator. Allows you to quickly require login for an area of your site based only on a URL pattern.
Similar to [zbyte64's snippet](http://www.djangosnippets.org/snippets/966/)
If any cache keys you generate include user (staff or public) supplied data, they may: be too long, contain invalid characters (at least by memcache's standards), or both.
This helper will sub out any invalid characters and md5 the key if it's too long.
Additionally, it'll insert the CACHE_MIDDLEWARE_KEY_PREFIX from django.conf.settings for you. In your memcache instances are used by multiple applications (Django or otherwise) this can help ensure your keys are unique to that a particular app on a particular site.
This form widget allows you to just display data in a rendered form, not giving the user the opportunity to change it. The initial data will just be carried through the form and showed to the user.
In combination with snipped [1184](http://www.djangosnippets.org/snippets/1184/) you can make this even tamper safe. ;-)
A subclassed version of the standard Django Paginator (django.core.paginator.Paginator) that automatically caches pages as they are requested. Very useful if your object list is expensive to compute.
MIT licensed.
Works exactly like the standard "extends" tag but enables one to fallback on a default template. This tag is LIMITED, as it falls back to the next template with the same name that DOES NOT contain "extends_default" (does NOT simulate full inheritance, just a single level).
A partial solution to problems like http://jeffcroft.com/blog/2008/aug/05/default-templates-django/.
MIT licensed.
Django's serializer has some limitations which makes it a bit of a pain to use. Basically it will ignore any atributes that have been added to a model object.
The code below is for an alternative serializer. This version allows you select what attributes will be serialized on a per object basis. It also allows you to either serialize the data into json or xml.
The original json encoder was written by [Wolfram Kriesing](http://wolfram.kriesing.de/blog/)
Example Usage:
dumper = DataDumper()
dumper.selectObjectFields('class_name',[...fields...])
dumper.selectObjectFields('class_name',[...fields...])
dumper.dump(model_instance,'xml')
dumper.dump(model_instance,'json')
dumper.dump(queryset,'xml')
After a point the sql server becomes the bottleneck in lots of web application, and to scale, master-slave replication with single master, multiple slave is recommended. This setup with nginx can be used to accomplish traffic distribution between master and slave based on request method.
Inspired by [snippet 1126](http://www.djangosnippets.org/snippets/1126/), I thought I would post a module that stores crontab entries in a database, with a less powerful, but more end-user friendly API. ("twice a week starting on Sat 1 Dec 2007, 6:23am", instead of "23 6,18 * * *").
The crontab is synchronised when an entry is changed, and relevant environment variables, function name and arguments are provided. You might want to store this as an app called "scheduler" to match the imports.
Enjoy!
Provides an efficient means of looking up multiple related model instances for a range of objects by pre-filling the cache attribute used by `SingleRelatedObjectDescriptor` with either complete model instances or a dict containing only specified fields, looking up all required data with a single query.
Example usage:
C:\django_projects\soclone>django-admin.py shell
>>> from soclone.models import Question
>>> from soclone.views import populate_fk_caches
>>> from django.db import connection
>>> from django.contrib.auth.models import User
>>> q = Question.objects.get(id=1)
>>> a = list(q.answers.all())
>>> connection.queries = []
>>> populate_fk_caches(User, (
... ((q,), ('author', 'last_edited_by', 'closed_by')),
... (a, ('author', 'last_edited_by')),
... ),
... fields=('username', 'gravatar', 'reputation', 'gold', 'silver',
... 'bronze'))
>>> connection.queries
[{'time': '0.000', 'sql': u'SELECT "auth_user"."id", "auth_user"."username", "au
th_user"."gravatar", "auth_user"."reputation", "auth_user"."gold", "auth_user"."
silver", "auth_user"."bronze" FROM "auth_user" WHERE "auth_user"."id" IN (1, 2)'
}]
When using Python's logging module in a concurrent environment (e.g. mod_python), messages get dropped by the standard file-based handlers. The [SocketHandler](http://www.python.org/doc/2.5.2/lib/node414.html) allows you to send logging messages to a remote socket. This snippet provides code for listening for such messages and writing them out to a log file. The final log file is configured as a standard logging file-based handler.
Django provides a `get_or_create` helper method in the `models.Manager` class which looks up an object for the given `kwargs`, creating one if necessary. But sometime you need a method which updates the object with given `kwargs` or creates it if it's not found. This snippet provides the helper for that purpose.
Use the snippet like this:
from django.db import models
class PersonManager(models.Manager):
update_or_create = _update_or_create
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
city = models.CharField()
objects = PersonManager()
person, created, updated = Person.objects.update_or_create(first_name="John",
last_name="Smith", defaults=dict(city="London"))
The method returns a tuple of (`object`, `created`, `updated`), where `created` and `updated` are booleans specifying whether an `object` was created or updated respectively. Both `created` and `updated` are `false` if `object` is neither created nor updated (that is `object` has just been fetched "as is" from db). This happens if the update fails.
Jinja2 is an alternative template system that can be plugged into django.
It offers greator flexibility in presentation logic; if you find the django template system too restrictive, you should have a look at Jinja2
(The syntax is very similar).
In Jinja, you don't need costum tags (most of the time), because you can call functions and pass them parameters too!
The only problem is that you cannot "load" functions from the template, this "loading" must be done by the code that renders the template. Same goes for filters and tests.
If you need only two or three functions/filters, no problem, you can manually add them to the Environment object; but this method doesn't really scale with real-life webapps.
This module/snippet offers a solution by allowing the user to define application-specific functions and filters and load them into the jinja2 environment automatically.
Here's how to use this:
1. Install Jinja2 (for a quick & dirty installation, you can just put the jinja2 folder in a folder that's in PYTHONPATH)
2. Save this python module somewhere and call it something meaningful (I have it as jinja.py in my project directory)
3. Whenever you need to respond (an HttpResponse) with a template that's rendered by jinja, import this module and call `return jrespond( template_name, context )`
4. Any filters or functions you define in any of your applications will be readily available inside the template (see the documentation in code)
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.