This example shows how you can easily limit the objects in the admin by specifying which Manager the admin should use. I haven't seen this documented anywhere (perhaps I've missed it), but it's proven extremely useful to me.
The example here will limit objects to those that are attached to the current Site, but you can use any Manager you want (for example, a Manager that shows only published Articles).
Finally -- not that I'm suggesting this -- but you *could* combine this with the ThreadLocals trick to show only objects that have been created by that user.
I like to keep all local settings files in my versioning repository. The way I differentiate between them is by querying the hostname of the local machine. I've got a host_settings folder with local settings files. Notice that the local settings file names go by a convention where '.' is replaced with underscores.
Example: host_settings/local_machine_tld.py
Based on the discussion at Empty Thoughts (http://blog.michaeltrier.com/2007/8/6/age-in-years-calculation) I built a quick and dirty custom filter.
Save this as a file in your "templatetags" folder. I called mine "calculate_age.py" and then in your template "{% load calculate_age %}" then use it, "{{ object.birthdate|age }}"
You need htmldoc, rst2html, the Python Imaging Libraray, BeautfiulSoup
and spoon.
The Debian/Ubuntu-packages are called htmldoc, python-docutils, python-imaging and python-beautifulsoup
You can get spoon.py http://beautifulspoon.googlecode.com/svn/trunk/spoon.py
To create the pdf files you have to call the script from django_src/docs
Here is an example output: http://henning.cco-ev.de/django/essential.pdf
the trick resides in `field.field.required`. The intuitive way of testing this in the templates is to access `field.required`. But it's not the good one. Enjoy!
[Found via Django users Google Groups](http://groups.google.com/group/django-users/browse_thread/thread/ce83f74fb1156b4b/0df36947de16a071?lnk=gst&q=required+field#0df36947de16a071)
This script will reload apache when any modifications are detected in a folder - useful only if the development server or mod_python's reload does not suit your needs for testing. It requires Linux 2.6.13+, Python 2.5, and the [development version of pyinotify](http://seb.dbzteam.com/pages/pyinotify-dev.html).
Replaces <code> blocks with syntax highlighted code. Use CSS to actually get the colours you want, look at pygments documentation for extracting css for various styles.
This snippet has the advantage of falling back on <pre> if anything goes wrong, and attempting to guess the syntax of code, falling back on python.
You can switch boolean fields in the admin without editing objects
Usage:
`
class News(models.Model):
# ...
pub = models.BooleanField(_('publication'),default=True)
# ...
pub_switch = boolean_switch(pub)
class Admin:
list_display = ('id', 'pub_switch')
`
Thanks for [svetlyak](http://www.djangosnippets.org/snippets/398/).
Usually, you can add links in the admin using such code:
class Pingback(models.Model):
#...
target_uri = models.URLField( _('Target URI'))
#...
def admin_target(self):
return '<a href="%(targ)s">%(targ)s</a>' % {'targ': self.target_uri}
admin_target.short_description = _('Target URI')
admin_target.allow_tags = True
#...
class Admin:
list_display = ('id', 'admin_target')
But when you have two or more url fields, such approach becomes to expensive. Follow the DRY principe and use my code in such way:
# Just add this line instead of the ugly four lines **def blabla**
admin_target = link('target_uri', _('Target URI'))
The rationale behind this decorator is described in django-users google group.
Usage:
=== urls.py ===
urlpatterns = patterns('',
(r'^', include('apps.app1.views')),
(r'^app2', include('apps.app2.views')),
)
=== apps/app1/views/__init__.py ===
@url(r'^index/$')
def index(request):
...
@url(r'^news/$')
def news(request):
...
urlpatterns += include_urlpatterns(r'^members', 'apps.app1.views.members')
=== apps/app1/views/members.py ===
@url(r'^profile/$)
def profile(request):
....
@url(r'^secure/$)
def secure(request):
...
@url(r'^path1/$', '^path2/$') # you can specify several patterns
def multipath_view(request):
...
def helper(): # easily distinguishable - no @url!
...
Summarizing, the benefits are:
* no more creating and supporting urlpattern maps (less files, less code, more DRY)
* have the url associated with a view in-place
* easily see if a function is a view
* fully compatible with other chained decorators
Call this function as the first thing in your cron, or console script; it will bootstrap Django, and allow you to access all of the Django modules from the console, with out using 'python manage.py shell'
Examples:
# A script within your django project.
from django_bootstrap import bootstrap
bootstrap(__file__)
--- or ---
# A cron script located outside of your django project
from django_bootstrap import bootstrap
bootstrap("/path/to/your/project/root/")
This is an example middleware that is highly inspired by how Symfony handles [i18n in URLs](http://www.symfony-project.com/book/trunk/13-I18n-and-L10n#Changing the Culture for a User). You basically set a (?P<dj_culture>[\w-]+) pattern in your URL and this middleware will determine the language to use for the i18n toolkit for Django.
It also removes the dj_culture parameter after dealing with it, so that you don't have to change all the views you want this middleware to work with.
Flash message add-on for Django. Uses sessions. Behavior is such that you set a flash message in a view. That message is stored in the sesssion. Then whenever it is that the message gets displayed, it is removed from the session (never to be heard from again)
**Installation:**
In your settings, enable the following items.
TEMPLATE_CONTEXT_PROCESSORS
django.core.context_processors.request
MIDDLEWARE_CLASSES
django.contrib.sessions.middleware.SessionMiddleware
Then put it into a file called flash.py in your templatetags directory.
**Usage:**
It's pretty simple. Do something like this in your view ..
>>>request.session['flash_msg'] = 'Your changes have been save'
>>>request.session['flash_params'] = {'type': 'success'}
And maybe put something like this in your template
{% load flash %}
{% flash %}
<h2>{{ params.type }}</h2>
{{ msg }}
{% endflash %}
It also support a flash template, you can specify a file
FLASH_TEMPLATE in your settings file and then that file will be rendered with msg and params as available variable.
Usage for this would simply be `{% flash_template %}` and then you gotta make a template file that does whatever you like.
Outside of that just be aware you need the Django session middleware and request context installed in your app to use this.
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.