Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Editar y traducir inline en Django fácilmente
Desde Yaco nos traen las aplicaciones pluggables django-inlinetrans y django-inplaceedit que permiten editar traducciones de templates y objetos de nuestros modelos desde el frontend de nuestro proyecto... -
Dropbox file upload handler for django
Dropbox announced new pro plans last week and some accounts have had their storage size doubled. Wouldn't it be wonderful if we could upload all our files to dropbox from our django webapp? In this post, I write a custom file upload handler that will upload files from our application to dropbox. Let us see how to use the custom file upload handler. Install the Dropbox Python SDK before you setup your django app to handle the file uploads. In your settings.py, add the following attributes (with the values filled): DROPBOX_APP_KEY = "" DROPBOX_APP_SECRET_KEY = "" DROPBOX_APP_ACCESS_TOKEN = "" DROPBOX_APP_ACCESS_TOKEN_SECRET = "" # Optional values below # The folder where you want the files uploaded. # Example: /Public or / DROPBOX_FILE_UPLOAD_FOLDER = "" # The value below may be either 'app_folder' or 'dropbox' DROPBOX_ACCESS_TYPE = "" The DROPBOX_APP_KEY and DROPBOX_APP_SECRET_KEY are provided to you when you create a new dropbox app. Fetching the access token and access token secret is outside the scope of this blog post but you can follow the Getting Started Guide until the Get an access token section and then paste the access token key and secret in the DROPBOX_APP_ACCESS_TOKEN and DROPBOX_APP_ACCESS_TOKEN_SECRET attributes respectively. Add the … -
Introduction to Django Selenium Testing
-
Python deployment using fabric and pip
I've spent a not insignificant amount of time working on a deployment function for within my ``fabfile.py`` (the configuration file used by [Fabric](http://fabfile.org)). It's well worth the investment, as being able to deploy with a single command (potentially to many servers) is not only faster, but much less prone to human error. Currently, I'm using [Mercurial](http://mercurial.selenic.com) as my source control. I'm also using it for deployment, but I'd like to get away from that. My deployment process looks something like this: 1. Ensure the local repository has no uncommitted changes. 2. Ensure the ``requirements.txt`` file is exactly the same as the output from ``pip freeze``. 3. Copy our public key to the remote server, for the user ``www-data``, if it is not already installed there. 4. Create a [``virtualenv``](https://pypi.python.org/pypi/virtualenv) in the desired location on the server, if there is not one already there. 5. Ensure ``mercurial`` is installed on the server. 6. Push the local repository to the remote server. This will include any subrepositories. I do a little bit of fancy magic to ensure the remote subrepositories exist. 7. Update the remote server's repository to the same revision as we are at locally. This means we don't necessarily need … -
Go Open Data
What started as a brief conversation between myself and Michael Druker almost a year ago has come to life. On Saturday, May 11th people from Windsor to Ottawa are going to come together at the University of Waterloo School of Pharmacy for GO Open Data, a one day conference. The conference aims to bring together people from across Ontario and across the various interests related to open data to enjoy 8 talks, 2 panels, and an exhibition called Open Data Alley. Citizens, journalists, developers, administrators, CIOs, librarians, different people from all the areas connected to this fusion of technology and policy will be in attendance. That alone will make for an exciting day. It is thanks to the many partners from the Region of Waterloo, the City of Waterloo and the University of Waterloo that such a small idea has become so successful. We have amazing speakers like Ontario Information and Privacy Commissioner Dr. Ann Cavoukian, and up and coming speakers like James McKinney from Open North in Montreal. You can hear an interview with Dr. Cavoukian on the lawful access episode of Jessie Brown's Search Engine podcast. The rest of the schedule can be found online: http://go-opendata.ca/ The conference … -
2.3.6 release
-
A Survey on Software Quality
A Survey on Software Quality Want to help me graduate, and make the software industry a better place for us all? Great! I am writing my graduate report on the topic of software quality, metrics, and visualization. The report will ... -
A Survey on Software Quality
A Survey on Software Quality Want to help me graduate, and make the software industry a better place for us all? Great! I am writing my graduate report on the topic of software quality, metrics, and visualization. The report will ... -
Multi-tenanted Django
TL;DR : I made a thing: [django-multi-schema][django-multi-schema]. As pointed out in the comments, it's now known as [django-boardinghouse][django-boardinghouse]. ## Software, as a Service (SaaS) This is a term that has been around for a while. Basically, providing software that runs on a server, and selling access to that system. Instead of charging people for the software, you charge them a recurring fee for access to the hosted service. If you have more than one customer, then you need to ensure that each customer can only access data that is 'theirs', rather than seeing everything. You need some way to *partition* the data, and there are two main ways to do this. 1. Every customer has their own server/database. 2. All the data is stored in one server/database. ## To each their own. One way of partitioning data is to provision an application server, and a database for each customer. These web servers, and indeed the databases may not even be on different virtual machines, let alone physical machines. I manage a legacy PHP/MySQL application that runs each 'server' as an Apache VirtualHost, shares the codebase, and uses some configuration to route the database connections. The advantages of this type of … -
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