Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
django-validation: an introduction
Some time ago I wrote this generic AJAX Django form validation code. Some people didn’t like this, as AJAX should not be used to perform form validation, which is sometimes true, sometimes not, as I pointed out before. So I’ve been thinking since some time to create a Django templatetag which allows one to generate client-side Javascript form validation code without writing any code himself (unless using custom widgets). Today I got into it. The resulting project is called django-validation. It basicly allows one to write a Newforms form class, and generate client-side validation code for this form in a template. Currently only CharField validation is implemented, more should follow soon and is easy to add. Next to validation of built-in field types, one can also add code to validate custom fields. This can be done inside an inner class of the field class. The current release is very alpha-grade software, a lot of enhancements could be done, and most certainly more standard field type validators should be written. Next to this, field type inheritance isn’t supported for now (so if your field type A inherits CharField, no CharField validation will be done), this should change soon. Patches are, obviously, … -
Django Flatpages with Debug Set to False
After deploying a site I am working on to a preview server running apache/mod_python, it was the first time serving up the site in something other than python manage.py runserver. I worked through a number of issues that I found quick answers for on the FAQ site for django, but one in particular I couldn't figure out, but eventually got pointed to the obvious in the irc channel for django. The site has a number of flatpages, which I have come to learn is a middleware trick where when a url doesn't match anything and right before a 404 normally would be thrown giving the Page Not Found error, it checks against any flatpage "urls" you have registered the database with static content. If it finds something it will return that content, if not the 404 bubbles back out of the middleware and goes to the user. Everything worked fine with DEBUG=True in my settings.py file. However, when I changed it to DEBUG=False, I got a 500 Internal Server Error but then when I looked at my error.log, I could see a django exception saying it couldn't find the 404.html. This made no sense to me at all. Why would … -
Django Flatpages with Debug Set to False
After deploying a site I am working on to a preview server running apache/mod_python, it was the first time serving up the site in something other than python manage.py runserver. I worked through a number of issues that I found quick answers for on the FAQ site for django, but one in particular I couldn't figure out, but eventually got pointed to the obvious in the irc channel for django. The site has a number of flatpages, which I have come to learn is a middleware trick where when a url doesn't match anything and right before a 404 normally would be thrown giving the Page Not Found error, it checks against any flatpage "urls" you have registered the database with static content. If it finds something it will return that content, if not the 404 bubbles back out of the middleware and goes to the user. Everything worked fine with DEBUG=True in my settings.py file. However, when I changed it to DEBUG=False, I got a 500 Internal Server Error but then when I looked at my error.log, I could see a django exception saying it couldn't find the 404.html. This made no sense to me at all. Why would … -
Django Custom Filter Registration
I wrestled with this one for about an hour last night before realizing it was rather simple. Following the instructions to create a custom template filter, I thought everything was simple and made since until when I tried to load the page to test it. The page spewed a stack trace telling me that it couldn't find the custom filter I was trying lo load with: {% load website.app.custom_filters %} {% filter htmlcompress %} ... {% endfilter %} I then realized that I had registered it like so: website/app/template_tags/custom_filters.py from django import template register = template.Library() @register.filter("htmlcompress") It seems that there is some magic that occurs that loads the custom_filters.py module in a global namespace so that doing this in my base template works: {% load custom_filters %} {% filter htmlcompress %} ... {% endfilter %} Thought I'd post this in case I am not the only new person to django wrestling with this. -
Django Custom Filter Registration
I wrestled with this one for about an hour last night before realizing it was rather simple. Following the instructions to create a custom template filter, I thought everything was simple and made since until when I tried to load the page to test it. The page spewed a stack trace telling me that it couldn't find the custom filter I was trying lo load with: {% load website.app.custom_filters %} {% filter htmlcompress %} ... {% endfilter %} I then realized that I had registered it like so: # website/app/template_tags/custom_filters.py from django import template register = template.Library() @register.filter("htmlcompress") It seems that there is some magic that occurs that loads the custom_filters.py module in a global namespace so that doing this in my base template works: {% load custom_filters %} {% filter htmlcompress %} ... {% endfilter %} Thought I'd post this in case I am not the only new person to django wrestling with this. -
StaticGenerator 1.1
StaticGenerator for Django has been updated to version 1.1. This update adds file/path deletion, and support for HttpRequest.get_host() which would cause StaticGenerator to fail on Django trunk. -
Running Multiple Django Versions in Development
I have needed to use different revisions of the django trunk at different points in time (in testing locally a new revision before upgraded in production, or working on two different projects that deploy to two different production environments, etc). There may be a better way, but how I have handled it pretty painlessly is by running this script: !/bin/bash rm -rf /[YOUR PATH]/$1 svn co -r $1 http://code.djangoproject.com/svn/django/trunk/django /[YOUR PATH]/$1 sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django sudo rm /usr/bin/django-admin sudo ln -s /[YOUR PATH]/$1/ /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django sudo ln -s /[YOUR PATH]/$1/bin/django-admin.py /usr/bin/django-admin echo "Switched to" $1 It takes a single parameter, a revision number. ./switch.sh 7000 I run this script from within a directory in my home directory called "django". You will likely need to change the paths in the script above if you are not running Python 2.5 on Mac OSX. Also, remember to substitute "[YOUR PATH]" for the base location of where you want to store the django code. -
Running Multiple Django Versions in Development
I have needed to use different revisions of the django trunk at different points in time (in testing locally a new revision before upgraded in production, or working on two different projects that deploy to two different production environments, etc). There may be a better way, but how I have handled it pretty painlessly is by running this script: !/bin/bash rm -rf /[YOUR PATH]/$1 svn co -r $1 http://code.djangoproject.com/svn/django/trunk/django /[YOUR PATH]/$1 sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django sudo rm /usr/bin/django-admin sudo ln -s /[YOUR PATH]/$1/ /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django sudo ln -s /[YOUR PATH]/$1/bin/django-admin.py /usr/bin/django-admin echo "Switched to" $1 It takes a single parameter, a revision number. ./switch.sh 7000 I run this script from within a directory in my home directory called "django". You will likely need to change the paths in the script above if you are not running Python 2.5 on Mac OSX. Also, remember to substitute "[YOUR PATH]" for the base location of where you want to store the django code. -
StaticGenerator 1.0.1
As was pointed out there was a rather stupid bug in StaticGenerator: it didn’t import Model which would cause it to fail. Sorry. -
More good words for z3
Electric Duncan some more good things to say about zope3 or z3 here, this time it's vs django. To a certain extent I do agree with some of the things mentioned in that article. At times I do feel that I am trying to bend django to my will when I was coding my application, but alas, I am too green in z3 to give any meaningful comment regarding the comparison. Here, duncan mentions something that piqued my interest - Coding his application in z3, with learning curve thrown in took him two days ! Now that is a wow-ser for me ! Although at the back of my mind the article look more slanted towards zope than django which might explain why the author felt more at home with z3, but then it's a good read after all and has inspired me more to go towards giving z3 another serious look for my web development work. -
Announcing StaticGenerator for Django
Want to speed up your Django app? StaticGenerator is a Python class for Django that makes it easy to create static files for lightning fast performance. It accepts strings (URL), Models (class or instance), Managers, and QuerySets in a simple syntax. -
Cool Django Apps / Frameworks / Add-Ons
Ran across three really cool looking extensions to django: databrowseDatabrowse is a Django application that lets you browse your data. As the Django admin dynamically creates an admin interface by introspecting your models, Databrowse dynamically creates a rich, browsable Web site by introspecting your models. sitemap Django comes with a high-level sitemap-generating framework that makes creating sitemap XML files easy. webdesign The django.contrib.webdesign package, part of the “django.contrib” add-ons, provides various Django helpers that are particularly useful to Web designers (as opposed to developers). I am anxious to given these items a spin, especially databrowse. -
Cool Django Apps / Frameworks / Add-Ons
Ran across three really cool looking extensions to django: databrowseDatabrowse is a Django application that lets you browse your data. As the Django admin dynamically creates an admin interface by introspecting your models, Databrowse dynamically creates a rich, browsable Web site by introspecting your models. sitemap Django comes with a high-level sitemap-generating framework that makes creating sitemap XML files easy. webdesign The django.contrib.webdesign package, part of the “django.contrib” add-ons, provides various Django helpers that are particularly useful to Web designers (as opposed to developers). I am anxious to given these items a spin, especially databrowse. -
Django Fixtures and Flatpage Deployment
I was introduced today to the concept and django feature known as Fixtures, while reading my dead-tree version of the new django book. I am currently building a small site, fairly simple and mostly static. I have written an app that is my own take on the flatpages that are in django.contrib (a post on this later) -- I basically needed a little more flexibility for different islands of content. In building this site and setting up the appropriate flatpages in my development, I realized that I am going to need to seed the database when I release to production or else there are going to be a lot of 404 errors. Also, since the pages are referred to in my menus, I need for the url on the flatpage model to be exact. It's not that many pages, but still, I thought, there had to be a better way that either manually hand entering all the data, troubleshooting 404s for typos in the url field, or doing any manual exporting of data at the mysql prompt. As if by some divine revelation, I happened across the chapter in the book talking about django-admin dumpdata/loaddata. What's cool about this is … -
Django Fixtures and Flatpage Deployment
I was introduced today to the concept and django feature known as Fixtures, while reading my dead-tree version of the new django book. I am currently building a small site, fairly simple and mostly static. I have written an app that is my own take on the flatpages that are in django.contrib (a post on this later) -- I basically needed a little more flexibility for different islands of content. In building this site and setting up the appropriate flatpages in my development, I realized that I am going to need to seed the database when I release to production or else there are going to be a lot of 404 errors. Also, since the pages are referred to in my menus, I need for the url on the flatpage model to be exact. It's not that many pages, but still, I thought, there had to be a better way that either manually hand entering all the data, troubleshooting 404s for typos in the url field, or doing any manual exporting of data at the mysql prompt. As if by some divine revelation, I happened across the chapter in the book talking about django-admin dumpdata/loaddata. What's cool about this is … -
getting to pesky foreign key data in django
Optimizing databases is a good practice and should be done for any enterprise applications, but as all things go there is a price to pay. The price you pay is when calling back and displaying the data into one can be real PITA. django is a damn good framework and allows you to do work fast with a pedal-to-the-metal feel but then certain amounts of work still has to be done when you have foreign keys defined.Say you have a database with two tables : contacts and address. The relationship of the two tables are of the one to many kind, I could never really wrap my head around the one-many many-one many-many thingy so let me just say it in layman so I understand it better myself. "One contact can have one or more than one address"class Contacts(models.Model):..... bla blaclass Address(models.Model): customer_id=models.ForeignKey(Contacts,edit_inline=models.STACKED,num_in_admin=2)So in the code above you have basically linked both the tables together using a ForeignKey relationship. the 'edit_inline' ... mumbo jumbo just tells django to add the address field into the main Contacts form during creation and modification and not as a pop up link ( This is important and could be a clincher for normal users … -
Filtering foreign key choices in newforms-admin
I decided it was time to learn something about the newforms-admin branch of Django, so I set out to try to write a couple of simple models for administering a mail server (something we always needed at GMTA, but I have never really liked any of the currently available options). Here is the models so far: class Customer(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() def __str__(self): return self.name class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) customer = models.ForeignKey(Customer) class Domain(models.Model): name = models.CharField(max_length=100) customer = models.ForeignKey(Customer) def __str__(self): return self.name def save(self): # When a user adds a Domain, save the current customer. if not self.id: self.customer = get_current_user().customer_set.all()[0] # Call the super save method super(Domain, self).save() class Mailbox(models.Model): name = models.CharField(max_length=100) domain = models.ForeignKey(Domain) password = models.CharField(max_length=100) def __str__(self): return '%s@%s' % (self.name, self.domain) class Meta: verbose_name_plural = "mailboxes" class Alias(models.Model): name = models.CharField(max_length=100) domain = models.ForeignKey(Domain) destination = models.EmailField() def __str__(self): return '%s@%s -> %s' % (self.name, self.domain, self.destination) class Meta: verbose_name_plural = "aliases" Model notes There is a few gotchas in the above model code: Remember to add AUTH_PROFILE_MODULE to your settings. See the Django Book on user profiles for details. I use a thread locals hack to … -
Configure Mercury mail transport system for external mail
Usually I develope my projects locally on my pc. Needless to say that you sometimes have to send an email from your script to external mail to check if everything is fine. So you need to configure your system in a way that your local apache webserver is able to send mail to external addresses. I always use XAMPP for Windows because it contains everything you need for developing PHP applications as well as all the stuff for sending mails: fake sendmail und Mercury Mail Transport System. I reference to XAMPP 1.6.5 (for Windows) and Mercury 4.5 here. Mercury is already pre-configured in XAMPP - all settings that I don't explicitly address stay as they are :) I'm writing this because I'm not a mail professional and read a lot of tutorials and none of them really worked. So I extracted what I needed and put it all together. An important assumption for this tutorial is that you have your own SMTP server, for example the one that your webspace hoster provides. So let's get started: start Mercury (using the XAMPP Controlpanel) and then open the admin panel. first of all we disable the HTTP server of Mercury so that … -
Configure Mercury mail transport system for external mail
Usually I develope my projects locally on my pc. Needless to say that you sometimes have to send an email from your script to external mail to check if everything is fine. So you need to configure your system in a way that your local apache webserver is able to send mail to external addresses. I always use XAMPP for Windows because it contains everything you need for developing PHP applications as well as all the stuff for sending mails: fake sendmail und Mercury Mail Transport System. I reference to XAMPP 1.6.5 (for Windows) and Mercury 4.5 here. Mercury is already pre-configured in XAMPP - all settings that I don't explicitly address stay as they are :) I'm writing this because I'm not a mail professional and read a lot of tutorials and none of them really worked. So I extracted what I needed and put it all together. An important assumption for this tutorial is that you have your own SMTP server, for example the one that your webspace hoster provides. So let's get started: start Mercury (using the XAMPP Controlpanel) and then open the admin panel. first of all we disable the HTTP server of Mercury so that … -
Configure Mercury mail transport system for external mail
Usually I develope my projects locally on my pc. Needless to say that you sometimes have to send an email from your script to external mail to check if everything is fine. So you need to configure your system in a way that your local apache webserver is able to send mail to external addresses. I always use XAMPP for Windows because it contains everything you need for developing PHP applications as well as all the stuff for sending mails: fake sendmail und Mercury Mail Transport System. I reference to XAMPP 1.6.5 (for Windows) and Mercury 4.5 here. Mercury is already pre-configured in XAMPP - all settings that I don't explicitly address stay as they are :) I'm writing this because I'm not a mail professional and read a lot of tutorials and none of them really worked. So I extracted what I needed and put it all together. An important assumption for this tutorial is that you have your own SMTP server, for example the one that your webspace hoster provides. So let's get started: start Mercury (using the XAMPP Controlpanel) and then open the admin panel. first of all we disable the HTTP server of Mercury so that … -
Comment Notification in Django
After receiving a number of spam comments on my blog, I decided to utilize Django's built-in signal dispatch system to notify me via email when I receive a comment. Code included. -
Django ModelForm and newforms
Browsing the Django code after a recent svn up shows that newforms.form_for_instance and friends are deprecated and that you should use a ModelForm instead. This post gives a brief example of how to do this. -
Django generic AJAX form validation
I just created a generic view for Django which allows a developer to easily add AJAX-style form validation to a newforms based form. The system needs one server-side view, and some client-side JavaScript. You can find the view code in my Django snippets Git repository. The view only works with POST requests. It takes a standard HttpRequest and some options: form_class: this parameter defines the newforms class to validate against. It can be specified in the extra args parameter of the view’s urlconf. If you don’t specify it, the ‘form_class’ POST field will be used. If this doesn’t exist either, an exception is raised. The parameter can be a newforms form instance, a string, or a class (which should be a subclass of BaseForm). format: the serialization format to use. Currently only ‘json’ is supported. args: extra argument list to provide to the form constructor (shouldn’t be provided in most cases) kwargs: extra argument dics to provide to the form constructor (shouldn’t be provided in most cases) Next to the server-side view you’ll need some pretty basic JavaScript code on client side. I use JQuery and the JQuery Form plugin. Here’s some sample code, assuming the form ID is ‘my_form’, … -
Best tech bits of 2007
Número uno: Duels.com Launched in Q4, Duels is a seriously addictive online fantasy dueling game where players collect items to kit out their characters and challenge each other to a battle shadow fight style. I came across it via TechCrunch and now can't stop signing in for a sly duel or 10. The beauty of it is the asynchronous game play, which means I challenge a bunch of players and then come back in an hour or two to check the results or respond to any challenges issued to me. Perfect. Do yourself (and me) a favour and sign up using this link. You'll have the satisfaction of knowing you're helping me earn a nifty service badge - just don't blame me when you lose a week of your life! Nummer twee: Twitter (and twitterific) Ah twitter! Strictly speaking twitter belongs in 2006, but I can't help but include it here. Part chat, part mircoblog, part txt, twitter is a communication platform that informs the future. Or something. Someone far smarter that me will soon come up with a killer app to push the platform, but until then, it's an integral part of my day. I've met quite a few … -
Filesystem issues and django-couchdb work
Last night, when shutting down my laptop (which had been up for quite a long time because of suspend/resume niceness), it crashed. I don’t know what exactly happened: pressed the GNOME’s logout button, applications were closed, until only my background was visible, then the system locked up, so I suspect my X server (some part of it, GPU driver (fglrx) might be the bad guy). I was able to sysrq s u o, so I thought everything would be relatively fine. This morning I powered on my system, and while booting, fsck of some partitions was taking a rather long time. It’s pretty normal fsck was taking somewhat longer, but not thát long… I’m using JFS on most logical volumes. When the consistency check of my /home partition was done, a whole load of invalid files was displayed and later on moved to lost+found: 34068 files. Once booted, I scanned my filesystems again, rebooted, logged in, started X. Everything started fine, until I launched Evolution: it presented my the ‘initial run’ wizard. Other issues (on first sight): all Firefox cookies were gone, and Pidgin’s blist.xml was corrupted. When using my old computer (which had frequent lockups on heavy IO usage) …