Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Site-wide login protection (and public views)
A common pattern in websites is when a few pages are protected and require a login to be accessed. The @login_required decorator often comes in handy for these situations. But, another pattern which is quite common is when most of the site is protected, with just a few exceptions of pages that remain public (e.g. frontpage, registration page, etc.). In that case, it can be quite tedious to decorate all of the views with @login_required, and it can be easy to forget to decorate some of them. So, I came up with a simple system which by default protects every view and then lets you explicitly tell which views should be public. This makes things both easier and less error-prone. Installation The core of that system is contained in the following middleware code: import re from django.conf import settings from django.contrib.auth.decorators import login_required from path.to.your.decorators import PublicView class LoginRequiredMiddleware(object): def __init__(self): self.public_patterns = [] self.public_views = [] if hasattr(settings, 'PUBLIC_VIEWS'): for view_path in settings.PUBLIC_VIEWS: view = self.get_view(view_path) self.public_views.append(view) if hasattr(settings, 'PUBLIC_PATHS'): for public_path in settings.PUBLIC_PATHS: self.public_patterns.append(re.compile(public_path)) def get_view(self, view_path): i = view_path.rfind('.') module_path, view_name = view_path[:i], view_path[i+1:] module = __import__(module_path, globals(), locals(), [view_name]) return getattr(module, view_name) def matches_public_view(self, view): if … -
Exploring Pinax – Part 1
What this is about After learning how to build a Flex client and a Python server running on Google App Engine, I decided to try a pure-Web, pure-Python alternative. I chose Django, a first-class Web framework. I went through the tutorial and read the excellent book Practical Django Projects. The next step is building a [...] -
New Django Site For Porsche Enthusiasts
Recently I’ve completed a revamp of Patrick Motorsports on the Django platform. The owner, James, has been working with Porsches for more than 15 years. He races Porsches, builds Porsches, and sells parts for Porsches. Overall its a cool shop, every time I’m over I see a dozen cars in various states [...] -
AJAX upload progress bars with jQuery, Django and nginx
I've included upload progress bars on a couple of Django sites. Thanks to the new file handling in Django 1.0, a code snippet from djangosnippets.org, and jquery-upload-progress, it's really not difficult, but I haven't seen a complete example, so I put together a demo app showing how the pieces fit together. I'll also cover the case where you want a proxy to provide the upload progress tracking, without involving Django. -
JSONField for Django Models
I was needing to store semi-structured data on a model for a project I am working on, but didn't want to parse strings or create a foreign key to a key/value type table. The use of JSON came to mind via the simplejson library. I thought leveraging Python's dict and list data structures would provide ample flexibility will minimizing any parsing of text (at least directly by me). Before I set out to write a JSON field type, I thought I'd give Google a try and sure enough someone (deadwisdom) had beat me to it. This snippet is really cool in that now I can declare fields of type JSONField() and simple interact with them as python data types however, they get saved to the database as simplejson encoded strings and rehydrated back from strings into their original data structure, leaving you without having to think about how the data will be stored. -
JSONField for Django Models
I was needing to store semi-structured data on a model for a project I am working on, but didn't want to parse strings or create a foreign key to a key/value type table. The use of JSON came to mind via the simplejson library. I thought leveraging Python's dict and list data structures would provide ample flexibility will minimizing any parsing of text (at least directly by me). Before I set out to write a JSON field type, I thought I'd give Google a try and sure enough someone (deadwisdom) had beat me to it. This snippet is really cool in that now I can declare fields of type JSONField() and simple interact with them as python data types however, they get saved to the database as simplejson encoded strings and rehydrated back from strings into their original data structure, leaving you without having to think about how the data will be stored. -
Home for the Dojo Foundation
Finally the Dojo Foundation Web Site, a joined work of people from SitePen and uxebu, has launched. The main purpose of the site is explaining the intention of the Dojo Foundation, decluttering the Foundation from the Dojo Toolkit and giving all the other interesting projects under the hood of the Dojo Foundation a corporate presentation location. You can visit the site, that was build on top of dojango (wohooo) at http://dojofoundation.org. It was great to work together with the people of SitePen and I hope there will be more things in the future where we can join our forces. -
Django Poor Man's Cron
As I have promised in the last blog entry, I am sharing a link to an experimental conceptual app Poor Man's Cron which tends to exploit various bots to implement scheduled tasks.Criticisms, praises, thanks, and suggestions are very welcome! -
Django settings files for development and production
When developing projects with Django, one usually uses at least two deployments of the project: One for developing things and another for the production site. Let’s assume that the development deployment resides on your local computer in the directory /www/project and can be accessed via http://localhost:8000/. The production site uses Apache and mod_python, is available at [...] -
Regular expressions, Friedl and Kodos
Understanding and using the power of regular expressions, or simply regex, is a must for every smart programmer. Django uses them quite often on its elegant URLConf system. I've been using regular expressions for a very long time and have read many books about them but if I have to recommend just one I'll go for the classic Mastering Regular Expressions by Jeffrey Friedl. And nothing better to test you're on the right track while writing your own regular expressions than Kodos, a simple but nice Python based tool, easy to install from any Debian based distro with a quick sudo apt-get install kodos. <!--break--> -
Regular expressions, Friedl and Kodos
Understanding and using the power of regular expressions, or simply regex, is a must for every smart programmer. Django uses them quite often on its elegant URLConf system. I've been using regular expressions for a very long time and have read many books about them but if I have to recommend just one I'll go for the classic Mastering Regular Expressions by Jeffrey Friedl. And nothing better to test you're on the right track while writing your own regular expressions than Kodos, a simple but nice Python based tool, easy to install from any Debian based distro with a quick sudo apt-get install kodos. <!--break--> -
Use double quotes for {% url %} on Django
I recently commented about using the right quotes with Python and simplejson and today I found a similar issue with Django. It happens when using the {% url %} tag on the template system in Django 1.0. {% url %} helps you to avoid hardcoding links and relies on naming your url patterns. Let's suppose we have a url like this in our URLConf: url(r'^add/chatroom/(?P\w+)$', 'myapp_chatroom_add', name='myapp_chatroom_add'), Now you could insert {% url %} in your template to get the url for a link: {% url myapp_chatroom_add chatroom_data="abc" %} Notice I'm passing the string "abc" using double quotes as the chatroom_data parameter. And here's the important part, these two won't work: {% url myapp_chatroom_add chatroom_data=abc %} which does not use quotes at all, or this one: {% url myapp_chatroom_add chatroom_data='abc' %} which uses single quotes. The errors may vary depending on how your code works but the fact is to remember that when passing string based parameters to {% url %} you need to always use double quotes. If you're using numbers you could use either no quotes or double quotes. Single quotes will never work. <!--break--> -
Use double quotes for {% url %} on Django
I recently commented about using the right quotes with Python and simplejson and today I found a similar issue with Django. It happens when using the {% url %} tag on the template system in Django 1.0. {% url %} helps you to avoid hardcoding links and relies on naming your url patterns. Let's suppose we have a url like this in our URLConf: url(r'^add/chatroom/(?P\w+)$', 'myapp_chatroom_add', name='myapp_chatroom_add'), Now you could insert {% url %} in your template to get the url for a link: {% url myapp_chatroom_add chatroom_data="abc" %} Notice I'm passing the string "abc" using double quotes as the chatroom_data parameter. And here's the important part, these two won't work: {% url myapp_chatroom_add chatroom_data=abc %} which does not use quotes at all, or this one: {% url myapp_chatroom_add chatroom_data='abc' %} which uses single quotes. The errors may vary depending on how your code works but the fact is to remember that when passing string based parameters to {% url %} you need to always use double quotes. If you're using numbers you could use either no quotes or double quotes. Single quotes will never work. <!--break--> -
Shifting Bits: My Django Blog is Live
Just a short announcement to say that I am finally free of Wordpress and mod_php on my server. This site is Django-powered! Still lots more that I want to do with it, but my basic requirements are complete (comments, comment moderation, xmlrpc interface for MarsEdit compatibility, rss feeds, and tagging). -
Shifting Bits: My Django Blog is Live
Just a short announcement to say that I am finally free of Wordpress and mod_php on my server. This site is Django-powered! Still lots more that I want to do with it, but my basic requirements are complete (comments, comment moderation, xmlrpc interface for MarsEdit compatibility, rss feeds, and tagging). -
Shifting Bits: My Django Blog is Live
Just a short announcement to say that I am finally free of Wordpress and mod_php on my server. This site is Django-powered! Still lots more that I want to do with it, but my basic requirements are complete (comments, comment moderation, xmlrpc interface for MarsEdit compatibility, rss feeds, and tagging). -
Jutda Helpdesk - A Django-Powered Ticket Tracker for Small Enterprise
I'm a firm believer in providing a great customer support experience to your customers, so when I needed a way to manage customer requests for WhisperGifts, I began putting together an in-house solution. There are a number of great open-source helpdesk packages available, however most of them are written in PHP which is not installed on my server for various reasons. This caused me to begin to write one in my framework of choice, Django. The website for Jutda Helpdesk can be found at www.jutdahelpdesk.com, which includes documentation and links to the Google Code Page which is used for bug tracking and version control. Some of the features include: Full e-mail integration (it can pick up e-mails from your POP3 or IMAP mailboxes) Sends HTML & plain-text e-mails (templates controlled via admin screen) Multiple ticket queues, to use for different products or customer groups Pre-set replies for common ticket responses Built-in reporting & statistics Automatic ticket escalation with the ability to ignore weekends & public holidays * Web-based API to allow 3rd party software integration A full demo is available online where you can try out the features and get a feeling for what it's capable of. There's still a … -
Jutda Helpdesk - A Django-Powered Ticket Tracker for Small Enterprise
I'm a firm believer in providing a great customer support experience to your customers, so when I needed a way to manage customer requests for WhisperGifts, I began putting together an in-house solution. There are a number of great open-source helpdesk packages available, however most of them are written in … -
How to setup Apache, mod_python and a reverse proxy to Lighttpd for Django on Ubuntu
Update: I don't recommend this setup anymore. Use the improved setup of Django with nginx, Apache and mod_wsgi. It's October 2008 and there's no doubt now that serious web development requires working with frameworks, software that allows us, lazy coders, to forget about repetitive tasks and focus on the specifics of each project, the stuff that makes them truly unique. It's pretty obvious too that Django, the Python based web framework, is attracting more developers and companies lately. Guido is a googler since 2005 and the recently launched Google App Engine uses Python and Django. Seriously, there's not a better time to jump into the Django train (no pun intended RoR guys). Experienced programmers can start writing Django applications quickly thanks to the excellent documentation and the free Django book. I've also read and can recommend Practical Django Projects, by James Bennett, part of the Django team, and Learning Website Development with Django, by Ayman Hourieh, a very smart and young Google engineer. Django is really a web framework for perfectionists with deadlines. I'm very near to one and have almost finished coding what will be my first Django based application for Facebook. Yes, I've got a few articles about … -
How to setup Apache, mod_python and a reverse proxy to Lighttpd for Django on Ubuntu
Update: I don't recommend this setup anymore. Use the improved setup of Django with nginx, Apache and mod_wsgi. It's October 2008 and there's no doubt now that serious web development requires working with frameworks, software that allows us, lazy coders, to forget about repetitive tasks and focus on the specifics of each project, the stuff that makes them truly unique. It's pretty obvious too that Django, the Python based web framework, is attracting more developers and companies lately. Guido is a googler since 2005 and the recently launched Google App Engine uses Python and Django. Seriously, there's not a better time to jump into the Django train (no pun intended RoR guys). Experienced programmers can start writing Django applications quickly thanks to the excellent documentation and the free Django book. I've also read and can recommend Practical Django Projects, by James Bennett, part of the Django team, and Learning Website Development with Django, by Ayman Hourieh, a very smart and young Google engineer. Django is really a web framework for perfectionists with deadlines. I'm very near to one and have almost finished coding what will be my first Django based application for Facebook. Yes, I've got a few articles about … -
The Django Toolbar: Updated
So after some late night code slinging to scratch a wild itch of an idea, I rethought my approach in how I forked the code for the Django Debug Toolbar project. Partly this was prompted by some folks that took some time to leave a few comments on the previous post announcing the release -- many thanks! Anyway, I just committed changes to a new fork of the Django Toolbar project that I hope is considering merge worthy by Rob Hudson to get back into the project and my fork can live a short but useful life until my pull request is incorporated. The basics of this change is that you can control whether or not server side logging occurs as well as whether or not the toolbar is displayed via some configuration settings that are documented in the README.rst. Check it out and let me know what you think. I'd like to build some dashboard type tools for browsing the server side logged data. But beyond that I think it is probably ready to start using. -
Exploiting Spammers, Search Engines, and Other Bots
Django is a great platform for building web projects in a clean and manageable way. But when you want to find its relationship with poverty for a blog post on Blog Action Day, it becomes a difficult puzzle. But still that's a great challenge!Django has a large community all over the world and someone who is gold at statistics could write a cool analytical report about djangoers' relations with poverty in the world or the user activity on Blog Action Day site using the maps and numbers provided in the links.The Django community or the social groups mentioned above are just small parts of the big network. Looking at the bigger image of the world, internet, and the future, you might realize that everybody is connected to somebody and something, all those connections get defined in social networks, and the web is like a living and evolving organism. We are kind of going towards a machine that we can use and it can use us (See the Matrix).We can look at a newly created site based on Django as at a small node in the web. The site together with its visitors forms a network. Different APIs and inter-site communication … -
The Django Toolbar: Updated
So after some late night code slinging to scratch a wild itch of an idea, I rethought my approach in how I forked the code for the Django Debug Toolbar project. Partly this was prompted by some folks that took some time to leave a few comments on the previous post announcing the release -- many thanks! Anyway, I just committed changes to a new fork of the Django Toolbar project that I hope is considering merge worthy by Rob Hudson to get back into the project and my fork can live a short but useful life until my pull request is incorporated. The basics of this change is that you can control whether or not server side logging occurs as well as whether or not the toolbar is displayed via some configuration settings that are documented in the README.rst. Check it out and let me know what you think. I'd like to build some dashboard type tools for browsing the server side logged data. But beyond that I think it is probably ready to start using. -
Filter the Django ModelAdmin set
I was playing around today and thought it would be quite cool to modify/filter the query for the ModelAdmin class. Aiming to create helper functionality rather than a security feature. After all django-admin users are (or at least, should be) trusted users. Either way, it can be handy to filter down the options and clear things up a bit. When you make the ModelAdmin class in admin.py you can then override the default queryset method. So say for example you have a set of articles and you only want users to be able to edit articles they have originally posted. So a VERY simple model could look like this; class Article(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=60) content = models.TextField() Then in admin.py; class ArticleAdmin(admin.ModelAdmin): def queryset(self, request): if request.user.is_superuser: qs = self.model._default_manager.get_query_set() else: qs = self.model._default_manager.get_query_set().filter(author = request.user) ordering = self.ordering or () if ordering: qs = qs.order_by(*ordering) return qs And there you have it. Now in the admin the user will only see posts that they are the author of (unless the user is a super_user). Again just to stress this doesn't enforce security (you can get to the other posts to edit by modifying the page address) … -
Passing variables to named patterns via {% url %} in Django templates
When coding Django one of my most important goals is avoiding all kind of hardcoded urls in my applications. Let's see this line from one of my app's URLConf: url(r'^edit/object/(?P<object_id>\w+)/$', 'object_edit', name='object_edit'), This points to a page like /edit/object/123, notice I'm using a named pattern here, and calls a view defined with: def object_edit(request, object_id): Then I can do what I need with the object identified by object_id. Now, imagine I have a list of objects in a template so I can add an edit link to each one of them, something like this: <a href="{% url object_edit object_id=4}">edit object</a> Notice that 4? I put it there just for making my point clear, what I really want to do is something like: <a href="{% url object_edit object_id={{ object.object_id }} %}">edit object</a> but that produces an error like this: TemplateSyntaxError at ... Could not parse the remainder: '{{' from '{{'. It seems a template variable can't be used inside a {% url %} tag, and I guess the same applies to any template tag. After thinking a bit about how other tags work with variables, the {% for %} loop for example, I decided to get rid of the {{ and …