Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
QuerySets, Q Objects, datetime, and Far Too Much Context
QuerySets, Q Objects, datetime, and Far Too Much Context -
DjangoCon - DC Tips
Mad props to Jackie Kazil, who helped me write this post! So, coming to DjangoCon in September? Let's have a chat about DC. The location DjangoCon DC is actually in Northern Virginia, not in the heart of the Capitol. Specifically, it's being held in Crystal City at the Hyatt Regency, which is close to the Crystal City Metro Station (the yellow and blue metro lines) and one stop away from Reagan National Airport (DCA). I worked in the area for many years, and while it doesn't have as much of the DC grit and history, it makes up for in being a great nexus between convenience and cost. As someone who's been to several conferences in DC, I can tell you this is a good thing. It is a safe, clean, affordable, and transportation-accessible part of the DC metro area that is littered with Django developers. If, for some reason, you aren't going to be staying at the conference's hotel, you're in luck. DC has a LOT of hotels. In general, the closer they are to a metro stop, the more expensive they are, but it's still possible to find no-frills hotels very close to a metro stop. If you … -
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. -
Why escape-on-input is a bad idea
The right way to handle issues with untrusted data is: Filter on input, escape on output This means that you validate or limit data that comes in (filter), but only transform (escape or encode) it at the point you are sending it as output to another system that requires the encoding. It has been standard best practice since just about forever [citation required]. An alternative is “escape on input”: at the point that data enters your system, you apply a transformation to it to avoid a problem further down the line when the data is used. It's come to my attention that some serious web developers (or at least, they take themselves seriously and are taken seriously by others) are still suggesting the practice of escape-on-input. For example, with escape-on-input, to avoid XSS any data that enters your system has HTML escaping applied to it immediately, before your application code touches it. I chose that example deliberately, because people are actually recommending it: in some recent “PHP sucks” debate. which, in turn, linked to a page by Rasmus Lerdorf recommending escape-on-input as a sensible way to deal with XSS. The page, admittedly, is describing a ‘toy’, a ‘no-framework PHP framework’, … -
Curiosity has landed!
I'm terribly proud of what was accomplished last night: A car-sized robot weighing a whopping 8,580 pounds (3,893 kg) was landed on Mars. It is packed with scientific packages that will expand our knowledge of Mars, and has the power to use them for at least 14 years. Simply put, this is an incredible step forward. As an American, I'm proud that our nation is capable of putting together such amazing feats of engineering and science. People from a diverse arrangement of backgrounds and origins came together to make something incredible happen. As a human being, I'm proud that we have yet again proven that we are still capable of working together to make amazing things happen. As someone who grew up in the 1970s, and someone who is proud to have worked at NASA for over 5 years, this is my American dream. Going Forward Curiosity is about to do amazing things and will tell a story to us that we'll never forget. Alas, NASA is a terribly easy target for politicians. It's budget has shrank to a small fraction of the it's early 1970s high, and it remains a target to this day. While the politicians congratulate the … -
Curiosity has landed!
I'm terribly proud of what was accomplished last night: A car-sized robot weighing a whopping 8,580 pounds (3,893 kg) was landed on Mars. It is packed with scientific packages that will expand our knowledge of Mars, and has the power to use them for at least 14 years. Simply put, this is an incredible step forward. As an American, I'm proud that our nation is capable of putting together such amazing feats of engineering and science. People from a diverse arrangement of backgrounds and origins came together to make something incredible happen. As a human being, I'm proud that we have yet again proven that we are still capable of working together to make amazing things happen. As someone who grew up in the 1970s, and someone who is proud to have worked at NASA for over 5 years, this is my American dream. Going Forward Curiosity is about to do amazing things and will tell a story to us that we'll never forget. Alas, NASA is a terribly easy target for politicians. It's budget has shrank to a small fraction of the it's early 1970s high, and it remains a target to this day. While the politicians congratulate the … -
Curiosity has landed!
I'm terribly proud of what was accomplished last night: A car-sized robot weighing a whopping 8,580 pounds (3,893 kg) was landed on Mars. It's packed with scientific packages which will expand our knowledge of Mars, and has the power to use them for at least 14 years. Simply put, this is an incredible step forward. As an American, I'm proud that our nation is capable of putting together such amazing feats of engineering and science. People from a diverse arrangement of backgrounds and origins came together to make something incredible happen. As a human being, I'm proud that we have yet again proven that we are still capable of working together to make amazing things happen. As someone who grew up in the 1970s, and someone who is proud to have worked at NASA for over 5 years, this is my American dream. Going Forward Curiosity is about to do amazing things and will tell a story to us that we'll never forget. Alas, NASA is a terribly easy target for politicians. It's budget has shrank to a small fraction of the it's early 1970s high, and it remains a target to this day. While the politicians congratulate the JPL … -
Django, websocket et bidouillage.
Lors du Django Meetup Paris numéro 2 (qui a eu lieu dans les locaux de 20 minutes, merci à eux pour le prêt de la salle (et à Julien pour l’orga) ), un petit récap des confs EuroDjango a été fait par Samuel (le frère de David, et oui un Paccoud peut en cacher un autre!!). Apparemment un des sujets porteur des EuroDjango avait été le ‘web temps réel’ (ce que je déteste ce terme tiens … temps réel, ça a un sens.. ça ne veut pas juste dire un truc en mode connecté) et la mise en place de celui ci dans Django (et du fait que peut être notre framework adoré n’était pas super en avance sur ce sujet). J’en ai profité pour donner mon avis sur la question. A savoir qu’à mon sens, les serveurs webs n’était pas fait du tout pour gérer des connexions en mode connecté. Parce qu’ils n’ont pas été prévu pour cela. Idem pour le cœur de django qui n’est pas fait pour garder des pools de sockets, des états par connexion clientes, etc etc … Alors qu’à contrario il y a des frameworks (je pense à twistted mais pas seulement) ou des … -
Deadline for DjangoCon Financial Aid requests is tomorrow!
For 2012, DjangoCon US has moved to Washington, DC, and everyone is invited! If you need financial support to get there, the Django Software Foundation and PyLadies have paired with a number of forward thinking sponsors to help get you there. All genders are eligible for assistance, so don't hesitate to submit your application. The deadline for financial aid requests is tomorrow, Friday, August 3rd by 11:59pm Eastern Time. Apply while you still have time! -
Deadline for DjangoCon Financial Aid requests is tomorrow!
For 2012, DjangoCon US has moved to Washington, DC, and everyone is invited! If you need financial support to get there, the Django Software Foundation and PyLadies have paired with a number of forward thinking sponsors to help get you there. All genders are eligible for assistance, so don't hesitate to submit your application. The deadline for financial aid requests is tomorrow, Friday, August 3rd by 11:59pm Eastern Time. Apply while you still have time! -
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. -
Deadline for DjangoCon Financial Aid requests is tomorrow!
For 2012, DjangoCon US has moved to Washington, DC, and everyone is invited! If you need financial support to get there, the Django Software Foundation and PyLadies have paired with a number of forward thinking sponsors to help get you there. All genders are eligible for assistance, so don't hesitate to submit your application. The deadline for financial aid requests is tomorrow, Friday, August 3rd by 11:59pm Eastern Time. Apply while you still have time! -
Attaching custom exceptions to functions and classes
Having too many custom exceptions on a project can be a pain, but a few choices ones are really nice. The problem is that in complex libraries having to import both functions and exceptions becomes a drag. To mitigate having to remember to import custom exceptions, this is a handy pattern you can use in a project and can be done on both functions and classes. Attaching a custom exception to a function This works because Python functions are first-class objects. They can be passed around as things, and in this case, have things assigned to them. # logic.py class DoesNotCompute(Exception): """ Easy to understand naming conventions work best! """ pass def this_function(x): """ This function only works on numbers.""" try: return x ** x except TypeError: raise DoesNotCompute # Assign DoesNotCompute exception to this_function this_function.DoesNotCompute = DoesNotCompute Now I can import the function, and it won't just through DoesNotCompute exceptions, it will also carry the function along with the import: >>> from logic import this_function >>> this_function(5) 3125 >>> this_function(4.5) 869.8739233809259 >>> this_function('will throw an error.') Traceback (most recent call last): File "<input>", line 1, in <module> File "logic.py", line 10, in this_function raise DoesNotCompute DoesNotCompute Alright, that doesn't … -
Attaching custom exceptions to functions and classes
Having too many custom exceptions on a project can be a pain, but a few choices ones are really nice. The problem is that in complex libraries having to import both functions and exceptions becomes a drag. To mitigate having to remember to import custom exceptions, this is a handy pattern you can use in a project and can be done on both functions and classes. Attaching a custom exception to a function This works because Python functions are first-class objects. They can be passed around as things, and in this case, have things assigned to them. # logic.py class DoesNotCompute(Exception): """ Easy to understand naming conventions work best! """ pass def this_function(x): """ This function only works on numbers.""" try: return x ** x except TypeError: raise DoesNotCompute # Assign DoesNotCompute exception to this_function this_function.DoesNotCompute = DoesNotCompute Now I can import the function, and it won't just through DoesNotCompute exceptions, it will also carry the function along with the import: >>> from logic import this_function >>> this_function(5) 3125 >>> this_function(4.5) 869.8739233809259 >>> this_function('will throw an error.') Traceback (most recent call last): File "<input>", line 1, in <module> File "logic.py", line 10, in this_function raise DoesNotCompute DoesNotCompute Alright, that doesn't … -
South 0.7.6 released
As the post title implies, yet another version of the ever-popular migrations library is out. The major addition in this release is --update, courtesy of Michael Elsdörfer - it lets you update an existing migration in-place for minor changes when you haven't committed the migration yet. There's also quite a few other changes - see the release notes for more. -
Attaching custom exceptions to functions and classes
Having too many custom exceptions on a project can be a pain, but a few choices ones are really nice. The problem is that in complex libraries having to import both functions and exceptions becomes a drag. To mitigate having to remember to import custom exceptions, this is a handy pattern you can use in a project and can be done on both functions and classes. Attaching a custom exception to a function This works because Python functions are first-class objects. They can be passed around as things, and in this case, have things assigned to them. # logic.py class DoesNotCompute(Exception): """ Easy to understand naming conventions work best! """ pass def this_function(x): """ This function only works on numbers.""" try: return x ** x except TypeError: raise DoesNotCompute # Assign DoesNotCompute exception to this_function this_function.DoesNotCompute = DoesNotCompute Now I can import the function, and it won't just through DoesNotCompute exceptions, it will also carry the function along with the import: >>> from logic import this_function >>> this_function(5) 3125 >>> this_function(4.5) 869.8739233809259 >>> this_function('will throw an error.') Traceback (most recent call last): File "<input>", line 1, in <module> File "logic.py", line 10, in this_function raise DoesNotCompute DoesNotCompute Alright, that doesn't … -
Announcing Django Dash 2012
Announcing Django Dash 2012 -
The road to hell is paved with regular expressions …
… or what is the cost of using regular expressions for simple tasks Regular expressions are one of the most powerful tools in computing I have ever seen. My previous post about Django compressor and image preloading is a good example how useful they might be. The only limit of their use is your imagination. But “with great power, comes great responsibility” or in this case a great cost. Even the simplest expressions can be quite heavy compared with other methods. The reason to write about this is a question recently asked in a python group. It was about how to get the elements of a list that match specific string. My proposal was to use comprehension list and simple string comparison while other member proposed using a regular expression. I was pretty sure that the regular expression is slower but not sure exactly how much slower so I made a simple test to find out. import re import timeit my_list = ['abc-123', 'def-456', 'ghi-789', 'abc456', 'abc', 'abd'] def re_check(): return [i for i in my_list if re.match('^abc$', i)] t = timeit.Timer(re_check) print 're_check result >>', re_check() print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) def simple_check(): return [i for i … -
Filtres a l'admin de Django 1.4
En una de les darreres aplicacions que hem fet, la d'apibaleares hem tirat força de l'administrador de Django. Segurament i donades les característiques que volem que tengui l'apliació al final, anirem cap a un administrador ad-hoc, però ara per començar va força bé. Un dels primers problemes va sorgir amb els filtres. Amb l'admin de Django és molt senzill fer un filtre per qualsevol camp, però té l'emperò que si el camp és una clau forana cap a una altra taula amb molts elements Django et pinta tots els elements, amb la qual cosa la plana creix molt i el llista es fa mal de manejar. Amb Django 1.4 tenim l'opció de crear-nos els nostres propis filtres i dir-li a l'admin que els faci servir. Per posar-vos en situació el que voldríem és que enlloc del filtre com a llista per la clau forana, poguéssim seleccionar l'element a filtrar des d'un desplegable. És veritat que perdem la selecció múltiple, però a l'usuari no li fa res, el que no vol és tota la llista al costat dret del llistat. Així doncs, el primer que farem serà veure què hi ha respecte als filtres. La documentació de Django es minsa, potser … -
RapidSMS UNICEF Rwanda Conference
Recently, I have had the pleasure of attending the UNICEF Rwanda conference with Tobias. The conference is focused on developing a comprehensive eHealth suite for numerous nations to implement. Mobile technology is changing the landscape of public health, and SMS messaging is leading the way. Conference goers were tasked with organizing the existing eHealth and mHealth technical infrastructure to reduce redundancy in the existing applications. The goal was to create a comprehensive eHealth/mHealth software suite for maternal, newborn and child health, nutrition and Ending Mother to Child transmission of HIV (eMTCT). The conference also hoped to improve the interoperability of key existing platforms to provide functionality that is currently not possible by using one software tool. Caktus was very excited to take part in this conference and learn more about how developers can assist with the creation of useful health tools. Recently, Colin Copeland and I have become RapidSMS community coordinators. Our goals are to strengthen the existing infrastructure and write documentation for the existing code so that the application. The main goal for the RapidSMS project is to be fully usable by UNICEF country offices and other users without sustained support from outside software consultants. Through attending the UNICEF … -
Breakage when upgrading from Celery 2.5.3 -> 3.0.4
Commenting on my update to my Celery rant, @asksol asked me to post the Pylint results that made me question the claim of backwards compatibility. (“@Asksol asked” — See what I did there? That’s alliteration. It’s a sign of a quality blog post. Ask for it by name.) Again for the record, @asksol is a smart and friendly person. I know I wouldn’t last a day supporting a project the way he has supported Celery over multiple years. I’ve calmed down since yesterday, and I hope that something good results from my rant — if not for me, then for a future Celery user needing upgrade help. In his reply to my rant, @asksol describes some history and rationale for how he manages code change, and I encourage you to read it. Here we go: With django-celery 2.5.5, celery 2.5.3, Pylint 0.25.1, and a pylint.cfg that disables “W0511,R0904,R0801,R0903,C0302,R0922,R0914,R0902,C0111,R0912,R0915,I0011,W0232″, Pylint reports nothing. When I upgrade to django-celery 3.0.4 and celery 3.0.4, Pylint reports: $ fab pylint [localhost] local: pylint --rcfile="/Users/johnd/Documents/dev-quisitor/dev/configs/pylint.cfg" ips_quisitor ************* Module ips_quisitor.accounts.tasks E0611: 2,0: No name 'PeriodicTask' in module 'celery.task' ************* Module ips_quisitor.admin_dash.admin E1120: 49,8:CCAdmin.save_model: No value passed for parameter 'self' in function call ************* Module ips_quisitor.admin_dash.tasks E0611: 3,0: … -
Additional context for class based views through urlconf
I thought there was a simpler method of adding context through the urlconf but after having a look at the source this is what I came up with. Apparently there's only get_context_data() so I used a lambda to add what I needed. Update: I should probably have used extra_context={'model': 'Frontpage'} url( r'^$', TemplateView.as_view( template_name='pages/front.html', get_context_data=lambda: {'model': 'Frontpage'}, ), name='front', ), -
Additional context for class based views through urlconf
I thought there was a simpler method of adding context through the urlconf but after having a look at the source this is what I came up with. Apparently there's only get_context_data() so I used a lambda to add what I needed. Update: I should probably have used extra_context={'model': 'Frontpage'} url( r'^$', TemplateView.as_view( template_name='pages/front.html', get_context_data=lambda: {'model': 'Frontpage'}, ), name='front', ), -
Additional context for class based views through urlconf
I thought there was a simpler method of adding context through the urlconf but after having a look at the source this is what I came up with. Apparently there's only get_context_data() so I used a lambda to add what I needed. Update: I should probably have used extra_context={'model': 'Frontpage'} Raw url( r'^$', TemplateView.as_view( template_name='pages/front.html', get_context_data=lambda: {'model': 'Frontpage'}, ), name='front', ), -
Additional context for class based views through urlconf
I thought there was a simpler method of adding context through the urlconf but after having a look at the source this is what I came up with. Apparently there's only getcontextdata() so I used a lambda to add what I needed. <strong>Update</strong>: I should probably have used extra_context={'model': 'Frontpage'} Raw url( r'^$', TemplateView.as_view( template_name='pages/front.html', get_context_data=lambda: {'model': 'Frontpage'}, ), name='front', ),