Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
PyCon 2013 Recap---Teaching and Learning with the Python Community
Caktus had a wonderful time at this year’s PyCon conference. We believe strongly in supporting our developers in their quest to become the best coders that they can be and think that being at PyCon is a great way for them to learn about what’s going on in the Python community. We sent ten people to the conference to work at our booth and attend conference events. The organizers of PyCon, headed by Jesse Noller, put on an amazing event that created a space for people to meet face to face in order to work and learn together. During the opening keynote presentation, Jesse Noller shared with PyCon his parting gift to the PyCon community before relinquishing the reins after his last year of heading PyCon. He told the audience that the Python Software Foundation was providing a Raspberry Pi computer to each of the 2,500 conference attendees in the hopes that they would build awesome projects and share them widely. This parting gift to the community was part of his contribution to enable pythonistas as he said to, "build a legacy for Python and the community that enriches and enlivens the next generation of programmers" by "infecting everyone with … -
Multi-file find and replace for {% url “quoted” %} tag in Django 1.5
Django 1.5 deprecates the old {% url %} tag style and uses the new one. The new one needs the url name to be quoted. So instead of {% url public_index %} it must be {% url "public_index" %}. You’ll get an error: ‘url’ requires a non-empty first argument. The syntax changed in Django 1.5, see the docs. Instead of adding quotes to each one in each template manually, I wanted a multi-file find and replace regex. Examples abound of using find with xargs and sed. But here’s a simple Python script and example usage to do just that. Note that it updates the files in-place. Make sure you have a backup and/or they’re committed to version control just in case something goes wrong and messes up your templates. You’ve been warned. Here’s a simple find and replace Python script: import sys import os import re def main(argv=None): if argv is None: argv = sys.argv if len(argv) < 4: print """ Usage: %s find replace filename.txt [filename2.txt...] """ % argv[0] exit find = argv[1] replace = argv[2] filepaths = argv[3:] for filepath in filepaths: text = open(filepath).read() #print re.sub(find, replace, text) new_text = re.sub(find, replace, text) if new_text != text: … -
Best practices with Django on WebFaction
This blog post is about deploying Django apps. It is addressed primarily to WebFaction, but applies to any other hosts else with one-click installers for this kind of app. First, many thanks to WebFaction for their great service and support. I've got very few complaints about them in general. However, I think their approach to setting up Django projects is far from ideal, and makes life harder than it needs to be. The WebFaction Django docs tell us to create a new Django app by using the control panel and choosing an app of type ‘Django’ and then choosing your Django version. This will install an Apache instance with mod_wsgi, and a copy of the Django sources, and set up a basic Django app skeleton. There are lots of problems with this: What happens when there is a security issue with Django? The user will need to have an upgrade mechanism. This is covered in the docs, but it is an 11 step process. And this process is a process they will first have to do in their development environment for testing, in some way, and then again on their live box. How many people will actually do that, especially … -
Github test commit reports for teams
I recently wrote githubinfo. It is a quick and handy script that queries the github API of one or more organizations and gives you a simple report on the amount of commits with tests in the last week. I figured it could be useful to others, so I made it available on pypi, including reasonable documentation of course: https://pypi.python.org/pypi/githubinfo . You can pip install githubinfo (or put it in your buildout). It is just a simple single command and the output looks like this: $ testcommitinfo loading project neerslagradar-site loading project ... ... We want more and better testing. For a quick and dirty quantity indication ('more'), here are the commits that have the string 'test' in of of the commit's touched filenames. Period: 8 days. Github organizations that I queried: ddsc, lizardsystem, nens Projects sorted by amount of commits with tests ----------------------------------------------- lizard-neerslagradar: 11 (25%) lizard-progress: 3 (9%) radar: 1 (33%) ... Committers sorted by amount of commits with tests ------------------------------------------------- Reinout van Rees: 12 (11%) Remco Gerlich: 3 (6%) Arjan Verkerk: 2 (8%) ... Goal I wrote it because we wanted to improve our development process at Nelen & Schuurmans. We wanted more tests. So I wrote a … -
Core Concepts of Django Forms
In my opinion, the concepts behind Django's non-model forms can be listed in just three (3) bullets: Forms render HTML. Forms are "just" Python constructs. Forms validate dictionaries (Python's Key/Value structure). Let's dig in! Forms render HTML. If I construct a Django form: # myapp/forms.py from django import forms class MyForm(forms.Form): title = forms.CharField(required=True) I can render it in a template, or for better clarity in this post, the Python REPL: >>> from myapp.forms import MyForm >>> f = MyForm() >>> f <__main__.MyForm object at 0x1016c6990> >>> print(f) <tr><th><label for="id_title">Title:</label></th> <td><input id="id_title" name="title" type="text" /></td></tr> You can even see this done with initial values in the Django docs: https://docs.djangoproject.com/en/1.5/ref/forms/api/#django.forms.Form.initial Forms are "just" Python constructs. I believe it was Alex Gaynor who said back in 2008 that Django forms were "just" Python constructs. He's right: >>> from myapp.forms import MyForm >>> # class >>> MyForm <class 'myapp.forms.MyForm'> >>> # object >>> form = MyForm() >>> form <myapp.forms.MyForm object at 0x1023f1450> >>> # iterable >>> [x for x in form] [<django.forms.forms.BoundField object at 0x102495990>] >>> [x for x in form.fields] ['title'] >>> # dictionary-like >>> form.fields['title'] <django.forms.fields.CharField object at 0x1024a17d0> Understanding the structure of Django forms is really useful. This structure is … -
Core Concepts of Django Forms
In my opinion, the concepts behind Django's non-model forms can be listed in just three (3) bullets: Forms render HTML. Forms are "just" Python constructs. Forms validate dictionaries (Python's Key/Value structure). Let's dig in! Forms render HTML. If I construct a Django form: # myapp/forms.py from django import forms class MyForm(forms.Form): title = forms.CharField(required=True) I can render it in a template, or for better clarity in this post, the Python REPL: >>> from myapp.forms import MyForm >>> f = MyForm() >>> f <__main__.MyForm object at 0x1016c6990> >>> print(f) <tr><th><label for="id_title">Title:</label></th> <td><input id="id_title" name="title" type="text" /></td></tr> You can even see this done with initial values in the Django docs: https://docs.djangoproject.com/en/1.5/ref/forms/api/#django.forms.Form.initial Forms are "just" Python constructs. I believe it was Alex Gaynor who said back in 2008 that Django forms were "just" Python constructs. He's right: >>> from myapp.forms import MyForm >>> # class >>> MyForm <class 'myapp.forms.MyForm'> >>> # object >>> form = MyForm() >>> form <myapp.forms.MyForm object at 0x1023f1450> >>> # iterable >>> [x for x in form] [<django.forms.forms.BoundField object at 0x102495990>] >>> [x for x in form.fields] ['title'] >>> # dictionary-like >>> form.fields['title'] <django.forms.fields.CharField object at 0x1024a17d0> Understanding the structure of Django forms is really useful. This structure is … -
Now it's your turn
I just watched Jacob's talk on "Porting Django apps to Python 3", and realised it was time to tackle my own small Django apps. The problem with porting is that you need your dependencies to be ported first. But now that Django has Python 3 support, the finger is no longer pointing at Django — it is pointing at all of us with Django apps that have only Django as a dependency (or other dependencies that are already ported to Python 3). As Jacob put it at the end of the talk, it’s your turn. So, I took the challenge, and here is a walk through of what you need to do, and what I had to do: Find an app/library you've written that has very few dependencies, or all dependencies already ported to Python 3. In my case, django-easyfilters. Not a massively popular library, but it has had over 1000 downloads, and I know some people use it. Install tox and create a tox.ini file to run your test suite on more than one version. Start with all the Django versions you want to support, with Python 2.x combinations (Python 2.6 and 2.7 recommended), and Python 3.3. My tox.ini … -
Mails amb Django - IV
Amb tot el que hem vist fins ara podem organitzar els nostres enviaments de correus i mantenir al seu manteniment organitzat encara que el nombre d'opcions sigui gran. Hi ha encara un grapat d'escenaris que és interessant tractar, ja que ens els trobarem sovint. Pensem en aquests possibles escenaris: Ens hem de connectar a un servidor SMTP extern i el temps de connexió és gran, la qual cosa fa que la nostra aplicació web no respongui. Tenim un entorn de preproducció on els correus no s'enviïn però on volem mantenir registre del que s'hauria enviat. Volem mantenir un registre dels correus que s'envien dins la nostra aplicació. El primer escenari es pot resoldre amb un servidor de correu local y fent realy cap al servidor final, però això a vegades no és possible ja que no tenim la gestió del servidor de correu. També ho podem resoldre amb un sistema de coes, és a dir, l'enviament de correu es posa com a tasca i és un altre programa (un worker) el que se n'encarrega de fer l'enviament. La combinació de Celery+Redis ens pot anar bé, però també estam afegint un factor gran de complexitat: hem de tenir Redis instal·lat, configurar … -
Getting AngularJS Authentication Working with Django
django-angular-auth is a very simple example app or seed to get AngularJS authenticating using Django and Tastypie. Although AngularJS' documentation has gotten much better, it still took me quite a while to figure out what exactly was the best path to take. Also, there are a few gotchas with allowed headers and cross-site security which are already solved in the example. Take a look and let me know what you think. -
Custom Django Template Tag: Generate the absolute URL
Custom Django Template Tag: Generate the absolute URL -
Mails amb Django - III
Fins ara hem vist com podem enviar correus electrònics amb format text, amb format HTML en el dos formats. També hem vist que podem generar el nostres correus a partir de plantilles Django. A poc que l'aplicació es vaig fent més gran veurem que és molt interessant poder tenir tots els correus que enviam centralitzats, de manera que no hagem d'anar a cercar per codi i per les diferents aplicacions els correus que enviam. Sovint a més els correus que enviam són semblants: van dirigits a la mateixa gent, o tenen informació que canvia molt poc d'uns als altres, com el peu del missatges o la salutació. Una situació ideal per utilitzar dues coses: les plantilles de Django per a la generació de correus i aprofitar com Django va a cercar les plantilles per tenir tots els correus centralitzats a un mateix lloc, i per una altra banda l'herència pròpia de Python que ens permetrà guanyar temps a l'hora de generar els correus i farà que siguem menys propensos a error a l'hora de generar-los. Ara és quan a un se li encén la bombeta i es posa com a un boig a generar classes de Python per a la … -
Useful Packages for Django projects (part 1)
This is the first of a series of posts about which libraries and tools we use for our Django development. Almost every Nomadblue project will have the following packages in their requirements.txt pip file. Probably most of the readers won't find much news here; however, eventually someone can realize he was missing something that could be leveraging their productivity or making life easier. Pillow As stated by the library documentation, Pillow is the "friendly" PIL fork by Alex Clark and Contributors. With Pillow you can stay cool as it installs smoothly using pip, and also you can sleep at night because somebody is maintaining the library in a healthy state through continuous integration, regular releases, bug fixing and development on github, and active participation on the Imaging-SIG. South When we started with Django (more than 5 years so far) there were a bunch of migration libraries out there, with different approaches. Andrew Godwin became a frequent flyer on the Django community, eventually winning the pulse and gathering the Djangonauts until South became a "must" or "de-facto" library to manage your database schema and data transitions. Worth mentioning that Andrew recently applied at kickstarter for a call to develop "a new, … -
Django CMS: cannot import name plugin_pool
Django CMS: cannot import name plugin_pool -
Overloading Django Form Fields
One of the patterns we get positive feedback for mentioning in our book is overloading form fields. The problem this pattern handles is the use case of when we have a model with a field(s) that allows for blank values, how do we force users to enter values? For example, assuming the following model: # myapp/models.py from django.db import models class MyModel(models.Model): name = models.CharField(max_length=50, blank=True) age = models.IntegerField(blank=True, null=True) profession = models.CharField(max_length=100, blank=True) bio = models.TextField(blank=True) How do we make all those fields (name, age, profession, bio) required without modifying the database? This is the way I used to do it: # myapp/forms.py from django import forms from .models import MyModel class MyModelForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True) age = forms.IntegerField(required=True) profession = forms.CharField(required=True) bio = forms.TextField(required=True) class Meta: model = MyModel See the problems with this approach? MyModelForm is nearly a copy of MyModel, and was in fact created by copy/pasting model and then modifying it. In software engineering parlance, it violates the principal of Don't Repeat Yourself (DRY) and is fertile ground for introducing bugs. MyModelForm has a bug! Can you spot the bug? The code example below illuminates where I purposefully/gleefully placed an error: class MyModel(models.Model): # … -
Overloading Django Form Fields
One of the patterns we get positive feedback for mentioning in our book is overloading form fields. The problem this pattern handles is the use case of when we have a model with a field(s) that allows for blank values, how do we force users to enter values? For example, assuming the following model: # myapp/models.py from django.db import models class MyModel(models.Model): name = models.CharField(max_length=50, blank=True) age = models.IntegerField(blank=True, null=True) profession = models.CharField(max_length=100, blank=True) bio = models.TextField(blank=True) How do we make all those fields (name, age, profession, bio) required without modifying the database? This is the way I used to do it: # myapp/forms.py from django import forms from .models import MyModel class MyModelForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True) age = forms.IntegerField(required=True) profession = forms.CharField(required=True) bio = forms.TextField(required=True) class Meta: model = MyModel See the problems with this approach? MyModelForm is nearly a copy of MyModel, and was in fact created by copy/pasting model and then modifying it. In software engineering parlance, it violates the principal of Don't Repeat Yourself (DRY) and is fertile ground for introducing bugs. MyModelForm has a bug! Can you spot the bug? The code example below illuminates where I purposefully/gleefully placed an error: class MyModel(models.Model): # … -
In Memory Of Malcolm
In Memory Of Malcolm -
Mails amb Django - II
Enviar un e-mail fent servir plantilles Django Com ja tots sabeu Django té un sistema de plantilles molt eficaç. Normalment les fem servir per mostrar l'html de les nostres aplicacions web, però no estan limitades a això, i com veurem les podem fer servir per generar els nostre correu. La manera de fer-ho és fent servir render_to_string que podem trobar a django.template.loader. Aquesta funció agafa com a paràmetres el nom de la plantilla que volem fer servir i un diccionari amb els paràmetres que farem servir a la plantilla. Agafa un tercer paràmetre, que ha de ser de tipus Context, però que per als nostres objectius no la farem servir gaire. Quan volem enviar un correu ho podem fer dins la vista, però sovint ho farem des de classes d'utilitat, el model o un formulari, on el request no està disponible. Per això hem de tenir em compte que la majoria de vegades no tindrem accés a les variables que normalment estan accessibles a les plantilles mitjançant el context processors. Així doncs que si el correu te links pensau que tot el que siguin referències a arxius i links forçosament necessiten de Sites, MEDIA_URL i STATIC_URL (o fer servir el … -
Django Webmaster Verification
Today I have released version 0.2.1 of django-webmaster-verification. I never took the time to write a post about it, so here you go. The Django application helps to quickly register with various webmaster tools like: Google Webmaster Tools Bing Webmaster Tools Yandex Webmaster Tools Majestic SEO Alexa These tools can help you to monitor your site's performance in search engines which can be quite useful. Django-webmaster-verification is a very simple app that I wrote to avoid repeating setting up the Google tools on each site I manage. It grew a little from there, and today I added support for the Alexa tools. I'm not a big fan of Alexa and I don't think their metrics are very useful. All the people I know who use it are into something like internet marketing, SEO, etc. Nothing against that, but it makes me think that the Alexa data does not represent an average sample of the web population. Anyway, somebody requested it, more power to him! So if you're a Django developer and at least a little interested in SEO give it a try. -
Django Webmaster Verification
Today I have released version 0.2.1 of django-webmaster-verification. I never took the time to write a post about it, so here you go. The Django application helps to quickly register with various webmaster tools like: Google Webmaster Tools Bing Webmaster Tools Yandex Webmaster Tools Majestic SEO Alexa These tools can help you to monitor your site's performance in search engines which can be quite useful. Django-webmaster-verification is a very simple app that I wrote to avoid repeating setting up the Google tools on each site I manage. It grew a little from there, and today I added support for the Alexa tools. I'm not a big fan of Alexa and I don't think their metrics are very useful. All the people I know who use it are into something like internet marketing, SEO, etc. Nothing against that, but it makes me think that the Alexa data does not represent an average sample of the web population. Anyway, somebody requested it, more power to him! So if you're a Django developer and at least a little interested in SEO give it a try. -
Mails amb Django - I
En aquest article, o millor dit, sèrie d'articles, intentaré explicar el millor que pugui la problemàtica que ens trobam en el dia a dia la gent que hem d'enviar correus electrònics des de les nostres aplicacions Django, no tant des del punt de vista de com es fa, sinó del programador que té que desenvolupar d'aplicació. Veurem distints escenaris i com podem tenir una solució que s'adapta a cada un d'ells, de manera que acabem amb un petit receptari, que esper anar ampliant amb l'adjuda de tots. La referència fonamental per Django és la documentació "sending email", miraré de no repetir-la molt, però per completitud convé fer una petita introducció. Configurar el servidor Volem enviar un e-mail ràpid en resposta a un esdeveniment. Per a poder enviar un e-mail des de la nostra aplicació Django prèviament haurem d'haver configurat en nostre servidor SMTP. Això es fa amb les variables del settings EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER i EMAIL_HOST_PASSWORD. Ja que hi som convé definir el mail que farem servir en cas que no el posem de manera explícita al DEFAULT_FROM_EMAIL Normalment no hem de definir res si el nostre servidor d'e-mail és el mateix servidor on està l'aplicació i tenim un SMPT … -
Django AJAX Edit Mode
I can't even remember where I saw this, but the suggestion was that viewing and editing data are different operations, and should be different modes. For instance, when viewing some data, you would need to explicitly decide to enter the edit mode. In a web page, this would be by following a link to a page that had a form that allowed for editing. Attempting to submit the form would result in either the same page being displayed, along with any validation errors, or being redirected back to the viewing page. This is the pattern I've been working on implementing with a module for our work system. However, we can reduce the amount of data sent, and the amount of page redraw, by using dynamic element replacement. So, we can have some AJAX that loads in the edit form in-place, and replaces the view form. Saving it then either returns the edit form with validation errors, or the view form again. We can do all of this with one view. Depending upon how it is accessed, it will return either a different template, or render the template differently. ## Solution One: render a different template. {% highlight python %} # … -
My First Kickstarter
In days gone by, getting money from a group of random people over the internet was probably a crime. Now it's the next step in project funding. UPDATE: The kickstarter has gone very, very well. I'll be writing a long post as it draws to a close about the whole experience. I've had the idea of crowdfunding an open source project for a while now, but it wasn't until a few weeks ago that it occurred to me that I could combine my one free day a week (which I used to use for flying lessons) and my pet Django feature into one crowdfundable whole. Thus, today I'm launching the Schema Migrations for Django project on Kickstarter. I've set a goal which would pay for a decent amount of my free days, and I'm hopeful that it will be reached. I'll do a post-mortem blog post on the project and what running a Kickstarter project of this type is like once it's over in two weeks' time - I can say, however, that I've had invaluable feedback from friends and members of the Django community to help me polish the descriptions, tweak the rewards, and generally get it feeling like … -
Configuring No-WWW for IIS on Azure
As part of the rollout of my site redesign, I’ve also switched hosts from WebFaction to Windows Azure. WebFaction was a great value for a shared host, and I’ll probably continue to use it in the future for small Python/Django projects, but I’ve been experimenting with Azure on some other projects and took the opportunity to make the switch. Where’d my .htaccess go? Azure Web Sites use IIS as a web server, not the more common Apache (or Nginx) server widely used across the Unix world. While Azure handles all of the server setup and maintenance for many cases, you’ll still need to get your hands dirty if you need custom handling. One of the big behaviors I needed to maintain in the migration was to continue adherence to the No-WWW philosophy. This means making dancarroll.org the canonical name of my site, with www.dancarroll.org redirecting to the no-www version. I had this set up on the previous iteration of the site using an Apache .htaccess file. It was very easy to find examples of how to do this across the web. RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=permanent,L]IIS, however, does not use .htaccess files. Instead, … -
Logging in Django
This is a talk I gave at Agiliq on 21-March-2013 as a part of the Hyderabad Python Meetup Group -
Django Meetup – March 21, 2013
Today I had the pleasure of talking about how my team switched from PHP to Python (Django) and the realizations that I had after the process. I learnt a lot about web development in the process and had a great time making the site better for our users. Related posts: Welcome to ProcrastinatingDev DjangoCon 2011 – Real world Django deployment using Chef DjangoCon 2011 – Confessions of Joe Developer