[1396 total ]
Rafael Campos de Bastiani: NicEditor no Admin do Django

Depois de muito tempo sem postar algo aqui, devido a trabalho, faculdade e vícios em geral, eu resolvi fazer um pequeno tutorial de como usar um WYSIWYG, o que eu usarei neste artigo e que gostei muito dele é o NicEdit[url]http://nicedit.com[/url] ... [More] , ele é leve e bem pratico, e fácil de incorporar ao admin do Django.

O NicEdit é constituído de dois arquivos, o [b]nicEdit.js[/b] e o [b]nicEditorIcons.gif[/b] nos quais ... [Less]

Rafael Campos de Bastiani: NicEdit no Admin do Django

Depois de muito tempo sem postar algo aqui, devido a trabalho, faculdade e vícios em geral, eu resolvi fazer um pequeno tutorial de como usar um WYSIWYG, o que eu usarei neste artigo e que gostei muito dele é o NicEdit[url]http://nicedit.com[/url] ... [More] , ele é leve e bem pratico, e fácil de incorporar ao admin do Django.

O NicEdit é constituído de dois arquivos, o [b]nicEdit.js[/b] e o [b]nicEditorIcons.gif[/b] nos quais ... [Less]

Arthur Koziel: Automatical superuser creation with Django

I delete and sync my database fairly often during development with Django because the "syncdb" command will not alter the table in the database after, for example, adding a new field to the corresponding model.

The problem I have with this ... [More] is typing in the same data for a superuser over and over again. It's a very repetitive task, so I was grateful when I heard this tip from my co-worker Sebastian today.

Superuser from fixture

We're going to automatically load the superuser from a fixture. To do this, dump the data of the auth module into a fixture called "initial_data.json":

./manage.py dumpdata --indent=2 auth > initial_data.json

You'll see that along the superuser that you've already created during the usual "syncdb" execution, a few other credentials got dumped. Since we only need the data for the superuser, delete the irrelevant stuff. The file should look like this:

[
{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "arthur",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2008-09-04 14:25:29",
"groups": [],
"user_permissions": [],
"password": "sha1$fooobar123",
"email": "arthur@arthurkoziel.com",
"date_joined": "2008-09-04 14:25:29"
}
}
]

The fixture called "initial_data.json" will automatically get loaded by Django every time you execute the "syncdb" command.

Delete your database and try to run the "syncdb" command with the "--noinput" option passed (it will prevent the script to go into interactive mode):

./manage.py syncdb --noinput

There shouldn't be a prompt for a superuser and you should see a message at the end of the output indicating that your fixture was loaded.

Admin login

Not having to create a superuser is great, but if you're working a lot with Django's contrib.admin application, you'll need to log-in again every time you sync the database and load the user fixture. Another repetitive task that can be eliminated:

After logging in into the admin backend, dump the data of the "session" table into stdout:

./manage.py dumpdata --indent=2 sessions

Copy the dictionary containing the session for your superuser and append it to the list in "inital_data.json" like this:

[
{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "arthur",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2008-09-04 14:25:29",
"groups": [],
"user_permissions": [],
"password": "sha1$foobarbarfoo",
"email": "arthur@arthurkoziel.com",
"date_joined": "2008-09-04 14:25:29"
}
},
{
"pk": "9aadfe1de61b0937fasd684221f03",
"model": "sessions.session",
"fields": {
"expire_date": "2008-10-20 14:34:59",
"session_data": "foobar123"
}
}
]

You might want to increase the "expire_date" a little bit, so that your session won't expire.

Now everytime you delete and sync your database (remember to pass "--noinput"), Django will automatically load the superuser and it's associated session from the fixture. You won't have to manually type in the data for the user and log-in into the backend everytime anymore. [Less]

Eric Florenzano: [Link] This Week in Django

The TWiD guys have outdone themselves yet again! I have had the distinct honor of appearing and guest hosting on their show. Now they have completely re-done their website. This is one of the best redesigns I've seen in quite a while, and I'm certain that it will become a defacto goto for great Django information and news.

Eric Florenzano: [Link] Zerok's Blog

Zerok has committed a ton of great patches to my Django reusable application projects. Every time that I review one of his patches, it goes through without any modifications. This guy not only provides great patches, but he has some great Django tips and tricks. Subscribe to his blog for some serious Django tips and tricks.

Hugo: Django 1.0 released!

