Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
django-validation now includes inheritance support
I’m happy to announce django-validation got field type inheritance support since a couple of minutes. This means your form fields will be validated starting from the most base field type (django.newforms.Field) up to the actual field type (no multiple-inheritance supported though). In the example I wrote yesterday, when using a TestField field, this field will be validated as a django.newforms.Field (a “required” check will be done), then as a django.newforms.CharField (“min_length” and “max_length” checks), and finally as a TestField. A normal CharField would be validated as a Field first, then as a CharField, etc. The returned errors will be a list of all errors found, starting with the most basic one (the ones found by the most general class, Field). Next to this, all generated Javascript code should be namespaced now (based on Python module and class names), although there might be some bad things left, I’m no Javascript guru. The generated code might be somewhat messy. Current Python code is most certainly ugly and will need more rewrites. Next to this, other field types should be added, and some tests would be nice too. I made a snapshot of yesterday’s sample (with some changes, the ClientValidator API slightly changed), … -
Deploying Compacted Javascript with Django
Here is a small extension to the manage command to make deployment of compacted javascript easier (hopefully). I think this is better explained with a usage example. I have the templates referring both the standard javascript files for easier debugging and compacted ones for deployment (the debug variable is the standard one and allows the split between development/deployment). {% if debug %} <script src="{{ MEDIA_URL }}js/jquery-1.2.2b.js" type="text/javascript"></script> <script src="{{ MEDIA_URL }}js/jquery.cookie.js" type="text/javascript"></script> <script src="{{ MEDIA_URL }}js/jquery.dimensions.js" type="text/javascript"></script> <script src="{{ MEDIA_URL }}js/jquery.hoverIntent.js" type="text/javascript"></script> <script src="{{ MEDIA_URL }}js/jquery.cluetip.js" type="text/javascript"></script> {% else %} <script src="{{ MEDIA_URL }}js/jqbase-min.js" type="text/javascript"></script> {% endif %} In the settings file I maintain some variables for the JSC command. JSC_PATH = '/path_to_media/static/js' JSC_FILES = ( ('jqbase-min.js',('jquery-1.2.2b.js', 'jquery.cookie.js', 'jquery.dimensions.js', 'jquery.hoverIntent.js', 'jquery.cluetip.js')), ('jqui-min.js',('ui.mouse.js','ui.draggable.js', 'ui.draggable.ext.js', 'ui.droppable.js', 'ui.droppable.ext.js')) ) # either jsmin or jspacker, defaults to jsmin JSC_METHOD = 'jsmin' The first one is the path to the javascript files, the second is a list of compacted filenames and list of files to be included in the compacted one. The third setting is the method to compact the javascript, with options being the jsmin or the jspacker. Then in the command line I run ./management.py jsc to build the compacted files before deployment. … -
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’, …