Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
django-piston form validation -- part 3
In my previous post titled "Exploration of django-piston -- part 2" [1] I end the post by 2 open issues. This post will propose a solution to the first one:The validation errors are returned as a pseudo xml string.Bad Request <ul class="errorlist"><li>content<ul class="errorlist"><li>This field is required.</li></ul></li><li>title<ul class="errorlist"><li>This field is required.</li></ul></li></ul>To put it in other words I would prefer if django-piston return the validation errors of the form in the format specified in the request. JSON$ curl -u testuser:foobar -X POST -d content="This post is created using the api" http://127.0.0.1:8000/api/posts/?format=jsonBad Request {"title": ["This field is required."]}yaml$ curl -u testuser:foobar -X POST -d content="This post is created using the api" http://127.0.0.1:8000/api/posts/?format=yamlBad Request title: [!!python/unicode 'This field is required.']xml$ curl -u testuser:foobar -X POST -d content="This post is created using the api" http://127.0.0.1:8000/api/posts/?format=xmlBad Request <ul class="errorlist"><li>title<ul class="errorlist"><li>This field is required.</li></ul></li></ul>After a while reading the source of django-piston and poking around I have implemented this feature in my branch.The biggest hurdle was that for some reasons "form.errors" cannot be serialized directly.simplejson.dumps(form.errors)*** TypeError: is not JSON serializableIn order to work around this issue you need to force python to evaluate this proxy object.dict((key, [unicode(v) for v in values]) for key,values in form.errors.items())The last bit is … -
Weather App Tutorial. Part 5 of 5. Graph View
I had some problems with the internet, so I am posting this entry a little later that expected. But anyway, this is it - the final part of the tutorial about the weather app. You can read the first four parts here: 1, 2, 3, 4. Today I will show you how to display a chart with statistical data from the collected weather details.I googled a little to find out what charting system to use for this small project. And I found Open Flash Chart as an interesting solution. It's a flash-based charting system which uses Ajax requests to get the data for the graphs. That means that we'll need a view which will show the graphs and another view, which will provide the data. Each location will have its own page displaying a chart, so it would be nice to have URLs where each location would be accessed by a slug. We already have a field sysname which could be used here, but my best practice is to have separate fields for url slugs which might be changed at anytime and sysnames which should be defined once and not changed at all because the sysname binds an object with … -
Comments and an Atom Feed
Small update for this site: Comments are now working and there is an Atom Feed for the latest posts in this blog. The behaviour and the style of the comments is not very polished yet, but I’ll work on that later. I’ll also add more feeds, e.g. for post comments, categories and tags. -
Magic! Python! Django! Whee!
This blog is now run by Django. I didn’t really like Wordpress which I used before. And also I don’t like PHP anymore (I really liked it some years ago, but everything changed, when I learned Python …). When I told a friend that I wanted to switch from Wordpress to something else, he just said: «Use Django.» So I took a look at the Tutorial and was instantly thrilled. At first, I wanted to use an existing weblog app, but I also wanted to code an app for my own and since I din’t find a weblog app that I 100% liked, I just decided to write my own. So here it is (far from finished though)! Features so far: Basic post model (title, slug, pub date, modify date, status, category, HTML body) Post manager for post counts (per year, month, category (and tag)) Hierarchical category model – imho, this is the highlight of my app. Archive and Categories Some special template tags. Usage of a recursive template tag for the categories Unit- and doctests for the models and template tags Features to come: Comments Atom feeds Sidebar Static pages Trac integration for my projects Search Last.fm sidebar widget … -
Comments and an Atom Feed
Small update for this site: Comments are now working and there is an Atom Feed for the latest posts in this blog. The behaviour and the style of the comments is not very polished yet, but I’ll work on that later. I’ll also add more feeds, e.g. for post comments, categories and tags. -
Tuning the count method on a queryset
Some alternate ways to manipulate the pagination of Django query sets. -
Weather App Tutorial. Part 4 of 5. Template Tag
If you followed the first parts of the tutorial, you should have basic understanding how to create an app with models, set up administration, and retrieve data from third-party services. This part is about displaying collected data in any template using custom template tag.At first, we need to create a directory templatetags containing an empty __init__.py file in the climate_change directory.mkdir -p climate_change/templatetagstouch climate_change/templatetags/__init__.pyI will call the template library weather. So I have to create a file weather.py in climate_change/templatetags and define and register the template tag in that file. The template tag get_current_weather should display the current weather for a chosen location. To define what location you choose, you could refer to id, name or location_id, but none of them is appropriate for this reason. id and location_id are not remember-able and not informative enough, whereas the name might be changed to translate the city to another language or to add some more specifics and this change would detach the template tag from the location. For those reasons, it is best to create a new field sysname for the location model which would have a unique non-changeable value as a textual humanized identifier for templates.But wait! It's such a … -
Weather App Tutorial. Part 3 of 5. Management Command
As you might have noticed, this is a continuous tutorial about an app which regularly checks weather and reports how it changes throughout years. Previously I wrote how to start a project and define the models. The interestingness of the app starts now. I will show you how to import weather details from Yahoo! Weather using a management command. Management commands in Django are those which are recognized by manage.py and django-admin.py, e.g. syncdb, shell, runserver, etc. It's not difficult to inject your own custom commands for your app. We'll need one that will be set as a scheduled task to check the current weather. To create a management command, you have to create directories management/commands/ inside of your climate_change directory and create empty files __init__.py in each of them. mkdir -p climate_change/management/commands touch climate_change/management/__init__.py touch climate_change/management/commands/__init__.py Now I'll create a file climate_change/management/commands/check_weather.py which will aggregate the data from the feed. Just looking at the examples of Django core commands, you can find, that management-command modules should have a class Command with an overridden method handle_norargs which will have all the logic of the command. I found an example of importing weather from Yahoo! and will be using it here. … -
Atualizações de segurança lançadas
Atualizações de segurança lançadas -
Atualizações de segurança lançadas
Atualizações de segurança lançadas -
exploration of django-piston -- part 2
Djangocon 09 was really food for thought and this post follow my previous post about django-piston. I found the talk from Avi Bryant about his experience building Trendly [1].My take away of this talk was that they have a single HTML page with a lot of JS. The JS is the used to get the JSON data the JSON from the server. Unfortunately I am unable to find a link to a better description of its talk.My last post hopefully convince you that it is easy relatively easy to create a web api to your django application [2]. This Post aims to show you how you can create a page to list and create a blogpost.List and create a blogpostThe idea here is to reuse the web api that we have created in the previous article to build a web page. One of the interesting feature of django-piston is the decorator @validate(BlogpostForm, 'PUT'). It enables you to validate the data send to your server and it takes as input a django form. A longuer description of this feature is available here [4].The view cannot be simpler [5] :def create_ajaxy_post(request): form = BlogpostForm() return direct_to_template(request, template='edit_ajaxy_post.html', extra_context={'form':form} )The template is using … -
Testing using a mocked HTTP server
Testing using a mocked HTTP server -
Weather App Tutorial. Part 2 of 5. Models
This is the second part of my tutorial how to make a weather app. This time I will show you how to create the models and set up the admin. Open the models.py file in the climate_change directory and enter the following: # -*- coding: UTF-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings class Location(models.Model): name = models.CharField(_("name"), max_length=200) location_id = models.CharField( _("location ID"), max_length=20, help_text=_("Location IDs can be retrieved from URLs of weather " "at specific cities at Yahoo! Weather, e.g. GMXX0008 from " "http://weather.yahoo.com/forecast/GMXX0008.html"), ) class Meta: verbose_name=_("location") verbose_name_plural=_("locations") def __unicode__(self): return self.name class WeatherLog(models.Model): location = models.ForeignKey(Location, verbose_name=_("location")) timestamp = models.DateTimeField(_("timestamp")) temperature = models.IntegerField(_("temperature (C°)")) humidity = models.IntegerField(_("humidity (%)")) wind_speed = models.DecimalField( _("wind speed (km/h)"), max_digits=5, decimal_places=2, ) visibility = models.DecimalField( _("visibility (km)"), max_digits=5, decimal_places=2, ) class Meta: verbose_name=_("weather log") verbose_name_plural=_("weather logs") ordering = ("-timestamp",) def __unicode__(self): return "%s @ %s" % ( self.location.name, self.timestamp.strftime("%Y-%m-%dT%H:%M"), ) The models are created. Now let's create the database schema for them. python manage.py syncdb Also in this step when asked, I created a superuser called "demo" to be able to access django-contributed administration. Let's try it out. We'll need to add a … -
django-registration
So, life has been eventful lately. There was DjangoCon, which was awesome even though I came away deeply unhappy with how my talk turned out; due to a lot of hectic things going on, it fell far below the standard I usually like to enforce for myself. I’ve got a couple things cooking for PyCon, though, which will hopefully make up for it. Things are starting to ramp up for the Django 1.2 development ... Read full entry -
django-registration
So, life has been eventful lately. There was DjangoCon, which was awesome even though I came away deeply unhappy with how my talk turned out; due to a lot of hectic things going on, it fell far below the standard I usually like to enforce for myself. I’ve got a couple things cooking for PyCon, though, which will hopefully make up for it. Things are starting to ramp up for the Django 1.2 ... Read full entry -
Weather App Tutorial. Part 1 of 5. Preparation
It is Blog Action Day tomorrow so I decided to participate in it as a blogger again. The theme for this year is "Climate Change". After a little brainstorm, I came up with an idea to write a tutorial how to build an app which regularly checks local weather and lets you compare different weather features for months of different years.I'll use Yahoo! Weather to check the current weather. From all information that it provides, we'll be mostly interested in temperature, humidity, wind speed, and visibility in the current location. The app will check the weather regularly, will allow you to show the current weather, and also provide a graph comparing average monthly weathers throughout years.So let's start with the new project. I have quite a clean computer and want to do the app the nice way. So first of all, I will install virtualenv to be able to install third-party python libraries in a closed environment which will only be used for this project (I have already installed setuptools and django).# install virtualenvsudo easy_install virtualenvI created a directory Projects in my home directory and cd to it.Let's create a virtual environment and start the new project and app.# create … -
Fünftes Treffen der Django-UserGroup Hamburg
Das fünfte Treffen der Django-UserGroup Hamburg findet am Dienstag, den 27.10.2009 um 19:30 statt. Wie beim letzten Mal treffen wir uns wieder in den Räumen der CoreMedia AG in der Ludwig-Erhard-Straße 18 in 20459 Hamburg. Eine Anfahrtsbeschreibung gibt es auf der CoreMedia Webseite oder via Google Maps. Bitte am Eingang Ludwig-Erhard-Straße 18 bei CoreMedia AG klingeln, in den 3. Stock fahren und oben am Empfang nach der Django-UserGroup fragen. Da wir in den Räumlichkeiten einen Beamer zur Verfügung haben hat jeder Teilnehmer die Möglichkeit einen kurzen Vortrag (Format: Lightning Talks oder etwas länger) zu halten. Eingeladen ist wie immer jeder der Interesse hat sich mit anderen Djangonauten auszutauschen. Eine Anmeldung ist nicht erforderlich. Für ein paar Getränke wird wieder gesorgt sein, es ist aber durchaus erlaubt/erwünscht sich selbst Getränke und/oder etwas zu Essen mitzubringen. Weitere Informationen über die UserGroup gibt es auf www.dughh.de. -
Job opportunity: engineer at Whiskey Media
This is a paid advertisement. My friends and former co-workers at Whiskey Media are looking for a developer to join their team. I can’t possible say enough good things about Whiskey Media: it’s a smart, well-run company that’s using cool tech to accomplish great things. I worked for Whiskey Media for about a year, and they’re one of my clients at Revolution Systems. I’m happy to answer questions about the company; feel free to drop me an email. -
Actualización de seguridad Django 1.0 y 1.1
Hace un par de días se publicó una importante actualización de seguridad para Django 1.0, 1.1 y la versión de desarrollo. El agujero de seguridad afecta a cualquier aplicación que utiliza campos EmailField ó URLField en sus modelos. El fallo se debe a la validación de direcciones de e-mail y URLs mediante expresiones regulares. Algunas direcciones podían producir un rendimiento negativo en el sistema al aplicarles las expresiones regulares haciendo que el thread correspondiente dejara de responder y se consumieran más recursos de la CPU pudiendo resultar en una denegación de servicio si se hiciera deliberadamente. -
Optimising compilers are there so that you can be a better programmer
In a discussion on the Django developers mailing list I recently commented that the performance impact of having logging infrastructure, in the case where the user doesn't want the logging, could essentially be disregarded because Unladen Swallow (and PyPy) are bringing us a proper optimising (Just in Time) compiler that would essentially remove that consideration. Shortly thereafter someone asked me if I really thought it was the job of the interpreter/compiler to make us not think about performance. And my answer is: the job of a compiler is to let me program with best practices and not suffer performance consequences for doing things the right way.Let us consider the most common compiler optimisations. A relatively simple one is function inlining, in the case where including the body of the function would be more efficient than actually calling it, a compiler can simply move the functions body into its caller. However, we can actually do this optimisation in our own code. We could rewrite: def times_2(x): return x * 2 def do_some_stuff(i): for x in i: # stuff z = times_2(x) # more stuffas: def do_some_stuff(i): for x in i: # stuff z = x * 2 # more stuffAnd this … -
Django and ASP.NET MVC
While looking at some blogs and news sites about the MVC web-frameworks, I stumbled upon a nice stack overflow question: ASP.NET MVC vs. Django - Which framework should I learn? The answers have a lot of interesting points. For example one argument pro django by user saner is that: Django is more mature and there are a lot of available components you can use. There is ORM so using database is very easy. Testing is simple and community is very responsive. Another user, Oko, suggests that django is newbie friendly: To start working with django, you don't have to be experienced Python programmer. If you are generally oriented in web development, you will find yourself working with django in no time. For the ASP.NET MVC side of things, Lau Franco gives one possible advantage for people who don’t know neither of the frameworks: …with ASP.NET MVC, you only need to learn the new framework. For Django, you also need to learn how to deploy, host and keep the site running (which means learning Apache and tools for dealing with it). Regardless of whether the above opinion is true or not, I think ASP.NET MVC has a good chance of gaining … -
The Mythical Django Pony, a blessing?
On my way to have lunch on the first day of DjangoCon in Portland, I met Eric Holscher in one of the corridors of the hotel holding a pink unicorn. It seemed odd to me so I approached and asked him about what he had in his hands. He explained that this was the unofficial Django mascot, which was a pony. I didn’t make the obvious observation that what he had in his hands was a unicorn, but asked how this came to be. He explained that one of the core dev on the Django mailing list responded to one of the feature requests saying “no, you can’t have a Pony!” as a way of politely refusing the feature request. I was surprised to be in a DjangoCon session two days later where Russell Keith-Magee talks about declined feature requests and how they are referred to as ponies, and suggests ways in which your features are likely to get accepted. He also explained the whole story behind the mythical Django pony (which is really a unicorn!). Why am I bringing this up now? well as I write the concluding chapters of my dissertation, I notice an odd relationship between the number of … -
* is Unix
Ryan’s I like Unicorn because it’s Unix appears to have started a mini-meme of folks writing simple forking network servers in their language of choice. I’m really enjoying reading ‘em – they’re a sort of Rosetta Stone of network code – so I’m going to keep a running list of links here. Tell me about any I’ve missed (via email, comments, or twitter) and I’ll add ‘em to the list. -
Python is Unix
Ryan Tomayko’s I like Unicorn because it’s Unix should be required reading for anyone doing anything involving networks or unixes these days. Like Ryan, I share a deep appreciation for the dark art of Unix system calls, and like Ryan I’m a bit dismayed to see them relegated to the dusty corners of our shiny dynamic languages. So I read I like Unicorn because it’s Unix with glee; it’s perhaps the cleanest, clearest explanation of how preforking socket servers work, and I enjoyed seeing Ruby’s twist on the old standard. -
BBCode and Syntax Highlighting with Django
Lightweight BBCode parser and syntax highlighting for Django. Code blocks set off with the tag will be automatically highlighted.