Django 1.0 released! - hat lange gedauert, aber das kann ja durchaus der Qualität zuträglich sein. Und hier ist es das. Gratulation!

Will Larson: Migrating the 'This Week in Django' Concept

In honor of the fresh redesign at This Week In Django, I decided to spend a few moments considering why this amazing concept hasn't caught on with other projects yet. Sure--Michael, Brian and Kevin put in a huge amount of time week after week--but ... [More] maybe there is something more?

This Week in iPhone Development
Soundtrack: any hit that allows silhouettes to groove violently.

Welcome to This Week in iPhone Development! We have a really exceptional show lined up for you.

Yes. Thats right. This week showed some crucial developments over at Apple. In fact, some of the engineers I have spoken to referred to the changes as "more exciting than my first child."

Really? So lets get started talking about those changes.

Ah.. right. Well, I'd love to. But our legal department is pretty sure we can't talk about it in public without violating the NDA.

Right. That's still a problem. How about this week in the blogs then?

Well, legal isn't really comfortable with us talking about those either. It might make us complicit or something.

Well. This has been another Week in iPhone Development. Tune in next week for more of the same great news!

This Week in Google Chrome
Soundtrack: something with the same levels of oddity and production values as the song for the Scala programming language1.

Welcome to This Week in Google Chrome!

Google made a goddamn browser. Holy hell. It's amazing.

Well, beyond being a browser, it has some really impressive technical qualities.

Man. This is so amazing. Reddit Programming is loving Google Chrome! Google made a browser!

Well, if we take a look at John Resig's piece on Google Chrome's Process Manager, then we begin to see how Chrome has some technical merit and may open up a new spurt of browser development.

Browsers have been spending a considerable amount of time working on CSS rendering, and I think its exciting that we'll come back to having a more holistic approach to browser development, that spends time looking at intuitive and uncluttered interfaces as well as performance issues.

Its a browser, dude. I can't believe I'm getting a browser!

Fuck it. I quit. You're worse than the color anouncer in Best in Show.

Anyway, after reflecting on it, it does seem there may be some explanations for why This Week in Django's brilliance hasn't yet migrated into other communities.

Strangely enough, the song is no longer prominently featured on their website. I was able to find a possibly usable link though on a blogspot blog entry. If someone finds a better link, let me know.↩ [Less]

Simon Willison: Think Wize crew celebrates the Django 1.0 release

Think Wize crew celebrates the Django 1.0 release. With a trip to the Django Reinhardt museum at his birthplace in the village of Liberchies, Belgium.

Ville Säävuori: Django Release Party in Helsinki

Heads up Finnish Djangonauts! Join us for celebrating the Django 1.0 release at Kaapelitehdas, Helsinki tomorrow evening (Saturday 6th) starting at 5 pm. More information on the location and attendees can be found on the event wiki ... [More] page.

This is an open invite — everyone is welcome!

See you there! :)

» Comment this entry [Less]

Gustavo Picón: Django 1.0 was released

Finally, Django reaches 1.0 status. If you have been using 0.96.x, it will be quite a bit of work to upgrade your apps, but it’s worth the effort. According to the release notes:
Since Django 0.96, we’ve made over 4,000 code commits, fixed more than 2,000 bugs, and edited, added, or removed around 350,000 lines of [...]

Joe Heck: Django 1.0

Congratulations to the entire development team and Django community for making the Django 1.0 release today! It’s a monumental accomplishment, and I’m very pleased to see it here.
I’m not as active in the community these days ... [More] , but I’m still using the project on a regular basis as one of my “secret weapons” to get things [...] [Less]

Sean O'Connor: Quick Django Trick

Recently while playing around with a Django model in the always awesome iPython shell I discoved a neat feature of the Django ORM.  It’s basically a way to get the id of a related object without actually triggering a query to get all of the related object’s data.
Frequently when working with a model which has [...]

Ivan Sagalaev: Транк — вот что главное

Вышла долгожданная версия Джанго 1.0. Мои самые искренние поздравления всем, кто участвовал и всем, кто сочувствовал. Совершенно серьезно ... [More] я считаю, что на данный момент это лучший питоновый веб-фреймворк.

Тем не менее, я хочу по случаю посмотреть на этот релиз с нетрадиционной стороны и, возможно, несколько войти в диссонанс с эйфорией, которая сейчас начнется :-).

Разговаривая с людьми [...] [Less]

