Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Integrating mongoDB and Django
After listening to Mike Dirolf talk about mongoDB at a recent Django-NYC meetup I was left wanting to learn more about mongoDB and how I could integrate it into my Django projects. Overview This screencast will quickly review places to learn more about mongoDB, and a few available Python APIs for working with mongoDB, particularly mongoengine. It also discuss a project that shows us how to leverage all the great things about Django and also integrate a NOSQL database into the mix. I stumbled onto the mongoEngine project about a month ago and have been meaning to post this screencast since then. What I like most about mongoEngine is that the classes structure looks and feels a lot like Django's models. I also really like its query API which also looks and feels a lot like Django's QuerySet API. Finally, I take a look at a Django powered tumblog project that uses mongoDB in the backend. This particular project leverages a custom authentication backend for handling application authentication, Django forms, Django views, templates, urls, etc. Essentially it uses everything but the ORM. This is not an extremely detailed tutorial -- my goal is to open up the discussion around a … -
2009 Django Dash Complete
The 2009 Django Dash is done. The site (http://alt.djangodash.com/) has the full commit logs and some interesting stats (overall, per team, per dasher). I'll do a better post-mortem tomorrow. Congratulations to all who participated and hope to see you next year! -
Postmortem: Django Dash 2009
Now that the Dash is over, I wanted to write up a little postmortem with some thoughts about how things went. To understate things, this year's Django Dash was amazing. In virtually every regard, the competition exceeded last year's contest. What Went Well First, a huge thanks to the sponsors. We went from 8 last year to 12 this year. Without them, there would be no prizes for the contest. We also doubled the number of teams that actively competed, which really impressed me. Many of the entries seem much more complete than last year as well. Using IRC & Twitter were also big wins. The IRC channel (#django-dash on Freenode) was where the party was most of the weekend (thanks to Eric for setting it up and admin'ing it). And being able to more easily/effectively distribute information via Twitter was nice (less infrastructure/headaches for me). Plus it was fun watching the #djangodash fly by. More stats and sparklines improved the website itself. I used the jquery.sparkline library and the new Aggregation support in Django trunk (soon 1.1), both of which proved easy to use and made it a little easier to spectate the contest. Bumping the team size from … -
Haystack 1.0.0-rc1
After almost a full year of development, Haystack has been marked as 1.0.0, release candidate 1. I'd recommend all users upgrade, as it is what Haystack 1.0.0-final will be unless any bugs are found. Should all go well, I'll be releasing 1.0.0-final next Sunday (Nov. 29, 2009). The release is available via git, via PyPi and as a tarball from GitHub. It's been a lot of work and lots of good contributions. I'm glad to finally be in the home stretch and will post something more substantial when 1.0.0-final drops. -
Haystack 1.0 Final Released
Haystack 1.0.0-final has been released (via the packages at PyPi or GitHub). You can also install it via ``sudo pip install django-haystack`` or via git from GitHub. The goal of Haystack is to provide modular search for Django. This means pluggable backends (Solr, Whoosh & Xapian currently), a reusable app architecture, the ability to add search to third-party modules without modifying their sources and a flexible codebase with many points of extension. The crown jewel is the ``SearchQuerySet``, which provides a ``QuerySet``-like interface to your search index. Included with the main install is everything needed to get basic search up and running in short order and yet powerful enough to provide search to some decent-sized sites. And there's a fair amount of documentation available. As with Django, Haystack will attempt to remain backward-compatible for the duration of the 1.X series, though there are no guarantees on this. Should a backward-incompatible change come up, I will post full disclosure on the changes on the mailing list as well as the commit itself. Some fun facts about Haystack's development: 315 days in development (from first commit to 1.0-final). 420 public commits with another 100 or so that were squashed. 27 people in … -
Better Local Settings
A common convention I've seen in the Django community is to place code like the following at the bottom of your settings file: # ``settings.py`` # Lots of typical settings here. # ... then ... try: from local_settings import * except ImportError: pass Then storing machine/user-specific settings within a local_settings.py> file. This file is set to be ignored by version control. I can't argue with needing overridden settings (do it all the time) but that import is backward in my opinion. My preferred technique is to still use the settings.py and local_settings.py but relocate the import. So local_settings.py starts out with: # ``local_settings.py`` from settings import * # Properly namespaced as needed. # Custom settings go here. DATABASE_HOST = 'localhost' The only other change is passing --settings=local_settings to any ./manage.py or django-admin.py calls. Trivial implementation, you still only need to override what you need, no changes needed to version control or development workflow. And since you've already imported all of the base settings, you can reuse that information to create new settings, like: # ``local_settings.py`` from settings import * DATABASE_NAME = "%s_dev" % DATABASE_NAME This is by no means a new technique, nor did I come up with it, but … -
Quickly Impersonate Another User In Your Django Project
I've created or worked on so many Django projects in the last 4 years that I find myself completely forgetting a project or client all together. It's sort of funny. Anyways... Too many times I've run into a situation where I, as an admin, need to impersonate another user on the system so I can verify a bug or issue that the user is experiencing. Over the years I've thrown together some internal methods to easily accomplish this. Well I finally got fed up with the process and decided to roll out a easily re-usable Django app to make it easy to do this for any Django project you may be working on. Drum roll please... Announcing Django-Impersonate OK, that wasn't as dramatic of an announcement as I'd hoped. In any case, you can clone django-impersonate on the BitBucket page for the app. It's also easily available via pip (pip install django-impersonate.) The app has a few helpful methods out the gate. A few views to actually start the impersonation, end it, list users, and search users. The search is just a basic query filtering on the username, first & last names, and email addresses of all the system users. … -
Exposing calendar events using iCalendar in Django
I recently wrote simple abstraction for exposing calendar events in Django as iCalendar feeds. It relies on vobject for managing the formatting of the calendar file, so you will need this if you want to try it out. It is available in Debian in the python-vobject package. Save this as a file somewhere in your project: import vobject from django.http import HttpResponse EVENT_ITEMS = ( ('uid', 'uid'), ('dtstart', 'start'), ('dtend', 'end'), ('summary', 'summary'), ('location', 'location'), ('last_modified', 'last_modified'), ('created', 'created'), ) class ICalendarFeed(object): def __call__(self, *args, **kwargs): cal = vobject.iCalendar() for item in self.items(): event = cal.add('vevent') for vkey, key in EVENT_ITEMS: value = getattr(self, 'item_' + key)(item) if value: event.add(vkey).value = value response = HttpResponse(cal.serialize()) response['Content-Type'] = 'text/calendar' return response def items(self): return [] def item_uid(self, item): pass def item_start(self, item): pass def item_end(self, item): pass def item_summary(self, item): return str(item) def item_location(self, item): pass def item_last_modified(self, item): pass def item_created(self, item): pass Now we need to couple this abstraction with a Django queryset. I placed this in a feeds.py in my application: from yourproject.path.icalendar import ICalendarFeed from yourproject.yourapp.models import SomeEvent class SomeEventCalendar(ICalendarFeed): def items(self): return SomeEvent.objects.all() def item_uid(self, item): return str(item.id) def item_start(self, item): return item.start def item_end(self, item): … -
Using Amazon S3 with Django
UPDATE: A commenter from this entry's submission on Reddit suggested setting up the CNAME to the S3 servers based on the bucket for your unique domain. By doing this, it will appear that the static files are hosted on your own servers instead of Amazon. A lot has been changing for this site lately. Not only did I switch hosting to the Python wonderland of WebFaction, but I also started serving static media -- CSS, JavaScript, images and other files -- through Amazon's Simple Storage Service (S3). Changing Web hosts from Dreamhost for this and my other Django apps was a must, but using Amazon's Web Service was more of an experiment really. Fortunately it's a cheap one: I owe Amazon eight cents for June. Follow the directions To get Amazon's S3 working for my site and Knox'd, I simply followed the directions published way back in 2006 by data wunderkind Adrian Holovaty. I'll paraphrase for readers of this blog: First, sign up for an Amazon S3 account. There is no charge until you actually use the service. Bonus: You can use your existing Amazon username and password like other purchases. Next you'll need to create a "bucket" for your … -
XML-RPC dispatching through Django test client
Django has a cleverly designed test client that creates a WSGIRequest and routes it through your views without the need of a web server. Furthermore it works on a temporary test database, thus any errors won't have any effect on your live database. I'm currently working on an application written using Django. This application, amongst other features, has an XML-RPC interface. The tests for this interface was being done by spawning a local web server and carrying out the tests over the wire. However, it would be nice to exploit the Django test framework. The solution is amazingly simple. I wrote a TestTransport class for xmlrpclib: import cStringIO from xmlrpclib import Transport from django.test.client import Client class TestTransport(Transport): """ Handles connections to XML-RPC server through Django test client.""" def __init__(self, *args, **kwargs): self.client = Client() def request(self, host, handler, request_body, verbose=0): self.verbose = verbose response = self.client.post(handler, request_body, content_type="text/xml") res = cStringIO.StringIO(response.content) res.seek(0) return self.parse_response(res) In my tests where I use the XML-RPC interface I initialize the ServerProxy object with: server = ServerProxy('http://localhost/xmlrpc/', transport=TestTransport()) That's about it. Now calls trough the server object will be handled by the Django test client. In my case I had a decorator around the … -
About Django and the importance of releases
My favorite Python web framework, Django, has not been updated for a long time. The most current release, 0.96, was released in March 2007. This is a very long time, when you're in the market of web frameworks. This doesn't seem to bother a lot of people, as the common answer in the django community seems to be just to run the trunk version (development version). I for one doesn't like that solution. And here are some of the reasons why. Some of the problems with running a development version When a security release is made, I cannot just update, but need to merge the change in, in all of my installations. An update could maybe break my existing code with backward incompatible changes. It's easier to tell my co-workers that our projects will run 0.96, and not r6389 for one project and r7291 for another (+ a couple of security patches). That's okay if you are a single-person team working on a single project, but not when you have several people and projects. Developers are afraid to commit new things to trunk, because a lot of users will be disappointed when they eagerly update their repositories each morning just … -
Resources for Django on WebFaction
It feels like forever ago that patrickbeeson.com and a few of my other sites were hosted on Dreamhost. That is, of course, an increasingly distant memory now that I'm served by WebFaction's nearly fire-proof boxes. But making a Django environment stable wasn't as turn-key as their marketing might lead you to suspect (though it's easier than Dreamhost). In an effort to help future WebFaction Djangonauts, here are some most-read posts from WebFaction's excellent user-forum and knowledgebase. Domain transfer Note: WebFaction doesn't handle domain registration. You'll need to change your name servers to those used by WebFaction. Mine are still on Dreamhost. How can I add a new domain to my account? Apache configuration How do I stop/start/restart my Django Apache instance? How to fix errors like: ImportError: No module named django.core.management How do I serve static content? Running multiple Django sites from the same Apache/mod_python instance Django configuration Serving the Django admin media directly from the main Apache server How do I run the latest Django trunk? Cron + Django Script For Newbies - deploying your Django app Running "manage.py syncdb" Using Robots.txt file under Django in WebFaction Sending e-mails from Django Deploying A Django Application Memory usage Note: If … -
Django and mod_wsgi: A perfect match!
mod_wsgi is an Apache module for serving WSGI-based Python web applications from the Apache HTTP server. Django, along with almost every other Python web framework today, comes bundled with a backend for acting like a WSGI application. A couple of months ago I decided to try it out in spite of mod_python. Discovering and trying out mod_wsgi really suprised me. It can take a massive beating, and outperforms mod_python in every practical aspect. The setup You will need a short Python "bootstrap" script to create a WSGI-handler for your Django project. Here is an example (call it wsgi_handler.py and place it in the root directory of your Django project - the one with manage.py and settings.py): import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') os.environ['DJANGO_SETTINGS_MODULE'] = 'projectname.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Finally set up your Apache virtualhost to use mod_wsgi: <VirtualHost *> ServerName www.projectname.org ServerAlias *projectname.org Alias /admin_media /usr/lib/python2.4/site-packages/django/contrib/admin/media <Location /admin_media> Order allow,deny Allow from all </Location> Alias /media /home/user/projectname/media <Location /media> Order allow,deny Allow from all </Location> WSGIScriptAlias / /home/user/projectname/wsgi_handler.py WSGIDaemonProcess projectname user=user group=user processes=1 threads=10 WSGIProcessGroup projectname </VirtualHost> In the WSGIDaemonProcess line, you can easily manage the amount of system resources (measured in processes and threads) mod_wsgi should … -
'Practical' tips for working with Django
Everything I did building the content management system for this Web site was wrong. Actually, that might be an overstatement since this Web site works quite well (better than it did in Movable Type). But in the course of building a new Django content management system (CMS) that will drive the new, soon-to-be-launched Young Professionals of Knoxville Web site, I've learned a lot of useful techniques. Much of my new-found knowledge is due to Django Release Manager James Bennett's wonderful book "Practical Django Projects." Custom managers One of the critical needs for the new YPK site is the posting and display of events. At first, I figured this would require a standard model with the following fields: slug name location (ForeignKey to Location subclass) description event date start time finish time attire (With two options: formal and casual) category (ForeignKey to Category app) But then I realized that I would need a way to filter out events that are no longer current -- who wants to view old events? That's where custom mangers in models come into play: class CurrentManager(models.Manager): def get_query_set(self): return super(CurrentManager, self).get_query_set().filter(event_date__gte=datetime.date.today()) This allows me to filter all events whose date is greater than or equal to … -
Hacking Django forms for CSS flexibility
The default output of the Django forms (former newforms) module is not very CSS friendly. With a few simple adjustments, you can make your web designer colleague happy. This patch will add three classes on the parent HTML element of the rendering of each form field (the tr, li or p tag depending on your rendering mode): The type of the form field. (Examples: CharField, ModelChoiceField) The type of the widget. (Examples: TextInput, SelectInput) Is the form field optional or required: Optional or Required Now a required DateField will render, using the as_table rendering, as: <tr class="DateField TextInput Required"> <th> <label for="id_date">Date</label> </th> <td> <input type="text" name="date" id="id_date" /> </td> </tr> Example uses A couple of example use cases where my patch will help you out: Special styling of required fields possible. Easier to add a date picker by JavaScript. Special styling of checkboxes (styling input elements to width: 100% also affects those). Download the patch Patch against forms/forms.py in Django 1.0: Download - View How to patch your newly downloaded Django-1.0.tar.gz For those of you not quite familiar with working with patches: $ wget http://www.hacktheplanet.dk/export/HEAD/misc/forms.py.patch $ wget http://www.djangoproject.com/download/1.0/tarball/ $ tar xvfz Django-1.0.tar.gz $ patch -d Django-1.0/django/forms/ < forms.py.patch -
How Django is good for SEO
Django, the venerable Python framework created for the publishing needs of a newspaper Web site, is surprisingly good for organic search engine optimization (SEO). In fact, Django comes with many options out-of-the-box that sets it apart from other means of building Web applications. These include: beautiful URLs, a plethora of database options, sitemap framework and elegant template design. Beautiful URLs Compare an URL from most any Django Web site to those of an ASP or PHP site, and you'll notice a big difference: You can read the Django URL. And that's good for you and Google since it's factored into the page's importance. Here's an example of URLs captured from two newspaper Web sites, the first using Django: Knoxnews.com (Django): http://www.knoxnews.com/news/2008/jul/22/storms-fell-trees-cut-power/ Startrib.com: http://www.startribune.com/local/stpaul/25971699.html Some PHP sites come close to Django's beautiful URLs: News-record.com (PHP/Drupal): http://www.news-record.com/content/2008/07/21/article/superintendent_finalists_have_nc_connections But what makes Django's URLs extra nice is the ease at which you can create them. To design URLs in Django, you need only create a Python module called URLconf. This serves as a "table of contents for your app," according to the official Django documentation. Here is an example of what a sample news site's URLconf looks like (taken from Django documentation): from django.conf.urls.defaults … -
YPKnox.com: Knoxville's newest Django site
The launch of the redesigned and retooled Young Professionals of Knoxville Web site brings yet another Django site online for the city of the Sunsphere. It also marks my third Django project -- the others being this site and Knox'd -- since I began learning the vaunted Python framework nearly two years ago. What I learned Building the new YPK Web site was a challenge in several ways. Here are some specific problems I encountered: How to filter out expired events in specific views, but make the permalinks available for bookmarks and search engines. How to only show "live" press releases, as opposed to press releases being edited. How to pass in more objects into generic views. How to improve the site performance by writing more efficient database queries and text-to-HTML rendering. The solutions for these problems were documented in a previous blog entry titled "'Practical' tips for working with Django." Also, I must again credit James Bennett for publishing his wonderful book Practical Django Projects without which I would probably still be hunting down information (or bugging the developers at work). Site features The new YPK Web site isn't that extraordinary. But it does feature some useful ways of … -
How to create user-specific admins in Django
The newForms admin branch of Django officially landed in trunk a few weeks ago. Not only does this allow for the awesome django.contrib.admin application to be more customizable, it also solves handily a problem I ran into for an upcoming project: Creating a user-specific Django admin where users see only the objects they create. Project intentions My latest Django project involves creating a basic content management system (CMS) that I can use as a hands-on example for a journalism class I'm teaching at The University of Tennessee this fall. The class, Managing Newspaper Web sites, will cover basic concepts for managing a modern newsroom where a CMS is a vital part of the publishing process. One assignment, for example, will require students to take a story written for print, and edit it for the Web as they enter it into a CMS. To accomplish this goal, I plan to build a basic models for stories, categories and photos that I hope will emulate those in Ellington, the Django-based CMS used by newspaper Web sites owned by Scripps (my employer). Other requirements But unlike Ellingon, where anyone with the proper access can see everyone else's stories, I don't want students to … -
How to upgrade to Django Comments 1.0
The release of Django 1.0 held many new developments for the Python-based framework that I've used to build several projects during the past few months. But one feature I was really looking forward to exploring was the new, refactored comments application. Unfortunately, Django Comments 1.0 also comes with the scary prospect of database updates, data migrations, markup changes, CSS changes and other headaches. Here's how I tackled the now-documented upgrade for this application. Prepare your projects My personal Web site was already running on a variation of Django trunk (pre-alpha) before I upgraded to Django 1.0 final. This made the update process somewhat easier since I'd already been through the updates for newForms admin and the like. Also, I don't have a typical development environment for this site, which really puts an emphasis on reading through the documentation. You don't want surprises from backwards-incompatible changes! Here are the steps I took for preparing my site for Django Comments 1.0: Read the documentation on the Django Project site thoroughly (including the upgrade guide) Comment out, or remove any references to the awesome, but incompatible (for now) django-comment-utils package Change any reference to "FreeComment" to "Comment" Change template tags to reflect the … -
Medill's News Mixer remixes story comments
The Knight Foundation grant-backed graduate program at Medill's School of Journalism has birthed what could be a game-changing effort for news story comments. Their effort, called News Mixer, leverages traditional news content, Facebook's Connect feature and offers three methods of user feedback: Questions and answers: Allows a reader to leave a question about the story, and allows other readers, including the reporter, to leave an answer. Quips: A short-answer, or Twitter-like format that allows you to offer a quick response, limited to 140 characters. Letters to the editor: An outlet for readers to send their thoughts in 250 words or less, whether about an article, another letter someone wrote, or on any subject the author deems important. An editor can then select and highlight the best letters. But what's unique about News Mixer is how it uses these three types of functionality to channel user comments in a more meaningful way. Why News Mixer is different Traditional Web story comments are wrought with problems, especially when editors and content producers are hands-off in their management style. This style of commenting usually consists of a form located at the end of a story or content and contains the following components: Name … -
How to stop spam on a Django blog
Don't rely on the honey pot to attract, and hold at bay, spam comments for your Django blog. Stopping spam completely for a blog built using Django takes a three-pronged approach of Akismet, date-based closing of comments and a cron-run script that removes spam comments from your database. And fortunately, all three steps are quite easy to implement. Note: I'm using Python 2.5 and Django 1.0.2 Install and enable Akismet The best front-line defense for stopping spam to your Django blog is to use Akismet via the Python API. Here are the steps: First, download akismet.py and put it on your PYTHONPATH. Then get a Akismet API key by signing up for a free Wordpress blog. Put the API key in the apikey.txt located in your Akismet directory. You'll also need to add the URL for your blog. Add this line to your Django project settings.py: AKISMET_API_KEY = '<your_api_key>' Open up your blog models.py and add the following code snippet (this will also enable e-mail notification for new, public comments): from django.contrib.comments.signals import comment_was_posted from django.utils.encoding import smart_str from django.core.mail import mail_managers import akismet from django.conf import settings from django.contrib.sites.models import Site ... def moderate_comment(sender, comment, request, **kwargs): ak = … -
RSS feed for comments on a Django blog entry
Django makes it possible to have an RSS feed for everything. Of course, possible is not always easy. Sometimes it just takes a little logic, documentation and the help of programmers much smarter than I to get things done. In this case, it means building an RSS feed for comments on individual entries on my Django blog. Prerequisites I'm using Django 1.0.2 and the contrib comments and syndication applications for this example. Creating the feed The first thing I'd recommend is checking out the Django Project documentation for creating a complex feed. This will show you how to derive objects related to another object (comments for an entry). My Django blog models.py is pretty basic: class Entry(models.Model): # Status options CLOSED_STATUS = 1 EDITING_STATUS = 2 LIVE_STATUS = 3 STATUS_CHOICES = ( (CLOSED_STATUS, 'Closed'), (EDITING_STATUS, 'Editing'), (LIVE_STATUS, 'Public'), ) # Title and slug fields title = models.CharField(max_length=200, help_text='This field will populate the slug field. Maximum 200 characters.') slug = models.SlugField(unique_for_date='pub_date') # Summary and body fields summary = models.TextField(help_text='Please use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a>.') body = models.TextField(help_text='Please use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a>.') # Markdown conversion for summary and body fields summary_html = models.TextField(editable=False, blank=True) body_html = models.TextField(editable=False, blank=True) # Tag field tags = … -
Usando o newforms do Django para gerar formulários
Esse é meu primeiro tutorial, não é extenso pois estou iniciando no Django e Python, e como eu gosto de ajudar sempre que possível eu vou compartilhar a experiência que fiz com essa classe nova do django, o newforms. Eu não vou me deter a explicar como iniciar uma aplicação nova e etc, isso já esta descrito nos tutoriais traduzidos do site da comunidade djangobrasil.org Vamos usar essas declarações: from django import newforms as formsfrom django.shortcuts import ... -
Usando NewForms com ModelForm
É isso ae! To de volta para ajudar aqueles que estão quebrando a cabeça assim como eu estava a uns dias atrás para usar essas classes do django que facilitam muito o desenvolvimento. Eu ainda estou de boca aberta com o que o Django é capaz de fazer e hoje me pergunto “porque estou desenvolvendo em Delphi, ASP.NET e C# e ainda uso Windows?” pois bem isso é meu ganha pão e infelizmente não posso parar, mas se hoje ... -
Model Referência (resumido e editado)
O model(modelo) é simples, é a fonte de dados definitiva para os seus dados. Ela contém os campos e comportamentos essenciais para os seus dados armazenados. Em geral, um model é uma tabela simples de um banco de dados. O básico:O model é uma classe Python com subclasses django.db.models.Model.Os atributos do model representam um campo no banco de dados.Model metadata (não as informações dos fields) são informadas em uma classe chamada Meta.O ...