Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Building a website API with Django. Part 1: API functions
WAPI and django-oauthsp are reaching the point when they are starting to become useful, so I decided it was time to write some articles explaining how they work and how you can use them in your sites. I'm currently using both of them in production at byNotes and I haven't run into any problems for now, but YMMV. This article talks about the principles behind WAPI and walks you trough the creation of a simple API function. Next articles in this series will explain more advanced concepts like custom serializations, user authentication against django.contrib.auth or using OAuth. Design Let's start by talking about the design ideas behind WAPI. My main motivation when I started writing it was abstracting most of the details involved in publishing a web API, since almost 100% of sites have the same requirements: ReSTful resources (sometimes SOAP or XML-RPC), serialization in different formats and user authentication. Handling all of this as views is not difficult, but it's tedious and a lot of times requires more code than the API itself. So, why not let the developer focus on providing useful endpoints and let a framework do the rest? WAPI only requires you to write a class. … -
MultipleSubmitButton Widget for ChoiceField
Recently I published a snippet with a widget rendering a choice field as a series of submit buttons.So the {{ form.do }} field from the following form:SUBMIT_CHOICES = ( ('save', _("Save")), ('save-add', _("Save and Add Another")), )class TestForm(forms.Form): do = forms.ChoiceField( widget=MultipleSubmitButton, choices=SUBMIT_CHOICES, )will be rendered as:<ul><li><button type="submit" name="do" value="save">Save</button></li><li><button type="submit" name="do" value="save-add">Save and Add Another</button></li></ul>Can somebody enhance this widget so that it supports iteration through different choices and getting specific buttons by indexes in the template? My trials failed, but maybe you will succeed! -
Proxying Django's admin views
In this post I share some thoughts on one way to customise the Django’s admin interface beyond what, I believe, it was originally designed for. Well, at least it’s an approach that I used to bring django-treemenus’ codebase up to the NewForms-Admin’s API, while preserving the app’s original behaviour. First, you may want to check the latest release of django-treemenus (0.6). In that release I’ve completely refactored the code to use all the goodness of NFA. Backward incompatible changes are minimal if you weren’t using the extension system, and from the user’s point of view everything is pretty much the same as before. The result is quite satisfactory: the amount of code was reduced by more than half, every known issue was fixed, and it is now much easier to extend/hack this app for those who are interested. Doing that refactoring made me realise even more how great NFA is. Still, I did not quite want to use it the “standard” way. Basically, I wanted to keep the URL scheme that was used in previous versions of treemenus. For example: /admin/treemenus/menu/1/ -> The menu #1 edit page. /admin/treemenus/menu/1/items/add/ -> Add an item to menu #1. /admin/treemenus/menu/1/items/9/ -> The item #9 … -
"Cool project, what CMS did you guys use?"
Pass223.com I recently worked on Pass223.com, a simple site that urges the Senate to pass a piece of legislation that requires the Senate to adhere to the same electronic financial disclosure rules in place for representatives and presidential candidates. Pass223.com is similar to that of hundreds of related action sites: choose a legislator, call them, report results, repeat. I wrote the code, our esteemed creative director Kerry did the bulk of the design, and various others here at Sunlight helped to refine the concept and wording of the site and call script. It was a bit surprising seeing how positive the feedback has been for such a simple site. A number of people have been pointing to Pass223 as an example of how this type of thing should be done. Most of that credit goes to the team that worked together to revise the awesomely straightforward script. The other question that has come up is what content management system (CMS) Pass223 was done on and what legislative database it was built on top of. This made me think about the other reason Pass223 was able to come together the way that it did, the tools used behind the scene. When … -
Kansas Primary 2008 recap
I’m winding down after a couple of very long days preparing for our coverage of the 2008 Kansas (and local) primaries. As always it’s been an exhausting but rewarding time. We’ve come a long way since the first election I wrote software for and was involved with back in 2006 (where election night involved someone accessing an AS/400 terminal and shouting numbers at me for entry). Our election app has become a lot more sophisticated, our data import process more refined, and election night is a whole lot more fun and loads less stressful than it used to be. I thought I’d go over some of the highlights while they’re still fresh in my mind. Our election app is definitely a success story for both the benefits of structured data and incremental development. Each time the app gets a little more sophisticated and a little smarter. What once wasn’t used until the night of the election has become a key part of our election coverage both before and after the event. For example, this year we had an overarching election section and also sections for indivudual races, like this section for the Douglas County Commission 2nd district Democratic primary. These … -
Eclipse 3.4 Ganymede and PDT
Unfortunately there is no working and official version of the PDT release for the current Eclipse release, Eclipse 3.4 Ganymede. However it is possible to use both. I found the solution within the Digital Base blog: Simply download the nightly build of PDT and integrate it as local site in the Eclipse update manager and then install. Quite easy. -
Eclipse 3.4 Ganymede and PDT
Unfortunately there is no working and official version of the PDT release for the current Eclipse release, Eclipse 3.4 Ganymede. However it is possible to use both. I found the solution within the Digital Base blog: Simply download the nightly build of PDT and integrate it as local site in the Eclipse update manager and then install. Quite easy. -
Eclipse 3.4 Ganymede and PDT
Unfortunately there is no working and official version of the PDT release for the current Eclipse release, Eclipse 3.4 Ganymede. However it is possible to use both. I found the solution within the Digital Base blog: Simply download the nightly build of PDT and integrate it as local site in the Eclipse update manager and then install. Quite easy. -
Django: messaging
When completing something like deleting an item or adding a user, it’s usually nice to report a message to the user to let them know what just happened. I also find it useful to send the user somewhere they’d “want” to go. For example, if they just created a user, send them to the list of users page, so they see the change they just made. I’m also a big advocate of keeping URLs clean. Because of these concerns the best answer in Django is to do an HttpResponseRedirect. Now the problem with that is that you can’t pass data to a redirect. To get around this there are messages that you can send to the users session itself. The mechanism isn’t that clean, but it does work, and it does do the job. So if you have a logged in user all you need to do to add messages is: request.user.message_set.create(message='User successfully created.') Now the flip side to the equation is that you “get” the message(s). So how this works is when you set a message you’re actually adding a message to a list. When you”get” the message, you’re actually getting the list (may be more than one message). … -
Adding Your Twitter Status to a Django Site
As part of changing the layout of my blog I wanted to add my latest Twitter status to the bottom left corner. It turned out to be very straight forward. Python has an excellent Twitter API — very litle code was required. There’s two ways you could go about doing this. The first way is to write a template tag that would fetch the latest tweet, the other to create a context processor that would provide a tweet variable to your templates. I choose the latter. Before we can start, the Twitter API module needs to be installed. You can find both the module and installation instruction over on google code: http://code.google.com/p/python-twitter/. Note: I had to install the SVN version as there’s a bug in python-twitter version 0.5 when using Apache — it works fine using the development server. To set up a context processor we first need to specify where Django can find our processors. This is done using the TEMPLATE_CONTEXT_PROCESSORS setting. Add the below to your project’s settings.py file. 1 2 3 4 5 6 7 8from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_CONTEXT_PROCESSORS = TEMPLATE_CONTEXT_PROCESSORS + ( "mysite.blog.context_processors.latest_tweet", ) TWITTER_USER = "omh" TWITTER_TIMEOUT = 3600 Django has bunch of context processors already defined … -
New Django Paginator Example
edit: This example has since been added to the official Django Docs for pagination. Big thanks to Scot Hacker for taking the initiative to submit the doc patch and make this happen (IE I’m far to lazy to submit it on my own). So I pulled the latest Django codebase from svn today and I [...] -
Już jutro wersja Django 1.0 beta 1
Już jutro ma wyjść pierwsza wersja beta Django. Ostatnią bardzo ważną zmianą, było dodanie newforms-admin do drzewa głównego. Jednakże zmian jest coraz więcej. Choć nie tak dużych to równie ważnych i kłopotliwych. Lista tych rzeczy, które mnie najbardziej dotknęły. Zmiana zasady... -
Tema do Django para GNOME
Eu utilizo no meu GNOME o tema Clearlooks acho que desde que ele foi lançado. Tentei utilizar outros, mas nunca me acostumei. Depois que o grande pixel-artista Jader Rubini, fez um lindo fundo de tela para a comunidade Django Brasil, eu dei uma uma pequena personalizada no Clearlooks e o chamei de Django. E por que não? Tem as mesmas cores comumente utilizadas pelo Projeto Django. Eu achei que o conjunto (fundo de tela, clearlooks e cores) ficou bonito e agradável. Dê uma olhada: Minha área de trabalho. Se gostou também, você pode obtê-los nos links abaixo: Tema: django-gnome-theme.tar.gz Fundo de tela: DjangoBrasil_Wallpapers_by_jaderubini.zip -
DjangoCon!
I’m a little late to the announcement party, but I’ll be attending DjangoCon and sitting on a panel about Django in Journalism with Maura Chace and Matt Waite. The panel will be moderated by our own Adrian Holovaty. I think the panel will be pretty fantastic but I can’t help be just as terrified as my fellow panelists. I love that we’ll have both Journalist-programmers and Programmer-journalists on the panel, and I love that Django is so often the glue that brings the two together. DjangoCon is going to be awesome. -
Lista de discussão Django Apps
O Michael Elsdörfer criou a lista de discussão Django Apps. A idéia é utilizar a lista para suas próprias aplicações Django e isso possui, no mínimo, duas grandes vantagens: Se faz desnecessário a criação de uma lista de discussão para cada nova aplicação; Existe uma potencial possibilidade de outras pessoas, não necessariamente usuárias de suas aplicações, participarem das discussões com ótimas opiniões. Eu não iria criar listas de discussões para minhas aplicações, uma vez que o número de discussões tenderia à zero e seria uma tarefa chata, mas, com isso, as aplicações Diário, Fleshin e Tube ganharam um local para discussão! Então, quando precisar, já sabe onde pode discutir algo a respeito das aplicações citadas acima. Já adicionei o grupo de discussão nas páginas dos meus projetos no Google Code. Utilize o prefixo [diario], [fleshin] e [tube] no assunto das mensagens, como descrito na página inicial do grupo: All messages should be prefixed with the application name in brackets. If the application name itself has the popular django prefix, it should be left off. E.g. use [tables] for django-tables. -
EuroPython 2008
I started writing this post at the airport just before flying back from Vilnius to Berlin. EuroPython 2008 - the three-days conference and sprints afterwards - gave me loads of information, new relations, and better understanding of the big image of Python developers' community.Some highlights from the conference follow.During video conference the author of Python programming language Guido van Rossum encouraged using Python 2.6 just after the release, but said that Python 3.0 still shouldn't be used for production. The good future-proof practices are inheriting from object for classes, using xrange(), sorted(), and zip() functions, "//" for floor divisions, and dict.iterkeys(). The full porting to 3.0 guide will be probably written and published in the python.org site.Clone Digger is a project from Google Summer of Code 2008 for finding similar pieces of code which could be optimized by moving that to parameterized functions.Restrictive Python is a project which blocks the user from executing dangerous functions or methods or accessing files which might harm the system. You can try Restrictive Python out in the simulated terminal.Python is an interpreted language and if you want to deploy a project writen in Python, you have to be sure that the end user will … -
Annoucning sPaste.com
Tonight I am officially launching my new side project, sPaste.com! sPaste is a simple tool to help you quickly and securely send small snippets of data around the web. As usual, the site is written entirely in Django on the server side and jQuery on the client side. At the moment it is little more [...] -
A simple site-wide, per-user, date format validation system
It is important to be aware that dates are spelled differently in different countries (e.g. dd/mm/yyyy in Australia or mm/dd/yyyy in the US). This is why it is a good idea to let the user select their preferred date format and store it into their user profile. For example, you may store the values "%d/%m/%Y" or "%m/%d/%Y" in that user’s profile. That way, you may display dates in the format chosen by the user throughout the site. Now, if the site contains many forms with date fields (say, for example, you’re building a calendar application), it can be a bit repetitive and annoying to check and assign the date format for every form in every view. To go around that, I came up with a simple trick. It all happens in the following class: class FormWithFormattedDates(forms.ModelForm): def __init__(self, *args, **kwargs): date_format = None if 'date_format' in kwargs: date_format = kwargs['date_format'] del kwargs['date_format'] # The ModelForm's __init__ method doesn't expect to receive that argument, so take it out. super(FormWithFormattedDates, self).__init__(*args, **kwargs) if date_format is not None: for (field_name, field) in self.fields.items(): if isinstance(field, forms.fields.DateField): field.input_format = [date_format] field.widget = forms.widgets.DateTimeInput(format=date_format) What this class does is explore what’s in the form, and … -
Testing App Views
How to easily test views in applications which don't have a urls.py file. -
Testing App Views
First of all, thanks to those people who've been reading and pointing out improvements in the comments - it's much appreciated, and I've learned a lot from you! Django applications tend to have views, in a views.py file. These are generally looked up by URL. URLConfs (various urls.py files) are used to map request URLs to views. This can lead to a problem from a testing perspective. Not all applications have urls.py files; and for those that do, there's nothing stopping a project wiring up different URLs to those views through a custom urls.py. It therefore becomes difficult to use Django's test client to invoke a view using a GET or a POST because you don't know how that URL has been configured. After all, you run python manage.py test from your project, and the project's configuration is used. Let's say I have a views.py that looks like this: from django.shortcuts import render_to_responsefrom django.template import RequestContextdef say_hi(request): return render_to_response('app/hi.html', context=RequestContext(request)) I want to use Django's test client to ensure that when this view is called, it returns an HTTP 200 OK response. However, my app doesn't have a urls.py - the person using it is meant to wire this view … -
Testing App Views
First of all, thanks to those people who've been reading and pointing out improvements in the comments - it's much appreciated, and I've learned a lot from you! Django applications tend to have views, in a views.py file. These are generally looked up by URL. URLConfs (various urls.py files) are used to map request URLs to views. This can lead to a problem from a testing perspective. Not all applications have urls.py files; and for those that do, there's nothing stopping a project wiring up different URLs to those views through a custom urls.py. It therefore becomes difficult to use Django's test client to invoke a view using a GET or a POST because you don't know how that URL has been configured. After all, you run python manage.py test from your project, and the project's configuration is used. Let's say I have a views.py that looks like this: from django.shortcuts import render_to_responsefrom django.template import RequestContextdef say_hi(request): return render_to_response('app/hi.html', context=RequestContext(request)) I want to use Django's test client to ensure that when this view is called, it returns an HTTP 200 OK response. However, my app doesn't have a urls.py - the person using it is meant to wire this view … -
Testing App Views
First of all, thanks to those people who've been reading and pointing out improvements in the comments - it's much appreciated, and I've learned a lot from you! Django applications tend to have views, in a views.py file. These are generally looked up by URL. URLConfs (various urls.py files) are used to map request URLs to views. This can lead to a problem from a testing perspective. Not all applications have urls.py files; and for those that do, there's nothing stopping a project wiring up different URLs to those views through a custom urls.py. It therefore becomes difficult to use Django's test client to invoke a view using a GET or a POST because you don't know how that URL has been configured. After all, you run python manage.py test from your project, and the project's configuration is used. Let's say I have a views.py that looks like this: from django.shortcuts import render_to_responsefrom django.template import RequestContextdef say_hi(request): return render_to_response('app/hi.html', context=RequestContext(request)) I want to use Django's test client to ensure that when this view is called, it returns an HTTP 200 OK response. However, my app doesn't have a urls.py - the person using it is meant to wire this view … -
Django moving toward 1.0: tickets overview
As the Django web framework (see our previous study comparing 3 major web frameworks) is moving toward the 1.0 release (due in early september this year), one of the creators of Django, Adrian Holovaty, asked about the strength and weekness of Django replied: I love the way URLconfs work — like a table of contents [...] -
Time to release: django-digest and django-oauthsp
Let me be clear on this: altough I'm already using this code in byNotes, I still consider it in alpha stage, so think twice before incorporating it into your project. django-digest is an app for helping with digest authentication. It implements the basic models needed for storing the data, while authentication is handle by wapi middleware. On the other hand, django-oauthsp implements the service provider side of OAuth with all the bells and whistles. Currently, it supports the full OAuth spec, custom token attributes, token renewal as specified by ScalableOAuth and problem reporting as specified by ProblemReporting. It also includes some views for requesting, authorizing, reviewing and revoking user tokens as well as registering, editing and listing consumers. If you try this apps, you know, leave some feedback in the comments ;). -
Django
Django