Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Developer Time
This blog post got started with a tweet. That tweet got retweeted a lot by developers. And system administrators. And database administrators. And any creative type. As of the time of this posting it had been retweeted over 170 times, a personal best. Obviously I struck a chord that resonated with a lot of people. Developers should have 4-6 hours of uninterrupted activity each day. Each 3-5 minute interruption costs more than you can imagine.— Daniel Greenfeld (@pydanny) December 3, 2012 Why did this tweet resonate with so many people? What I said in that tweet was not new - dozens if not hundreds of others have tweeted similar thoughts before and gotten many retweets. Heck, it's been written about in blogs and articles for years, either as a huge rant or often as an effort to politely educate others on how to set up a developer/operations/creative shop. I think this is because developers/engineers/creatives (and good managers) know that even a tiny distraction to someone "in the zone" takes more than just the 3-5 minutes it takes for you to finish a question and get an answer. Plus, because you are trying to remember the pieces in your head, you … -
Django REST framework: migrating from 0.x to 2.x
We used Django REST framework for a while now. Nothing spectacular yet. In most cases we're only returning a bit of JSON. We chose Django REST framework over Piston because that one was effectively unmaintained at the time. We chose it over tastypie because of the great way in which Django REST framework presents your API in the browser (the "browseable API" they call it), which is very helpful if you want others to actually use your API! And... Django REST framework uses Django's class based views, which we're using a lot. So it matches the style we want to work with. This was a second thing that gave it an edge over tastypie for us. Well, anyway, most of our Django REST framework 0.3.3 (or 0.4 or whatever) views looked like this: from djangorestframework.views import View as JsonView class SomeView(JsonView): def get(self, request): return {'some': 'dictionary', 'or': ['a', 'list']} JsonView would take care of converting everything that came in/out of the get() or post() between JSON and whatever Python data structure it represents. Handy. Since 30 october, version 2.0 is out. Lots of improvements and, from what I read, a better fit for many projects. But, boy, is it … -
Temporary standing desk at work
I've got a standing desk at home that I quite like. So I thought "why not also try it at the office?". My poor desk is now lacking four screws: every leg is only using one screw for the very last hole in the legs. Stable enough for a temporary test, but not something that I want all the time. So I'll have to find longer legs or a different desk. And it'll have to be some 5 cm higher, too. The main difference with my home desk is the amount of time I spend behind it: a full 8 hour working day (instead of a couple of hours in the evening at home). I've been at it for a few days now and it works out quite fine. Some quick observations: I walk around a lot more. If I want to ask something of someone sitting two desks away I'll just walk over instead of talking to him while sitting in my chair. I feel active at the end of the day! A bit tired in my legs, but I feel at least 2 cm taller. Discussing with a colleague often means sitting down for a minute (=getting a … -
Intersphinx links to Django's documentation
Intersphinx is a very neat way to point at other projects' documentation from within your own. Handy if you want to reference a Python module or an official Django setting or class. You have to do some setup work, like enabling the intersphinx extension. Most of the time, your automatically generated sphinx configuration will already have it enabled out of the box. Now you need pointers at the other projects' documentation (there needs to be a special objects.inv file with link target definitions). At the end of your file, add something like this: intersphinx_mapping = { 'python': ('http://python.readthedocs.org/en/v2.7.2/', None), 'django': ('http://django.readthedocs.org/en/latest/', None), 'sphinx': ('http://sphinx.readthedocs.org/en/latest/', None), } Now you can do fun stuff like this: Django knows about your URL configuration because you told it where to find it with the :django:setting:`ROOT_URLCONF` setting. Only... I got an error: ERROR: Unknown interpreted text role "django:setting". What? I couldn't figure it out and asked a question on stackoverflow. I got some tips, but couldn't get it to work. Then I got an idea. Sphinx has a lot of things build in, but not Django's custom Sphinx roles like setting! That's not a standard Sphinx one. Perhaps you need to copy/paste the other project's … -
Using Configurable User Models in Django 1.5
With the upcoming release of Django 1.5 one of the largest changes is that you can now specify your own User model. If you’re fine with Django’s current User model than you don’t have to change any code. If you want to take advantage of this new functionality then keep on reading as I’ll go through how to migrate your current application to the new configurable user model. Getting Started For the sake of simplicity let’s make our own User object that is exactly the same as Django’s current but fixes the email max_length field to comply with RFC 5321 of 254 characters and adds a required field for the user’s twitter handle. # myapp.models.py from django.contrib.auth.models import AbstractBaseUser class MyUser(AbstractBaseUser): username = models.CharField(max_length=40, unique=True, db_index=True) email = models.EmailField(max_length=254, unique=True) twitter_handle = models.CharField(max_length=255) ... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['twitter_handle'] You’ll notice a few new things about this: Inheriting AbstractBaseUser: This adds a few helper fields such as password and last_login as well as methods for setting the users password, getting the username, checking if the user is active. You can checkout a full list of what it includes here. USERNAME_FIELD: This is a string describing the name … -
Most Important Changes in Django 1.5
With the announcement of Django 1.5B1 and the final release of 1.5 around the corner I thought I’d go over some of the largest new features. For those that want to see the release notes you can do so here. Configurable User Model The largest change coming to Django 1.5 is the ability to specify your own user model instead of having to use the one that’s been shipped with Django for the past 6 years. Before Django 1.5, applications that wanted to use Django’s auth framework (django.contrib.auth) were forced to use Django’s definition of a “user”. In Django 1.5 you can create your own User account and include any of the fields you wish (Twitter, Facebook, larger email field, etc…). You can read more about it here. Python 3 Support Django 1.5 also includes experimental Python 3 support. They suggest not using it in production yet due to the complex nature of porting applications from Python 2 to Python 3 and the lack of use so far in production environments. Django 1.6 will have full Python 3 support. Saving a Subset of Model’s Fields You can now supply a update_fields argument to .save() and the model will only update … -
Stay with the Django CBV defaults!
One virtue of Django Class Based Views (CBVs) is that they come with pretty good default settings. The virtue of this is you can really pare your code down in size and complexity. For example, here is an implementation of CBVs based on a straight-forward Django model , stuffage.models.Stuff, that has a get_absolute_url method: stuffage/views.py: from django.views import generic from stuffage.models import Stuff class StuffDetailView(generic.DetailView): model = Stuff class StuffListView(generic.ListView): model = Stuff class StuffCreateView(generic.CreateView): model = Stuff class StuffUpdateView(generic.UpdateView): model = Stuff stuffage/urls.py: from django.conf.urls.defaults import patterns, url, include from stuffage import views urlpatterns = patterns("", url( regex=r"^create/$", view=views.StuffCreateView.as_view(), name="stuff_create", ), url( regex=r"^update/(?P<pk>\d+)/$", view=views.StuffUpdateView.as_view(), name="stuff_update", ), url( regex=r"^(?P<pk>\d+)/$", view=views.StuffDetailView.as_view(), name="stuff_detail", ), url( regex=r"^$", view=views.StuffListView.as_view(), name="stuff_list", ), ) These four CBVs will default to the following three templates without any action on my part: stuffage/stuff_detail.html (StuffDetailView) stuffage/stuff_form.html (StuffCreateView, StuffUpdateView) stuffage/stuff_list.html (StuffListView) So easy I use a simple script to render all this code! What about doing this all in the urls.py? Yes, I could do this all in the urls.py, but real Django code involves doing some logic in views, no matter how skinny you try to make said views. While I'm a huge proponent of logic in fat models, … -
Stay with the Django CBV defaults!
One virtue of Django Class Based Views (CBVs) is that they come with pretty good default settings. The virtue of this is you can really pare your code down in size and complexity. For example, here is an implementation of CBVs based on a straight-forward Django model , stuffage.models.Stuff, that has a get_absolute_url method: stuffage/views.py: from django.views import generic from stuffage.models import Stuff class StuffDetailView(generic.DetailView): model = Stuff class StuffListView(generic.ListView): model = Stuff class StuffCreateView(generic.CreateView): model = Stuff class StuffUpdateView(generic.UpdateView): model = Stuff stuffage/urls.py: from django.conf.urls.defaults import patterns, url, include from stuffage import views urlpatterns = patterns("", url( regex=r"^create/$", view=views.StuffCreateView.as_view(), name="stuff_create", ), url( regex=r"^update/(?P<pk>\d+)/$", view=views.StuffUpdateView.as_view(), name="stuff_update", ), url( regex=r"^(?P<pk>\d+)/$", view=views.StuffDetailView.as_view(), name="stuff_detail", ), url( regex=r"^$", view=views.StuffListView.as_view(), name="stuff_list", ), ) These four CBVs will default to the following three templates without any action on my part: stuffage/stuff_detail.html (StuffDetailView) stuffage/stuff_form.html (StuffCreateView, StuffUpdateView) stuffage/stuff_list.html (StuffListView) So easy I use a simple script to render all this code! What about doing this all in the urls.py? Yes, I could do this all in the urls.py, but real Django code involves doing some logic in views, no matter how skinny you try to make said views. While I'm a huge proponent of logic in fat models, … -
Stay with the Django CBV defaults!
One virtue of Django Class Based Views (CBVs) is that they come with pretty good default settings. The virtue of this is you can really pare your code down in size and complexity. For example, here is a straight-forward Django model , stuffage.models.Stuff that has a get_absolute_url method: stuffage/views.py: from django.views import generic from stuffage.models import Stuff class StuffDetailView(generic.DetailView): model = Stuff class StuffListView(generic.ListView): model = Stuff class StuffCreateView(generic.CreateView): model = Stuff class StuffUpdateView(generic.UpdateView): model = Stuff stuffage/urls.py: from django.conf.urls.defaults import patterns, url, include from stuffage import views urlpatterns = patterns("", url( regex=r"^create/$", view=views.StuffCreateView.as_view(), name="stuff_create", ), url( regex=r"^update/(?P<pk>\d+)/$", view=views.StuffUpdateView.as_view(), name="stuff_update", ), url( regex=r"^(?P<pk>\d+)/$", view=views.StuffDetailView.as_view(), name="stuff_detail", ), url( regex=r"^$", view=views.StuffListView.as_view(), name="stuff_list", ), ) These four CBVs will default to the following three templates without any action on my part: stuffage/stuff_detail.html (StuffDetailView) stuffage/stuff_form.html (StuffCreateView, StuffUpdateView) stuffage/stuff_list.html (StuffListView) So easy I use a simple script to render all this code! What about doing this all in the urls.py? Yes, I could do this all in the urls.py, but real Django code involves doing some logic in views, no matter how skinny you try to make said views. While I'm a huge proponent of logic in fat models, invariably I'm adding to the view … -
Les poneys envahissent la ville rose, aka DjangoCon Toulouse, vive les pains aux chocolats !
Ce week-end avait lieu la première DjangoCon Toulouse, une rencontre django régionale au pays du cassoulet. Les festivités commençaient à 11h30 le samedi avec des LT, puis une rafale de huit conférences l’après midi, et pour finir sprint et ateliers le dimanche. Cette Djangocon est également la première Cong qui n’était pas un événement autonome mais un événement à l’intérieur d’un autre événement (à savoir le capitole du libre). Je dois avouer que je suis assez partagé sur cette solution de l’événement dans l’événement. Effectivement cela permet d’attirer ‘des curieux’ qui viennent papillonner le temps d’une conférence ou d’un atelier (le nombre de 64 personnes dans l’auditoire a d’ailleurs été atteint). Cela permet aussi d’assister à une conférence de Jérémie Zimmermann la fin du premier jour. Enfin, cela permet de diminuer la charge de travail pour les orgas. Mais cela aussi signifie ne pas être mettre de tout les choix (essentiellement logistique) et de devoir gérer les interactions avec l’organisation globale. Je suis donc partagé sur ce mode d’événement à l’intérieur d’un autre. Mais venons en maintenant au Djangocon en elles mêmes. Tout d’abord le programme. LT et conférences étaient très intéressants. La rafale de huit conférence l’après midi, conférence … -
PyLadies Has Arrived In Longhorn Country!
Austin, Texas, known for its live music scene and hosting of the annual music and technology festival SXSW, is also home to a vibrant startup and programming community. Local Pythonistas are numerous enough to justify two separate meetup groups - one focused on web development, and a second centered around science and academia. Women are also well-represented, with a local GirlDevelopIt chapter (led by Garann Means), Rails Girls ATX, and a monthly all-girl hack night. And now we have PyLadies, here to represent the women of Austin's Python community. The aim of PyLadies ATX, led by Barbara Shaurette, is to help female Python developers (from aspiring to experienced) to grow in their careers in technology. In addition to working with local programmers, we're also planning to reach out to women in computer science programs at local colleges (such as the University of Texas) and eventually on outreach to computer science teachers in the area. As with other PyLadies chapters around the nation, the Austin group will support women through a combination of teaching/learning and social space. The first PyLadies ATX meetup will take place after the hustle and bustle of the holidays has passed - look for an announcement for … -
Case Study: URL Design for petcheatsheets.com
Backstory: On Saturday, November 17, 2012 Audrey Roy and I decided to participate in the Petcentric hackathon, a Los Angeles area Pet-themed product/coding contest held at Amplify. We arrived a bit late, but armed with Audrey's idea of creating a pet based reference sheet for owners, pet sitters, vets, and anyone else needing a card with data on pets, we got to work. About eight hours later we toggled a DNS switch and petcheatsheets.com was live. Update: Pet Cheatsheet's owner's pet information is private, because it includes emergency contact information that often includes phone numbers, email addresses, and even physical addresses of family members and friends. Maintaining the privacy of pets and their owners was also a consideration in implementation. URL Design Thoughts During development, one of the things I considered carefully was URL design of the primary feature, which was pets. The obvious choice was to go with a design that identified owners with pets: /<owner_username>/<pet_name>/ However, upon reflection, this didn't sit well with me. What if a pet changed owners? Identifying a pet with a particular owner in the URL meant that if we ever added a 'transfer ownership' feature, there would be extra work. Also, if we … -
Case Study: URL Design for petcheatsheets.com
Backstory: On Saturday, November 17, 2012 Audrey Roy and I decided to participate in the Petcentric hackathon, a Los Angeles area Pet-themed product/coding contest held at Amplify. We arrived a bit late, but armed with Audrey's idea of creating a pet based reference sheet for owners, pet sitters, vets, and anyone else needing a card with data on pets, we got to work. About eight hours later we toggled a DNS switch and petcheatsheets.com was live. Update: Pet Cheatsheet's owner's pet information is private, because it includes emergency contact information that often includes phone numbers, email addresses, and even physical addresses of family members and friends. Maintaining the privacy of pets and their owners was also a consideration in implementation. URL Design Thoughts During development, one of the things I considered carefully was URL design of the primary feature, which was pets. The obvious choice was to go with a design that identified owners with pets: /<owner_username>/<pet_name>/ However, upon reflection, this didn't sit well with me. What if a pet changed owners? Identifying a pet with a particular owner in the URL meant that if we ever added a 'transfer ownership' feature, there would be extra work. Also, if we … -
Case Study: URL Design for petcheatsheets.com
Backstory: On Saturday, November 17, 2012 Audrey Roy and I decided to participate in the Petcentric hackathon, a Los Angeles area Pet-themed product/coding contest held at Amplify. We arrived a bit late, but armed with Audrey's idea of creating a pet based reference sheet for owners, pet sitters, vets, and anyone else needing a card with data on pets, we got to work. About eight hours later we toggled a DNS switch and petcheatsheets.com was live. URL Design Thoughts During development, one of the things I considered carefully was URL design of the primary feature, which was pets. The obvious choice was to go with a design that identified owners with pets: /<owner_username>/<pet_name>/ However, upon reflection, this didn't sit well with me. What if a pet changed owners? Identifying a pet with a particular owner in the URL meant that if we ever added a 'transfer ownership' feature, there would be extra work. Also, if we ever implemented a sharing feature, changing URLs on a pet going to the same veterinarian their whole life might make the veterinarian's list of pets and their URLs invalid. With that in mind, I decided to go with an identifier and pet name, where … -
Testing and Django
Recently I have just enjoyed my first anniversary working at Imaginary. It has been a pleasure. Working in such a professional environment, with a great team of collegues, using Django and Python to solve problems I've never encountered before is, I have to say, a great experience to have ... -
Des poneys avec des chapeaux ronds aka DjangoBreizh, les poneys envahissent la bretagne
Samedi 17 novembre c’était donc la première edition des DjangoBreizh, une rencontre django locale en bretagne organisé par Exirel (bon ok, je ne suis pas tout a fait breton et pourtant j’y étais mais j’étais une exception) Le programme se découpait ainsi : matin conférence début d’après midi LT reste de l’après midi barcamp ou atelier d’initiation Pour une première conf, et conf régionale qui plus est, je trouve que le public fut au rendez-vous. 27 personnes pour les conférences, c’est en effet une belle réussite. Pour l’occasion, la cantine numérique de Rennes avait prêté ses locaux toutes la journée, ce qui a permis de mettre en place les conférence du matin et l’atelier initiation du matin (les barcamps se passant à quelques dizaines de mettre à la maison des associations) Ce que je retiens de cette rencontre régionale (hormis le fait qu’à rennes, il pleut tout le temps) c’est : il peut être difficile d’avoir des conférenciers locaux, il suffit alors de les faire venir d’ailleurs (mais il y a eu un certain nombre de conférencier ‘du cru’ et ça fait plaisir) la partie barcamp est une partie toujours très intéressante et qui fonctionne vraiment bien l’atelier d’initiation était … -
Understanding decorators
Understanding decorators in Python ###We will divide this post into two topics 1. Functions are objects and they can be passed around. 2. Writing few decorators As usual, I will be trying out the code in ipython and I suggest you to do the same. ###Functions can be passed around similar to any other object in Python. If you are already familiar with this, you can skip to next section. Let's first write a class. >>> class A(object): ... def __init__(self, a): ... self.a = a ... Let's create an instance of this class. >>> obj = A(5) >>> print obj.a 5 #output Let's write a function that takes an object, increase the value of instance variable 'a' by 10 and return the object. >>> def func(some_obj): ... some_obj.a = some_obj.a + 10 ... return some_obj ... In function **func**, our assumption is that we will always pass it an object as argument and this object will have an instance variable 'a'. Let's pass the created object **obj** of class A to this function and take the return value of this function in a variable named obj2. >>> obj2 = func(obj) >>> print obj2.a 15 We wrote a function 'func' … -
Things I learned from looking at graphs
We use Graphite to see how the Firefox Marketplace and Add-ons sites are doing. But the sheer volume of traffic to Add-ons always gives some interesting graphs. A while back we were switching between different clusters for add-on version check as the hardware behind it changed. As we switched clusters, we also switched from a hot cache to a cold cache. This resulted in a spike in traffic: That’s almost 45,000 requests per second coming into version check and being processed by Python and MySQL. With hardly a blip on the hardware loads, we processed that quickly. We can see the affect as the cache picked up the slack, it falls down to the usual 8,000 requests per second. Crazy traffic. We get a large number of requests to version check for a small number of add-ons. Like Adblock Plus which, as of writing this post, has over 15 million users. That’s pretty awesome. Looking at the traffic to Add-ons site (excluding version checks), traffic is very consistent depending upon the time of day. So when are those times? Here’s a graph of today’s traffic that I’ve annotated. Our low point is as India wakes up. It goes up as … -
Using South for schema and data migrations in Django
South is a schema and data migrations for Django. In an easy way you may update your database tables after you change your models. It also keeps all migrations in the codebase allowing to migrate backward if needed. In this article I'll show some standard South usage cases. -
Continuous integration of Django projects with Jenkins
Jenkins is a tool for watching or managing jobs. Either external like cronjobs or executing "build and test" jobs of your Django projects. There is even more, but in this article I'll focus on a basic Jenkins setup - building and testing a Django project. For Django there is django-jenkins that allows an easy integration with Jenkins tools like nice visualization of code coverage, pep8/pylint/pyflakes code violations. In this article I'll setup a local Jenkins configuration that will look on a folder with the code. In real world Jenkins would watch a repository and execute a job when a new changeset shows up. -
Using South for schema and data migrations in Django
South is a schema and data migrations for Django. In an easy way you may update your database tables after you change your models. It also keeps all migrations in the codebase allowing to migrate backward if needed. In this article I'll show some standard South usage cases. -
Using memSQL and MariaDB in Django projects
memSQL is a new database engine offering high efficiency thanks to RAM oriented data storage design and query compilation (check the FAQ). It's not related to MySQL but it offers a MySQL compatible client - and that allows easy, quick way to check it. MariaDB is a MySQL fork, binary compatible with it. This database server can be used as a drop in replacement for MySQL. The difference is in some extra features and extra storage engines added to MariaDB. -
Making Django and Javascript work nicely together
Backend and frontend cooperation may not be an easy task. For example in javascript code you may need some URLs to views or to icons required for some widgets. You can hardcode it or cleverly pass required data from backend to frontend. Also AJAX requests often want batches of data in JSON format. There is a way to make it quickly and clean. In this article I'll show some Django applications and solutions for much easier backend - frontend cooperation. -
Temporary files in Django for tests and on the fly file manipulation
Sometimes you need to do some operations on files on the fly in the code and place the result for form validation or save it with a model instance. When you want to write forms tests files may also be needed. To avoid using extra static files for tests you can use some temporary files. All those (and more) can be done with in-memory / temporary file-like objects. On the web there are StringIO or ContentFile usage examples but they wont work always - or as good as Django InMemoryUploadedFile object would. Here is an example of InMemoryUploadedFile usage for tests and other similar cases. -
Continuous integration of Django projects with Jenkins
Jenkins is a tool for watching or managing jobs. Either external like cronjobs or executing "build and test" jobs of your Django projects. There is even more, but in this article I'll focus on a basic Jenkins setup - building and testing a Django project. For Django there is django-jenkins that allows an easy integration with Jenkins tools like nice visualization of code coverage, pep8/pylint/pyflakes code violations. In this article I'll setup a local Jenkins configuration that will look on a folder with the code. In real world Jenkins would watch a repository and execute a job when a new changeset shows up.