Monday, June 15, 2009

Django TypeError Exception

One of the central pieces of Django is

This file is well documented and serves as a central place to match what pages get served by what URLs. Seems simple enough since they accept regular expressions.

One thing I did run into though was getting a TypeError exception. It looked something like this:

TypeError at /applicationname/

index() takes exactly 1 argument (2 given)

To me I was puzzled why this was happening. The reason is that when Django parses the regular expression it not only does a match but saves each of the tuples in the regular expression. In the documentation it is this line:

"The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments."

So what happens is that when you start to get fancy with your regular expressions the function signature in your needs to change as well to accommodate the extra parameters.


Kenny said...

Thanks to your post I've found that the error was actually in the URL regex. Thanks :)

Brent said...

You can also write your regex to use non-capturing groups if you don't want to create a new argument to be passed into the view. Just use a question mark and colon right inside your parentheses. Example: (?:willnotcapture)