Adding this mixing to your existing class based views allows for outputting of queries into any registered serialzier format -- very handy for dynamic JS based GUI on the JSON format.
This generic view mixing was created on our last project which required a fancy JS based user experience and yet also needed to be accessible through non JS enabled browsers.
Usually I start an authentication app with this model.
Don't forget to set it up in the settings file
AUTH_PROFILE_MODULE = 'authentication.UserProfile'
Apply the `login_required` decorator to all the handlers in a class-based view that delegate to `cls.dispatch`.
Optional arguments:
* redirect_field_name = `REDIRECT_FIELD_NAME`
* login_url = `None`
See the documentation for the [`login_required`](https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator) method for more information about the keyword arguments.
Usage:
@LoginRequired
class MyListView (ListView):
...
This is http://djangosnippets.org/snippets/1376/ rewritten as a new class-style Loader, and slightly improved.
Allows you to reference templates like this:
app_label:some/template/name.html
This makes it possible to insert customizations at any point in a template hierarchy. For example, you could replace a block within the base admin template:
{% extends "admin:admin/base.html" %}
{% block breadcrumbs %}Custom Breadcrumbs-Style{% endblock %}
Loading templates by path
app.template_name -> app/templates/template_name.html
app.subdir.template_name -> app/templates/subdir/template_name.html
Usage:
append in settings.TEMPLATE_LOADERS
and using render_to('app.index', context)
This is a model that implements (most of) the python dictionary interface. Meaning, you can work with this model exactly like a python dictionary, and it handles querying the database for it's values, saving/deleting the helper objects, etc.
I wrote this originally when I needed to store an arbitrary dictionary in the database, and decided to work it up into a near-complete implementation of a dictionary.
In order to make sure that the dictionary is the most optimized possible, I have a static method that can be used for retrieval. Feel free to ignore it if you don't care about optimizing database queries.
Here's an example:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from binder.models import Dictionary
>>> d = Dictionary.getDict('Foobar')
>>> print d
{u'Foobar': u'omgbbq', u'HAHAHAH': u"who's afraid of a big, black, bat?"}
>>> d['pot'] = 'The kettle is black.'
>>> print d
{u'Foobar': u'omgbbq', u'pot': u'The kettle is black.', u'HAHAHAH': u"who's afraid of a big, black, bat?"}
>>> print d['pot']
The kettle is black.
>>> for k, v in d.iteritems():
... print k +":", v
...
Foobar: omgbbq
HAHAHAH: who's afraid of a big, black, bat?
pot: The kettle is black.
>>> print d.keys()
[u'Foobar', u'HAHAHAH', u'pot']
>>> print d.values()
[u'omgbbq', u"who's afraid of a big, black, bat?", u'The kettle is black.']
>>>
There's several more functions that I've implemented; check the code to see. (An interesting note: DictField saves immediately upon making a change, which is good to keep in mind in case that functionality isn't expected.)
Hope someone finds this useful. :)
--Chris
Sorl thumbs for the lazy.
**Usage:** {% thumb p.image "noimage.png" %}
*tags.py* goes into your templatetags directory.
*includes/thumb.html* goes into your templates directory.
[Fork it here.](https://gist.github.com/985439)
This code provides a mixin and decorator which, when used together, can provide advisory locking on model methods. It provides locking by using MySQL's advisory lock system. See the example at the bottom of the code.
This is a convenient and easy way to guarantee your model methods have exclusive access to a model instance.
The LockableObjects class requires a MySQL backend, but it could be modified to use other back-end locking systems.
The lock name generation in `LockableObject.get_lock_name()` could be altered to create much more complex locking schemes. Locking per-object, per-method for example..
Lock attempts have a timeout value of 45 seconds by default. If a timeout occurs, EnvironmentError is raised.
**See the bottom of the script for an example**
> **Instructions:**
* **1:** Place the code in locking.py somewhere in your path
* **2:** In your models.py (or any script with an object you want to lock):
`from locking import LockableObject, require_object_lock`
* **3:** In the model you want locking for, add the `LockableObject` mixin
* **4:** Decorate the method you want to be exclusively locked with `@require_object_lock`
Add this to your apache config:
`<Directory /path/to/media>
WSGIAccessScript /path/to/access.wsgi
</Directory>`
Save the snippet as access.wsgi. Set up the paths, and do some authorization checking.
The above snippet makes all of the settings.py variables accessible in templates. Add this to the context_processors.py file inside your app directory. After that add the below line to the TEMPLATE_CONTEXT_PROCESSORS in your settings.py.
'*app_name*.context_processors.access_to_settings'
I often need to filter my change_list by author but my User table is usually pretty crowded and adding the User FK to list_filter would end up with hundreds of user links in the sidebar. This snippets replace those hundreds of links by a simple HTML <input>.
These generic views extend default views so that they also do permission checking on per-object basis.
* detail, update and delete - check access for user
* create - create permissions for user on object
* list - narrow object list with permissions
Classes prefixed with Owned are example implementation where user has access to object if designed object attribute references him.
Example:
`create_article = OwnedCreateView.as_view(owner='creator', model=Article, form_class=ArticleForm, success_url='/articles/article/%(id)d')`
Syntax:
{% math <argument, ..> "expression" as var_name %}
Evaluates a math expression in the current context and saves the value into a variable with the given name.
"$<number>" is a placeholder in the math expression. It will be replaced by the value of the argument at index <number> - 1.
Arguments are static values or variables immediately after 'math' tag and before the expression (the third last token).
Example usage,
{% math a b "min($1, $2)" as result %}
{% math a|length b|length 3 "($1 + $2) % $3" as result %}
You're looking at the most-bookmarked snippets on the site; if you'd like to help useful snippets show up here, sign up for an account and you'll get your own bookmarks list.