Alex Koshelev: Рождение Django 1.0

Ну вот. Даже как-то грустно. То чего все мы так долго ждали наконец свершилось. Джанга родилась в своем релизном варианте с гордым "1.0" на ... [More] ярлыке.

Почему грустно? Да потому, что тот темп, с которым менялась джанга последний год(с лишним), приучил нас быть всегда в тонусе, следить за изменениями, подстраиваться под них и как-то менять своё видение этого чудесного фреймворка. А что теперь? Мне кажется что темп упадет, а значит и драйв обитания на trunk будет не такой как раньше.

Ну ладно с ним с драйвом, будем искать в других областях. Важно то что наконец джанга должна приобрести общепризнанный статус production/enterprice-ready и пойти в массы с ещё более быстрыми темпами. Компании (конечно в большей степени управленцы в них), которые раньше на этапе выбора платформы и инструмента воротили нос от продукта, который был, как им казалось, не готов для боевого применения, сейчас начнут пересматривать свои воззрения, и уже для новых проектов боле пристально смотреть на джагу как на реального кандидата в освоении и применении. Я на это надеюсь по крайней мере. Пусть для многих смелых и разумных, уже давно джанга вполне была готовой к бою, но всё равно оставались сомневающиеся.

Так же теперь в споре на лидерство на рынке веб-фреймворков для быстрой разработки приложений у джанго есть новый веский довод.

Кстати, то что была организована Django Software Foundation, тоже придает солидности и добавляет козырей в колоду нашего любимого фреймворка.

Ожидаю всплеск интереса как к самой джанги, так и к сообществу в целом, как это было например после релиза GAE. А это поможет нам, разработчикам и отчасти евангелистам, быть более на виду и на нас станут обращать больше внимания. А кому этого не хочется?:)

Главное, чтобы после вселенской гулянки, корные разработчики продолжали привносить новые идеи и концепции для улучшения существующего положения вещей внутри фреймворка. А мы в свою очередь будем продолжать их осваивать и использовать в своих разработках, пусть с меньшей скоростью чем раньше. Но может быть это и не плохо? А может вообще всё будет по другому? Посмотрим.

Огромный шаг в завоевании умов и сердец веб-разработчиков сделан, кто раньше ещё размышлял "быть или не быть", теперь с большей долей вероятности скажут - "быть"!

Что же, живем и работаем дальше, но уже с чуть другим чувством. Да, и приходим обязательно на локальную гулянку в честь этого события!

PS: Интересно, а я один был озабочен вопросом - кто быстрее: джанга или гугл хром:)

Теги:
django

python

web [Less]

Mercurytide: Django articles: Django cheat sheet

With the release of Django 1.0, we're pleased to announce the release of a completely updated version of our highly popular Django Cheat Sheet which is crammed with a whole host of useful Django information.

Shwagroo Team: Django 1.0

Jak już zapewne wszystkim wiadomo, zostało wydane Django 1.0. Wiedziałem, że chłopakom się uda :).
Ostatnio powstało kilka niekompatybilnych wstecz zmian, jednakże w żaden sposób one mnie nie dotknęły. Pełną listę niekompatybilnych zmian możecie zobaczyć na...

Patrick Altman: Django Blog in the Works

I am previously stated my desire about rebuilding Shifting Bits into a Django-based blog, but it has been really slow going due to other time commitments.

