This snippet is used to monitor sphinx status via [django-sphinx](http://code.google.com/p/django-sphinx/).
It returns 0 (OK) or 2 (CRITICAL).
Remember to change this strings `ModelToMonitor` and `app_name`.
Usage :
`./manage your-controls-command --log`
If you try to load a template named filename.LANG.html it will try to load filename.de.html first, then filename.html afterwards (assuming that German is the currently selected language).
Usage: Put in a file named langtemplateloader.py under your project, and replace django's default filesystem loader with this in the TEMPLATE_LOADERS section of settings.py:
TEMPLATE_LOADERS = (
'myproject.langtemplateloader.load_template_source',
# 'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
'django.template.loaders.eggs.load_template_source',
)
This is an example how to dynamically import modules other than `models.py` from installed apps. It allows you to define the full module path just once in `INSTALLED_APPS` in the settings.
Using this technique makes it possible to write extensible and reusable apps as mentioned in [Abstract Models and Dynamicly Assigned Foreign Keys](http://djangotricks.blogspot.com/2009/02/abstract-models-and-dynamicly-assigned.html).
Probably, it would be great to have some helpers for doing this in django itself. For example:
from django.db import models
from django.utils import importlib
def import_installed(path):
"""
Imports a module from an installed app
>>> import_installed("myapp.forms")
<module 'myproject.apps.myapp.forms'>
"""
app_name, module = path.split(".", 1)
app = models.get_app(app_name)
return importlib.import_module(app.__name__[:-6] + module)
UPDATE: Reported as ticket [#10703](http://code.djangoproject.com/ticket/10703)
`dumpdata` without `MemoryErrors`, with progress notification. Most of the real work is done by snippets [1400](http://www.djangosnippets.org/snippets/1400/) and [1401](http://www.djangosnippets.org/snippets/1401/).
./manage.py dumpdata_stream --format=xml > big_dump.xml
This is basically the stock Django `dumpdata` with a few modifications. Django devs: it's hard to reuse parts of most Django management commands. A little refactoring could go a long way.
Call a function for each element in a queryset (actually, any list).
Features:
* stable memory usage (thanks to Django paginators)
* progress indicators
* wraps batches in transactions
* can take managers or even models (e.g., `Assertion.objects`)
* warns about `DEBUG`.
* handles failures of single items without dying in general.
* stable even if items are added or removed during processing (gets a list of ids at the start)
Returns a `Status` object, with the following interesting attributes
* `total`: number of items in the queryset
* `num_successful`: count of successful items
* `failed_ids`: list of ids of items that failed
** DEPRECATED**, use [django-reversetag @ github](http://github.com/ulope/django-reversetag/tree/master) instead.
If you want to be able to use context variables as argument for the "url" template tag this is for you.
Just put this code somwhere where it will be run early (like your app's _ _init_ _.py) and of you go.
Usage:
{% url name_of_view_or_variable arg1 arg2 %}
**NOTE:** This may possibly break your site!
Every view name that is passed to url will be tried to be resolved as a context variable first!
So if there is a variable coincidentally named like one of your views THEN IT WILL BREAK.
So far it works great for me, but keep an eye out for name clashes.
Wrote this some time ago when I couldn't find one already completed. Came up in the IRC channel so I decided to post it.
Easy enough to use.
`from ssldecorator import ssl_required`
`@ssl_required`
`def your_view(request):`
` ''' your code here '''`
You can place a variable in your settings.py to change the SSL domain (ie, if you have SSL running on secure.yourdomain.com instead of www.yourdomain.com)..
`SSL_DOMAIN = 'https://secure.yourdomain.com'`
Note: please include a proper URL. If https isn't used, the decorator will add it.
This is a simple modification to the standard transaction.commit_on_success decorator that is aware of existing transactions. If a managed transaction is already active then the wrapped function is called directly, assuming the active transaction will clean up as appropriate. Otherwise, a standard commit_on_success is performed.
I'm using this to wrap the save() method of models that manipulate other related models on save, e.g:
@nested_commit_on_success
def save(self):
super(MyClass,self).save()
for m in other_models:
self.fix_up_other_model(m)
m.save()
A management.py loading customized SQL feeding it raw to the database backend.
Just put it as `management.py` in your app and put whatever SQL you want run after syncdb in `app/sql/custom.backend_driver.sql`.
If the `backend_driver` is skipped the SQL will be loaded no matter database backend.
Since it is run after syncdb it will also be run for test.
For disabling autocomplete and security purpose, this snippet defines a CharField with a randomness name for each request of the form.
This is useful for turning off autocomplete for credit card input in all browsers, without breaking the xhtml validation.
* [https://wiki.mozilla.org/The_autocomplete_attribute_and_web_documents_using_XHTML#Security](https://wiki.mozilla.org/The_autocomplete_attribute_and_web_documents_using_XHTML#Security)
* [http://en.wikipedia.org/wiki/Cryptographic_nonce](http://en.wikipedia.org/wiki/Cryptographic_nonce)
This allows you to host your own URL shortening service for your site's internal urls. By adding this class as a Mixin to your models, any model with a get_absolute_url method will have a get_short_url method also, which either returns an existing redirect or creates a new one and returns that.
**Usage:**
Import the class above, add the mixin to your model declaration, and ensure you have declared a get_absolute_url method.
`class MyModel = (models.Model, ShortURL):`
**Pre-requisites:**
You must have the django.contrib.redirects app installed, and you must be using the RedirectFallbackMiddleware as a middleware class.
**Settings:**
Change the settings in the code above or set them in your settings.py file
SHORTURL_CHARS: the characters to use when creating a shorturl
SHORTURL_CHAR_NO = the number of characters to use in a shorturl
SHORTURL_APPEND_SLASH = whether to append a slash to the end of the shorturl redirect
**Notes:**
The default settings will give you about 17 million different unique short URLs, reducing the number of characters used to 4 will give you 600,000 or so. That's enough that collisions will be quite rare for sites of a few thousand pages (collisions just result in a urls being generated until an unused combination is found) but if you've got a big site you'll probably want to explore a more robust solution with a proper hash function.
[http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/](http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/)
This is my first snipplet. With this, you can manage your models in console using ncurses Dialog or Whiptail or XDialog. Models are auto-discovered. You can browse, edit, add and delete models. Bugreports very welcome.
Simple debug middleware that uses [pycallgraph](http://pycallgraph.slowchop.com) to get a visual representation of the call graph, including number of calls and execution times.
Usage:
1. Replace *myapp* in the snippet with the name of your application and or adjust include and exclude according to your needs
2. Add CallgraphMiddleware to your middlewares in settings.py
3. Append ?prof to any URL in your application to trigger the callgraph creation
Each callgraph cerated will be named callgraph-*timestamp*.png. This is because multiple callgraphs will be created when a re-direction occurs for example.
This recipe uses a modified version of Robin Dunn's fcgi.py module that adapts fcgi to wsgi and lets you run Django under mod_fcgid. One good
thing about mod_fcgid is that it does all process management for you,
which makes this setup quite straightforward.
Also, since Robin's module works both in a cgi and fcgi context,
switching a django site between cgi and fastcgi is a one-liner in the
apache config, without any changes to python code or django config. CGI may be handy for development, since it loads all code (including changed code) on every request, yet lets you work in an environment that resembles production.
Apache configuration examples are found in the comment at the beginning of the python module.
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.