Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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. -
Shops near you – geographic features of GeoDjango
Boom on mobile devices and widespread Internet access created a demand for applications aware of user geographic location. Nowadays using modern web frameworks with magical powers you can make such geo-enabled web applications easily. Django offers a special sub-framework called geodjango. There you will find an enormous amount of features of "geographic" nature. In this article I'll present a simple application that will use a part of GeoDjango to search and display shops closest to given address. -
Testing Django applications with Selenium
Selenium is a popular tool for browser automation. Main usage for Selenium are browser based tests of web applications. With a real browser and handy API you can test frontend behavior of an application (like JavaScript code). In Django 1.4 we got LiveServerTestCase - a TestCase that spawns a test server. This allowed much easier Selenium integration in Django tests. You can change a presentation on benlopatin.com. If you will find something different - check the date as it may describe older solutions for older Django versions. In this article I'll show some basic Selenium usage cases in tests - showcasing the api. -
Aiding tests with Ludibrio stubs and mocks
In tests we assume some input data and check if the output is equal to what we expect it to be. Sometimes is impossible to set the initial data as the code fetches some data from a third party API, or creates some data on its own (like random data). To aid testing of such code we can use ludibrio. It can mock or stub existing classes or functions making them work as we program it. -
REST API creation with django-tastypie
django-tastypie is probably the best at the moment tool for REST API creation in Django applications. The code is on github and documentation is on readthedocs.org. With tastypie it's easy to create REST API that will allow easy web access to data stored in models - get, update, edit or delete. In this article I'll show some basic usage of tastypie. -
Managing style sheets and JavaScript files with webassets
webassets is an application that manages (compress and join) static files like JavaScript or CSS (LESS, SASS too) files. It can work with various frameworks, including Django. Everything is described in the documentation. Compressed files have slightly smaller size and they load faster. One file made out of multiple CSS or JS files reduces the amount of HTTP requests needed to load the website. That also improves the load times.