Over the weekend, I started cutting out a fresh new template and a migration script to get my data export from WordPress into my Post model (borrowing heavily from Brian [...]

This Week in Django: This Week in Django 36

This Week in Django is a weekly podcast about all things Django.

This week we have James Bennett on the program discussing his book, the blog, speaking, and a whole lot more. We also discuss a few source commits, some cool projects from the ... [More] community, and the Tip of the Week.

Please see the Show Notes below for all the pertinent information and links

Show Notes

Big News (1:40)

New Comments Lands in Trunk (8557) – New Comments was just merged into trunk. So glad this one made it in time. Good work Thejaswi Puthraya (theju). It was his Google Summer of Code project. Also thanks goes to Jannis Leidel his mentor.

Upgrade Guide
Backwards Incompatible Change

Django Beta 2 Released – another important step in the push to Django 1.0.

Release Notes

Official Django 1.0 Release Party Announced – dinner party at the Tied House in Mountain View on Saturday, September 6th at 7pm. Coincides with DjangoCon, but all are invited to attend.

Interview – James Bennett (9:05)

James Bennett works for The World Online, the birthplace of Django, where he helps to develop Ellington, a content management system for news companies that is written in Django. He is also the Release Manager for the Django project, and an occasional contributor of code and documentation. He’s written the very popular book, Practical Django Projects for Apress and he is the man behind the always interesting blog The B-List.

Links

The B-List Blog
Ellington
How the news breaks – excellent post by Jacob Kaplan-Moss on the news process with election results. It’s very innovative.
Google Code Projects
Practical Django Projects
Let’s talk about documentation

Tracking Trunk (1:19:36)

X-View Middleware is removed from defaults (8537) – apparently just used for the docs and causing some confusion.

Fixed timesince filter to handle timezone-aware times (8579)

Removed oldforms, validators, and related code (8616)

ModelForms made more like Forms (8618)

Community Catchup (1:28:55)

Creating a Basic API with Django

Django Nashville – if you’re in the Nashville area there’s a new Google Group and plans for a meetup. We encourage you to head on over and add your name to the list.

Debugging Django Screencasts – Eric Holscher is planning a series of 5 – 7 screencasts that focus on debugging approaches with Django. It’s an excellent series so far and I’m looking for a lot more from Eric.

Screencast: Debugging with the Django Error Page
Screencast 2: Logging in Django, for fun and profit
Using pdb, the Python Debugger

Using Akismet with Django’s New Comments Framework – Great post on getting Akismet going with the newly landed comments framework. Be sure to read the comments on this one.

django-monetize – django-monetize is a pluggable Django app which aims to make it trivial to intelligently monetize your Django projects. So far, django-monetize has built in support for Amazon Affiliates’ Custom Links, Amazon Affiliates’ Omakase, Amazon Affiliates’ Search Links, Amazon Honor System donations, Dreamhost referrals, Google Adsense ad units, Paypal donations, and SliceHost referrals.

Satchmo trunk stabelizes with Django trunk Bruce Kroeze just checked in updates to Satchmo trunk which now means
Satchmo-trunk (rev 1469 or higher) should jive with Django trunk (rev 8761 or higher).
Please note the Backwards incompatible changes here – with these changes, Satchmo should be done with the last of the major incompatibility changes between Django and Satchmo.

Satchmo Developers on TWiD 31

Tip of the Week (1:40:51)

In my twitter last week I mentioned that I was frustrated by the lack of a first() method on the QuerySet so I just added one. I had a couple of people ask me how I did that. Well Django has this idea of Custom Managers that you can create for your models. I generally put this in its own managers.py module but you can put it anywhere.

from django.db import models

class PostManager(models.Manager):
def first(self):
return self.get_query_set()0

Once this is in place you need to add a line that indicates that you’ll be using your custom manager in place of the default one:

objects = managers.PostManager()

This technique is also featured on Page 160 in Practical Django Projects. James uses the approach to wrap up some complex extra() query so it’s simply accessible from the view. It’s a great approach and something you should try to do whenever possible.

jQuery style chaining with the Django ORM

Thank You! (1:45:04)

Lots of Vim goodness

Hacker Public Radio – VIM is my IDE – Jonas Rullo on his Hacker Public Radio podcast makes mention of This Week in Django and talks about his VIM setup.
Vim Screencast: Selections – Justin Lilly screencast on using visual mode for selections.
Vim Screencast: % Operator – Justin Lilly screencast on using the % operator in VIM. [Less]

Michael Trier: This Week in Django 36 - 2008-08-31

This Week in Django 36 has been posted. It’s a great episode with our special guest James Bennett. Hear James talk about the book, the blog, speaking, and a whole lot more.

Simon Willison: Announcing dmigrations

The team at Global Radio (formerly GCap Media) is the largest group of Django developers I’ve personally worked with, consisting of 14 developers split into two scrum teams, all contributing to the same overall codebase.

Working with that ... [More] many developers makes smart tools and processes essential, and in some cases we’ve had to develop our own. Today, we’re releasing one of them as an open source project.

dmigrations is a Django migrations tool. It addresses a common problem in Django development: if you change a model after creating the database tables for it with syncdb, how do you reflect those changes in your database tables without blowing away your existing data and starting again from scratch?

django-evolution attempts to address this problem the clever way, by detecting changes to models that are not yet reflected in the database schema and figuring out what needs to be done to bring the two back in sync. In contrast, dmigrations takes the stupid approach: it requires you to explicitly state the changes in a sequence of migrations, which will be applied in turn to bring a database up to the most recent state that reflects the underlying models.

This means extra work for developers who create migrations, but it also makes the whole process completely transparent—for our projects, we decided to go with the simplest system that could possibly work.

The interface to dmigrations is a pair of custom Django commands. The first, ./manage.py dmigrate, provides a set of command for listing, applying and unapplying (reverting) migrations. This entirely replaces Django’s syncdb command.

The second, ./manage.py dmigration, provides commands for code-generating new migrations. It turns out that most migrations fit a set of common patterns: add a new table, add the tables for a new Django application, add a column to an existing table, add an index. These common cases are handled by dmigration; if you want to do something more complex (rename a column while transforming its data for example) you’ll need to write a custom migration class.

The dmigrations tutorial provides a full introduction to both of these commands, as well as hints on writing your own custom migrations. Since migrations are just classes, one of our hopes is that external developers will write extra migration classes for operations like “rename column”—things that currently requires a one-off custom migration.

dmigrations is actually the third iteration of our in-house migrations system. The first, smigrations, was designed to do the least amount of work possible to give us a controlled way of applying changes to our database schemas. The ’s’ stood for ’simple’. The second version (dmigrations) written by Tomasz Wegrzanowski consisted of a major upgrade to smigrations that addressed many of the frustrations we found when using it with branched development, in particular the problem of migrations in two branches conflicting with each other. The ’d’ stood for ’distributed’.

Version three, released today, is my refactoring of dmigrations to de-couple it from the rest of our codebase. I’ve also stubbed out hooks for adding support for alternative database engines; dmigrations only supports MySQL out of the box, but I’m keen on getting it working with other databases now that it’s out in the wild. Patches welcome!

How does this fit in with South and django-evolution?

That’s an excellent question. We’ll be discussing all three systems on the schema evolution panel at DjangoCon this weekend. I would love to see co-operation between the projects; at the very least I’d like to see the emergence of a standard Django-style abstraction library for create/alter table statements (something we punted on entirely with dmigrations). You’ll certainly be hearing a lot more about migrations in Django after the conference. [Less]

Simon Willison: dmigrations thread on Django Nashville

dmigrations thread on Django Nashville. The Django Nashville Google Group is currently hosting the most interesting discussion of dmigrations.

Simon Willison: Low level hooks for multi-database support in Django

Low level hooks for multi-database support in Django. As discussed in this sub-thread on reddit: The internal Django Query class has a ’connection’ attribute which can be set by the constructor. This low level hook is the secret to talking to ... [More] more than one database at once, but higher level APIs have not yet been defined. Jacob Kaplan-Moss: “As a matter of fact, at least a couple high-traffic Django sites are using the new hooks.” [Less]

Michael Trier: Django 1.0

Well it’s finally here. Django 1.0 is the moment a lot of us have been waiting for. It’s a very exciting moment for the Django team but even more so for the development community at large. It represents a huge milestone in the web ... [More] framework space.

Django, without a doubt, brings forth some incredibly innovative ideas that help take web development to the next level. So I am pleased to be a part of this, in some small way, but also looking forward to what’s next for Django and its popularity as a web framework.

If you haven’t had the pleasure to experience Django I encourage you to do so now. You’re programming mind will thank you for the experience. [Less]

Andrew Godwin: South 0.3

The world of migrations in Django is definitely warming up now, and with that we're proud to announce the release of South 0.3, the 'intelligent django migrations app', available now from south.aeracode.org.

New in this release are the use ... [More] of fields rather than dicts for specifying columns in migrations, so migrations now look cleaner, work with all the databases Django supports to a better extent, and even support custom fields.

Also new is dependencies between apps, for those situations where your forum app's Post depends on your accounts app's Profile; South will work out the right way to apply everything so foreign keys don't horribly break.

There's also a nice number of bugfixes and general tweaks Andy and I have been making as South moves towards being used in active development work. If you think you might be needing migrations, or even if you don't, give South a try!

(Also new is a very carefully worded "why we're best" page on our wiki. I'm trying not to step on people's toes, just say why we're using South rather than anything else, but I'm not sure how well that's working) [Less]

Simon Willison: Django 1.0 released!

Django 1.0 released!. Outstanding. Massive thanks to everyone who contributed. We made it!

Simon Willison: Django 1.0 release notes

Django 1.0 release notes. What’s new in Django 1.0. Short answer: one heck of a lot.

Django 1.0 released!

No, you’re not hallucinating, it’s really here.

Around three years ago, Adrian, Simon, Wilson and I released some code to the
world. Our plan was to hack quietly on it for a bit, release a solid 1.0
release, and then ... [More] really get the ball rolling.

Well.

What happened, of course, was that an amazing community sprung up literally
overnight — our IRC channel had over a hundred people in it the day after
release, and it’s never been that “empty” since.

I really can’t stress enough how amazing our community of users and developers
are. About half of the code that’s gone into Django over the past three years
has been contributed by someone other than a core committer. Since our last
stable release, we’ve made over 4,000 code commits, fixed more than 2,000 bugs,
and edited, added, or removed around 350,000 lines of code. We’ve also added
40,000 lines of new documentation, and greatly improved what was already there.

Django 1.0 represents a the largest milestone in Django’s development to date: a
web framework that a group of perfectionists can truly be proud of. Without this
amazing community, though, it would have never happened.

You can download Django 1.0 on the Django downloads
page, and read the complete release
notes.

For distributors and for verification purposes, a file containing the MD5 and
SHA1 checksums of the 1.0 package has been placed on the djangoproject.com
server. This file
is PGP-signed with the Django release manager’s public key. This key has the ID
0x8C8B2AE1 and can be obtained from, e.g., the MIT PGP
keyserver. [Less]

Django 1.0 release candidate now available

In accordance with the (updated) Django 1.0 release roadmap, today we've released the first release candidate for Django 1.0.

To grab a copy of the release candidate, head over to the Django downloads page, and be sure to read the release ... [More] notes. Please keep in mind, though, that this release is not meant for production use, and is intended primarily for developers who are interested in checking out the new features in 1.0 and helping to identify and resolve bugs prior to the final release. The 1.0 alpha and beta releases and release candidates will not receive long-term support and will not be updated with security fixes, since their main purpose is to serve as a stepping-stone on the path to the final Django 1.0, due to be released as soon as possible..

For distributors and for verification purposes, a file containing the MD5 and SHA1 checksums of the release candidate package has been placed on the djangoproject.com server. This file is PGP-signed with the Django release manager's public key. This key has the ID 0x8C8B2AE1 and can be obtained from, e.g., the MIT PGP keyserver. [Less]

Eric Holscher: Using pdb to debug management commands and unit tests (Debugging Django Series,Part 4)

Screencast 4
Today's screencast is about pdb again. This time we are going to be debugging management commands, and unit tests for django. This is a little bit more powerful than the previous screencast which just introduced the basic debugging ... [More] commands.

Setup
This screencast uses a couple of really handy pieces of software. iPython is a wonderful piece of software for all python developers. It gives you handy things like tab completion, syntax highlighting, and all the modern amenities that we're used to in our editor from the python shell. Django's manage.py shell even uses ipython if it detects it, that's an endorsement if i've ever heard one.

ipdb is a simple wrapper around pdb that allows you to use ipython when you are doing your debugging. This is really handy as well. To get the code for these projects, go to their websites linked above or use the following code:

bzr branch lp:ipython
easy_install ipdb

Download and Video
You can download the video here (20MB mov)

Debugging management commands and unit tests from Eric Holscher on Vimeo.

Writeup
We start the screencast by breaking the testmaker management command that I've written. We call it like this:

python -i ~/EH/manage.py testmaker 67.207.139.9:8000

The import thing to note is the -i, which tells python to drop into the python (>>>) shell after the command is run. I then show how to use pdb postmordem command to go back into the crashed management command. This is called like so:

import pdb
pdb.pm()

and this allows you to actually go back into the previous command! Even if pdb isn't currently loaded at the time. This is a really neat feature of the debugger, and incredibly useful for diagnosing breakage that is hard to reproduce. You can go back up into the application and see the actual state of the variables at that time.

Next I introduce ipython which is a really nice python distribution. It has a really nice debugger, called idpb, which gives you all the ipython commands inside the debugger.

Next we go on to run testmaker with valid input after showing how to do a simple fix to check if the input was correct. We call ipython with an app passed in:

ipython ~/EH/manage.py testmaker 67.207.139.9:8000 -- -a mine

Note that -- is meant to tell bash that the input is done for ipython, and the rest will actually go to manage.py and into your python code. This is good to know for trying to pass things into management commands in ipython on the command line. This code will generate tests and fixtures for the application inside of the mine/ directory. Once we browser around a little on the test server, we have generated a unit test based on what we have done.

Assuming you have ipdb installed from Pypi, you can include ipdb inside of your unit test (or any python file being executed) and get the ipython debugger instead of vanilla pdb:

import ipdb
ipdb.set_trace()

Although I don't expound on it inside of the screencast, getting inside of tests is probably one of the more useful things you can do with the debugger. Trying to debug tests is really difficult, and sometimes they return really strange errors that are hard to get a handle on. Sometimes the line numbers are also off, and debugging doctests are notoriously hard to debug. You can debug doctests just as easily, with the following code (using ipdb if preferred):

>>> import pdb
>>> pdb.set_trace()

I figured out that the error in the unit test was actually due to a stale fixture left over from a previous run of the testmaker app. It didn't have enough data to return a paginated list, so has_next was false instead of true like when we ran it against the live database.

In related news, searching for ipdb on google made me stumble onto the The Internet Pinball Machine Database, which I didn't know existed previously. Yess! [Less]

Eric Holscher: Using pdb to debug management commands and unit tests (Debugging Django Series,Part 4)

Screencast 4
Today's screencast is about pdb again. This time we are going to be debugging management commands, and unit tests for django. This is a little bit more powerful than the previous screencast which just introduced the basic debugging ... [More] commands.

Setup
This screencast uses a couple of really handy pieces of software. iPython is a wonderful piece of software for all python developers. It gives you handy things like tab completion, syntax highlighting, and all the modern amenities that we're used to in our editor from the python shell. Django's manage.py shell even uses ipython if it detects it, that's an endorsement if i've ever heard one.

ipdb is a simple wrapper around pdb that allows you to use ipython when you are doing your debugging. This is really handy as well. To get the code for these projects, go to their websites linked above or use the following code:

bzr branch lp:ipython
easy_install ipdb

Download and Video
You can download the video here (20MB mov)

Debugging management commands and unit tests from Eric Holscher on Vimeo.

Writeup
We start the screencast by breaking the testmaker management command that I've written. We call it like this:

python -i ~/EH/manage.py testmaker 67.207.139.9:8000

The import thing to note is the -i, which tells python to drop into the python (>>>) shell after the command is run. I then show how to use pdb postmordem command to go back into the crashed management command. This is called like so:

import pdb
pdb.pm()

and this allows you to actually go back into the previous command! Even if pdb isn't currently loaded at the time. This is a really neat feature of the debugger, and incredibly useful for diagnosing breakage that is hard to reproduce. You can go back up into the application and see the actual state of the variables at that time.

Next I introduce ipython which is a really nice python distribution. It has a really nice debugger, called idpb, which gives you all the ipython commands inside the debugger.

Next we go on to run testmaker with valid input after showing how to do a simple fix to check if the input was correct. We call ipython with an app passed in:

ipython ~/EH/manage.py testmaker 67.207.139.9:8000 -- -a mine

Note that -- is meant to tell bash that the input is done for ipython, and the rest will actually go to manage.py and into your python code. This is good to know for trying to pass things into management commands in ipython on the command line. This code will generate tests and fixtures for the application inside of the mine/ directory. Once we browser around a little on the test server, we have generated a unit test based on what we have done.

Assuming you have ipdb installed from Pypi, you can include ipdb inside of your unit test (or any python file being executed) and get the ipython debugger instead of vanilla pdb:

import ipdb
ipdb.set_trace()

Although I don't expound on it inside of the screencast, getting inside of tests is probably one of the more useful things you can do with the debugger. Trying to debug tests is really difficult, and sometimes they return really strange errors that are hard to get a handle on. Sometimes the line numbers are also off, and debugging doctests are notoriously hard to debug. You can debug doctests just as easily, with the following code (using ipdb if preferred):

>>> import pdb
>>> pdb.set_trace()

I figured out that the error in the unit test was actually due to a stale fixture left over from a previous run of the testmaker app. It didn't have enough data to return a paginated list, so has_next was false instead of true like when we ran it against the live database.

In related news, searching for ipdb on google made me stumble onto the The Internet Pinball Machine Database, which I didn't know existed previously. Yess! [Less]