Inspired by the question series ‘Hidden features of …’, I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
Use os.path.dirname() in settings.py to avoid hardcoded dirnames.
Don’t hardcode path’s in your settings.py if you want to run your project in different locations. Use the following code in settings.py if your templates and static files are located within the Django project directory:
There’s a set of custom tags I use all over my site’s templates. Looking for a way to autoload it (DRY, remember?), I found the following:
from django import template
template.add_to_builtins('project.app.templatetags.custom_tag_module')
If you put this in a module that’s loaded by default (your main urlconf for instance), you’ll have the tags and filters from your custom tag module available in any template, without using {% load custom_tag_module %}.
The argument passed to template.add_to_builtins() can be any module path; your custom tag module doesn’t have to live in a specific application. For example, it can also be a module in your project’s root directory (eg. 'project.custom_tag_module').
回答 4
如果您正在处理多个Django项目,则Virtualenv + Python = life saver,并且它们有可能不都依赖于同一版本的Django /应用程序。
Virtualenv + Python = life saver if you are working on multiple Django projects and there is a possibility that they all don’t depend on the same version of Django/an application.
Use django debug toolbar. For example, it allows to view all SQL queries performed while rendering view and you can also view stacktrace for any of them.
Don’t write your own login pages. If you’re using django.contrib.auth.
The real, dirty secret is that if you’re also using django.contrib.admin, and django.template.loaders.app_directories.load_template_source is in your template loaders, you can get your templates free too!
from django.utils.translation import ugettext_lazy as _
classPost(models.Model):
title = models.CharField(_('title'), max_length=255)
body = models.TextField(_('body'))
created = models.DateTimeField(auto_now_add=True)
import twitter
from django.core.cache import cache
from django.db.models.signals import post_save
from django.conf import settings
def posted_blog(sender, created=None, instance=None,**kwargs):''' Listens for a blog post to save and alerts some services. '''if(created and instance isnotNone):
tweet ='New blog post! %s' instance.title
t = twitter.PostUpdate(settings.TWITTER_USER,
settings.TWITTER_PASSWD,
tweet)
cache.set(instance.cache_key, instance,60*5)# send pingbacks# ...# whatever elseelse:
cache.delete(instance.cache_key)
post_save.connect(posted_blog, sender=Post)
I wrote a blog post about this a few months ago so I’m just going to cut and paste:
Out of the box Django gives you several signals that are incredibly useful. You have the ability to do things pre and post save, init, delete, or even when a request is being processed. So lets get away from the concepts and demonstrate how these are used. Say we’ve got a blog
from django.utils.translation import ugettext_lazy as _
class Post(models.Model):
title = models.CharField(_('title'), max_length=255)
body = models.TextField(_('body'))
created = models.DateTimeField(auto_now_add=True)
So somehow you want to notify one of the many blog-pinging services we’ve made a new post, rebuild the most recent posts cache, and tweet about it. Well with signals you have the ability to do all of this without having to add any methods to the Post class.
import twitter
from django.core.cache import cache
from django.db.models.signals import post_save
from django.conf import settings
def posted_blog(sender, created=None, instance=None, **kwargs):
''' Listens for a blog post to save and alerts some services. '''
if (created and instance is not None):
tweet = 'New blog post! %s' instance.title
t = twitter.PostUpdate(settings.TWITTER_USER,
settings.TWITTER_PASSWD,
tweet)
cache.set(instance.cache_key, instance, 60*5)
# send pingbacks
# ...
# whatever else
else:
cache.delete(instance.cache_key)
post_save.connect(posted_blog, sender=Post)
There we go, by defining that function and using the post_init signal to connect the function to the Post model and execute it after it has been saved.
Use IPython to jump into your code at any level and debug using the power of IPython. Once you have installed IPython just put this code in wherever you want to debug:
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
Then, refresh the page, go to your runserver window and you will be in an interactive IPython window.
I have a snippet set up in TextMate so I just type ipshell and hit tab. I couldn’t live without it.
If you use the Bash shell, consider installing the Django bash completion script, which lives in extras/django_bash_completion in the Django distribution. It enables tab-completion of django-admin.py and manage.py commands, so you can, for instance…
Type django-admin.py.
Press [TAB] to see all available options.
Type sql, then [TAB], to see all available options whose names start with sql.
The ./manage.py runserver_plus facilty which comes with django_extensions is truly awesome.
It creates an enhanced debug page that, amongst other things, uses the Werkzeug debugger to create interactive debugging consoles for each point in the stack (see screenshot). It also provides a very useful convenience debugging method dump() for displaying information about an object/frame.
When trying to exchange data between Django and another application, request.raw_post_data is a good friend. Use it to receive and custom-process, say, XML data.
If you find the Django template language extremely restricting (like me!) then you don’t have to be stuck with it. Django is flexible, and the template language is loosely coupled to the rest of the system, so just plug-in another template language and use it to render your http responses!
I use Jinja2, it’s almost like a powered-up version of the django template language, it uses the same syntax, and allows you to use expressions in if statements! no more making a custom if-tags such as if_item_in_list! you can simply say %{ if item in list %}, or {% if object.field < 10 %}.
But that’s not all; it has many more features to ease template creation, that I can’t go though all of them in here.
Since Django “views” only need to be callables that return an HttpResponse, you can easily create class-based views like those in Ruby on Rails and other frameworks.
There are several ways to create class-based views, here’s my favorite:
from django import http
class RestView(object):
methods = ('GET', 'HEAD')
@classmethod
def dispatch(cls, request, *args, **kwargs):
resource = cls()
if request.method.lower() not in (method.lower() for method in resource.methods):
return http.HttpResponseNotAllowed(resource.methods)
try:
method = getattr(resource, request.method.lower())
except AttributeError:
raise Exception("View method `%s` does not exist." % request.method.lower())
if not callable(method):
raise Exception("View method `%s` is not callable." % request.method.lower())
return method(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return http.HttpResponse()
def head(self, request, *args, **kwargs):
response = self.get(request, *args, **kwargs)
response.content = ''
return response
You can add all sorts of other stuff like conditional request handling and authorization in your base view.
Once you’ve got your views setup your urls.py will look something like this:
from django.conf.urls.defaults import *
from views import MyRestView
urlpatterns = patterns('',
(r'^restview/', MyRestView.dispatch),
)
Instead of using render_to_response to bind your context to a template and render it (which is what the Django docs usually show) use the generic view direct_to_template. It does the same thing that render_to_response does but it also automatically adds RequestContext to the template context, implicitly allowing context processors to be used. You can do this manually using render_to_response, but why bother? It’s just another step to remember and another LOC. Besides making use of context processors, having RequestContext in your template allows you to do things like:
<a href="{{MEDIA_URL}}images/frog.jpg">A frog</a>
which is very useful. In fact, +1 on generic views in general. The Django docs mostly show them as shortcuts for not even having a views.py file for simple apps, but you can also use them inside your own view functions:
I don’t have enough reputation to reply to the comment in question, but it’s important to note that if you’re going to use Jinja, it does NOT support the ‘-‘ character in template block names, while Django does. This caused me a lot of problems and wasted time trying to track down the very obscure error message it generated.
Everybody knows there is a development server you can run with “manage.py runserver”, but did you know that there is a development view for serving static files (CSS / JS / IMG) as well ?
Newcomers are always puzzled because Django doesn’t come with any way to serve static files. This is because the dev team think it is the job for a real life Web server.
But when developing, you may not want to set up Apache + mod_wisgi, it’s heavy. Then you can just add the following to urls.py:
I learned this one from the documentation for the sorl-thumbnails app. You can use the “as” keyword in template tags to use the results of the call elsewhere in your template.
This is mentioned in passing in the Django templatetag documentation, but in reference to loops only. They don’t call out that you can use this elsewhere (anywhere?) as well.
django.views.generic.list_detail.object_list — It provides all the logic & template variables for pagination (one of those I’ve-written-that-a-thousand-times-now drudgeries). Wrapping it allows for any logic you need. This gem has saved me many hours of debugging off-by-one errors in my “Search Results” pages and makes the view code cleaner in the process.
Use xml_models to create Django models that use an XML REST API backend (instead of a SQL one). This is very useful especially when modelling third party APIs – you get all the same QuerySet syntax that you’re used to. You can install it from PyPI.
class Profile(xml_models.Model):
user_id = xml_models.IntField(xpath='/profile/@id')
email = xml_models.CharField(xpath='/profile/email')
first = xml_models.CharField(xpath='/profile/first_name')
last = xml_models.CharField(xpath='/profile/last_name')
birthday = xml_models.DateField(xpath='/profile/date_of_birth')
finders = {
(user_id,): settings.API_URL +'/api/v1/profile/userid/%s',
(email,): settings.API_URL +'/api/v1/profile/email/%s',
}
profile = Profile.objects.get(user_id=4)
print profile.email
# would print 'joe@example.com'
It can also handle relationships and collections. We use it every day in heavily used production code, so even though it’s beta it’s very usable. It also has a good set of stubs that you can use in your tests.
(Disclaimer: while I’m not the author of this library, I am now a committer, having made a few minor commits)