Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
RestORM - The client side of REST
RestORM structures the way you access a RESTful API and allows you to easily access related resources. It tries to be as generic as possible so it's not tailored to any specific API or server-side API library. With RestORM you can mock an entire API and replace the real client with a mock version in unit tests. RestORM is very extensible but offers many functionalities out of the box to get you up and running quickly. -
My requirements.txt
Every developer has their go to list of packages they use when starting out a new project. I thought I’d list my basic set of packages that I use for almost all of my projects. I got this idea from Daniel Greenfeld, you can check out his list here. Django Django is my go to framework. You can easily get a project going in a couple minutes. I’m using 1.4.2 in production and 1.5 in development. You can read about the changes to Django 1.5. django-secure django-secure provides you with a checklist of things you can do to make your site more secure. I include it to help me from forgetting about certain settings. django-model-utils Provides a number of useful mixins and utilities to help with certain pitfalls in Django. Status Field and Inheritance Manager are two very useful things. psycopg2 A no brainer if you’re using Postgres. Make sure you have XCode installed if you’re installing psycopg2 on OS X. django-debug-toolbar This tool gives you the ability to dig deep into the performance of your site. Just having the ability to quickly see how many queries are being run on a specific page is worth the installation. South Sanely … -
Heroku: Running multiple python processes in a single dyno using foreman
Recently I've made a few small python web projects that I've deployed on Heroku. For some of these projects I've needed to run asynchronous jobs through Celery. Heroku allows you to run one free dyno (or actually they give you 720 free dyno hours per month, which corresponds to one dyno constantly running). This means that if you choose to run one web dyno and one worker dyno (celery in this case), you'll be charged for 720 dyno hours. However, if you have a very small project, or your're working on a project that hasn't been released yet, you can avoid this cost. A heroku dyno is like a process, and in this process you can actually spawn new processes, as long as you stay within the limit of 512 mb ram (the process also only has one CPU core). Heroku suggests that you use foreman when you run your application on your local machine, but you can actually use foreman on heroku, in order to run multiple processes in a single dyno. Instructions 1. The first thing we'll do is to create a post_compile script in the bin directory of our project. In this script we'll add a few … -
Community Contributions: A Follow-Up
A few months ago, I wrote a blog post about contributing to community. A month later, that post was republished by the folks at Red Hat, in their online magazine OpenSource.com. When that article went up, I had a chance to read through it again and realized that there were a few things I forgot the first time around. In case there was any question, here's why community is so important: Lynn Root's PyCarolinas Keynote: Community FTW As with the first article, I'm focused on the communities in which I am actively involved - Django and Python - but I'm convinced that these suggestions apply to just about any open source community. On that note, here are some additional things you can do if you want to give back to open source: Answer questions in user groups. The two most active user groups in the Python world are probably Django users and comp.lang.python. Yes, sometimes the same questions seem to be asked over and over again, but there are always people new to the language or framework who need help finding their way - be a pal and help them find answers. Answer questions on StackOverflow. StackOverflow has channels for … -
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 December 7th, 2012, it had been retweeted over 500 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 won't be … -
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 December 7th, 2012, it had been retweeted over 500 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 won't be … -
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.