Parse a string for [BBCode](http://en.wikipedia.org/wiki/Bbcode) and generate it to (X)HTML by using the [postmarkup libary](http://code.google.com/p/postmarkup/).
In your template for generating (X)HTML:
{% load bbcode %}
{{ value|bbcode }}
In your template for removing BBCode fragments:
{% load bbcode %}
{{ value|strip_bbcode }}
Sometimes you need to prevent concurrent access to update/calculate some properties right. Here is (MySQL) specific example to lock one table with new object manager functions.
when you deploy djangos apps, some servers have problems resolving the absolute path of some files (e.g: sqlite3 + lighttpd + apache), using the snippet above solves this issue :)
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.
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.)
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/).
The Django JSON encoder already extends the `simplejson` encoder a little; this extends it more and gives an example of how to go about further extension.
Hopefully `newserializers` (see the community aggregator today) will supercede this, but until then, it's useful.
Based on Snippet [766](http://www.djangosnippets.org/snippets/766/) but added syntax highlighting of the sql output via [pygments](http://pygments.org/). The sql output will also be wrapped at 120 characters by default (can be configured by changing WRAP). It degrades nicely if pygments is not installed. This will add quite some cpu-cycles just for printing debug messages so use with care.
Following is the rest of the original description by [simon](http://www.djangosnippets.org/users/simon/) (shamelessly copied):
Adds a hidden footer to the bottom of every text/html page containing a list of SQL queries executed and templates that were loaded (including their full filesystem path to help debug complex template loading scenarios).
To use, drop into a file called 'debug_middleware.py' on your Python path and add 'debug_middleware.DebugFooter' to your MIDDLEWARE_CLASSES setting.
Edit: Added the ability to set the height of the debug-box
A Django view to create an image gradient on the fly as a PNG file. The direction, size and colors of the gradient a specified in the filename and extracted by Django in the urls.py.
Example usage from CSS:
`background: url(/gradient-down-255,255,255-to-0,0,0-70-of-120.png) repeat-x;` creates a 70-pixel vertical gradient as background from white to gray. No static images needed. To modify, nothing but the CSS needs to be edited.
This is nothing fancy and hasn't much to do with django itself, I just searched for this information for quite a while and thought it may be useful for others.
If you use IE7 (and maybe IE6), it will block cookies in iframes, if the iframes content comes from another server (quite common, I think).
The P3P specification lets you declare your privacy settings in a format interpretable by browsers, essentially you can tell IE that you adhere to "don't be evil", and are allowed to handle cookies afterwards.
I don't think that makes much sense, but it seems that it is the only way to make IE accept cookies in iframes.
I had no idea that django made it that incredibly easy to "patch" the response-header, but it does! :)
Include in your code like this:
t=Timer()
Then use it like this:
t.tick('Some optional description')
It will output the time spent between the tick and the previous tick (or inception) and the total time spent since it began tracking time. Can be placed multiple times in a long segment of code. Can be used to break out the amount of time being spent on various parts of your code so you can focus on optimizing those sections.
Extension to the normal ManyToManyField to support default values.
Build for the following use case:
publish_on = ManyToManyFieldWithDefault(Site, verbose_name=_('publish on'), default=Site.objects.get_current)
Where with a plain ManyToManyField the default site will not be selected. The ManyToManyFieldWithDefault fixes this by automatically selecting the default value if no other selections are given.
When the field also have null=True and Blank=True it will not select the default !
A simple InlineModelAdmin class that enables you to edit models that are bound by the instance via a generic foreign key (`content_type`, `object_id` pair)
Use like:
class PlacementInlineOptions( generic.GenericTabularInline ):
model = Placement
extra = 2
ct_field_name = 'target_ct'
id_field_name = 'target_id'
Can be also found at #4667
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.