Runs model methods on save, create, update, delete
Similar to Rails hooks
**Usage:**
*in models.py*
from myproject.hooks import connect_hooks
class MyModel(models.Model):
#...
# only on first save of a newly created object
def before_create(self): print self
def after_create(self): print self
# not on first save of a newly created object
def before_update(self): print self
def after_update(self): print self
# any save, new object or update
def before_save(self): print self
def after_save(self): print self
# delete, self is still available after delete
def before_delete(self): print self
def after_delete(self): print self
**connect_hooks(MyModel)**
A decorator that allows the programmer to restrict access to some views only to non logged-in users. For instance, if an user in logged in, it should be denied access to views like /accounts/register or /accounts/login.
init env
`env = Envoriment(extensions=('youproject.app.extensions.csrf_token'), loader=loader)`
or see [http://www.djangosnippets.org/snippets/1844/] and in settings.py:
`JINJA_EXTS=('jinja2.ext.i18n','youproject.app.extensions.csrf_token',)`
use this extension in jinja2 template just like django template:
`<form ...>{% csrf_token %}...</form>`
manything need to do with RequestContext, but it's too tedious.
use
`render_to_response("/my.html", {'key':value,},request)`
instead of
`render_to_response("/my.html", {'key':value,},new RequestContext(request)) `
and you can also use
`render_to_response("/my.html", {'key':value,},new RequestContext(request))`
it is an rewrite of [http://www.djangosnippets.org/snippets/74/]
in settings.py
AUTHENTICATION_BACKENDS = (
'yourproject.email-auth.EmailBackend',
)
Author: chris
I tried a few snippets of integrated jinja2 in django, which provided ?.render_to_string and ?.render_to_response in the way of jinja2. **But those snippets could not use the generic view**, because of the generic views is use default django template. so i write this snippet which could use generic view, and use the basic django.shortcuts.render_to_string, django.shortcuts.render_to_string.
#in yourproject/urls.py :
#install default environment is very simple
djangojinja2.install()
#install environment of specified Environment class
from jinja2.sandbox import SandboxedEnvironment
djangojinja2.install(SandboxedEnvironment)
#alternative you can install sepcified environment
env=Environment(...)
...
djangojinja2.install(env)
#something could be set in settings.py
TEMPLATE_DIRS = (path.join(path.dirname(__file__),"templates"),)
JINJA_GLOBALS=['myapp.myutil.foo',]
JINJA_FILTERS=['django.template.defaultfilters.date',]
JINJA_TESTS=('foo.mytest',)
JINJA_EXTS=['jinja2.ext.i18n']
#there is no change need for app.views
from django.shortcuts import render_to_response
def foo(request):
return render_to_response('/myjinja2.html',{'request':request})
test in django development version of r12026 , jinja2 2.2.1, python 2.5
The Django Admin site provides a "raw ID" feature for foreign keys that reference large tables. In the form view, the label of the referenced object will appear after the input. This snippet will make that label into a hyperlink that takes you to the form view for that object.
To use this snippet, copy base_site.html into your templates/admin directory (if you haven't already), and paste this code into that file somewhere after the 'extends "admin/base.html"' directive. If you are already using jQuery, you can remove the first script tag. If you are already extending "extrahead", just paste the script tag(s) into the block you have created.
[Documentation for raw_id_fields](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields)
This is an improvement on other ButtonAdmin implementations.
A few features : It allows you to specify whether button appears on change form or change list; whether the form is to be saved before the resulting function is called; whether the button should be displayed
Look at the bottom of the snippet for usage.
And make sure you admin urls are enabled using (r'^admin/', include(admin.site.urls)) instead of the old method
Passing datetimes from Python to a [YUI DataTable](http://developer.yahoo.com/yui/datatable/) via JSON served by [django-piston](http://bitbucket.org/jespern/django-piston/) turned out to be surprisingly rocky. This code actually works with ``YAHOO.lang.JSON.stringToDate`` (*not* ``YAHOO.util.DataSource.parseDate``) which cannot handle time zone specifiers other than "Z" or dates without timezones.
The YUI [DataSource](http://developer.yahoo.com/yui/datasource/) which uses this looks something like this - note that simply setting ``format:"date"`` does not work as that uses ``YAHOO.util.DataSource.parseDate``, which uses``Date.parse`` to do the actual conversion, which will involve browser-specific formats and as of this writing only Chrome's native ``Date`` can reliably parse ISO 8601 dates.
myDataSource.responseSchema = {
resultsList: '…',
fields: [
…
{
key: 'my_date_field',
parser: YAHOO.lang.JSON.stringToDate
},
],
…
};
Perhaps you don't want to drop a table, but you also want to do something faster than Model.objects.all().delete() but without resorting to raw SQL. This function, clear_tables, will call the sql_flush operation on a list of tables.
simple_tag is nice, but it would be useful if it had a "as variable" clause at the end. This little bit of code factors out the reusable parts and makes a tag almost as simple as simple_tag. Now you can create tags like the following:
{% some_function 1 2 as variable %}
{% some_function db person %}
To add a new function, just do:
register.tag("new_function",
make_tag(new_function))
(I think you have to take the quotes off a string.)
Most other methods I've seen for splitting an app's models across multiple files involve adding a couple lines to every model. This method factors out those duplicate lines into one place.
This snippet is for resolve the Django-PyAMF unicode problems, through the django force_unicode function called recursively, with a tuple of different charsets.
With this snippet, I made a set of admin actions for assigning `Quality` objects to `Package` objects.
The Django docs for [ModelAdmin.get_actions][1] explain the dictionary of tuples that is returned.
[1]: http://docs.djangoproject.com/en/1.1/ref/contrib/admin/actions/#django.contrib.admin.ModelAdmin.get_actions