Favorite Django Tips & Features? Favorite Django Tips & Features? python python

Favorite Django Tips & Features?


I'm just going to start with a tip from myself :)

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:

# settings.pyimport osPROJECT_DIR = os.path.dirname(__file__)...STATIC_DOC_ROOT = os.path.join(PROJECT_DIR, "static")...TEMPLATE_DIRS = (    os.path.join(PROJECT_DIR, "templates"),)

Credits: I got this tip from the screencast 'Django From the Ground Up'.


Install Django Command Extensions and pygraphviz and then issue the following command to get a really nice looking Django model visualization:

./manage.py graph_models -a -g -o my_project.png


Use django-annoying's render_to decorator instead of render_to_response.

@render_to('template.html')def foo(request):    bars = Bar.objects.all()    if request.user.is_authenticated():        return HttpResponseRedirect("/some/url/")    else:        return {'bars': bars}# equals todef foo(request):    bars = Bar.objects.all()    if request.user.is_authenticated():        return HttpResponseRedirect("/some/url/")    else:        return render_to_response('template.html',                              {'bars': bars},                              context_instance=RequestContext(request))

Edited to point out that returning an HttpResponse (such as a redirect) will short circuit the decorator and work just as you expect.


matomo