Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Ordering Edit Inlines
In my continued experimentation with the newforms-admin branch of Django, I wanted to figure out how to order fields of an inline. Looking at the documentation for inlines I saw there was not an ordering field. I had thought that there was but it turns out I was just mistaken in the object hierarchy. InlineModelAdmin inherits from BaseModelAdmin the same as ModelAdmin -- I was thinking that InlineModelAdmin inherited from ModelAdmin. Therefore, I had to determine a way to accomplish this via some spelunking through the code. At first, I thought I'd just create my own template by inheriting or copying the tabular.html template. After looking at it, I determined that I didn't want to figure out how to do a regroup on inline_admin_formset or if even that was the proper way to try to order things in that template. After a few minutes in the code I realized that I could just subclass BaseInlineFormset and specify the fields that I wanted to order by (in this example I will use start_time and end_time: from django.contrib import admin from django.newforms.models import BaseInlineFormset class MyOrderedFormset(BaseInlineFormset): def get_queryset(self): qs = super(SessionInlineFormset, self).get_queryset() return qs.order_by('start_time', 'end_time') class MyOrderedInline(admin.TabularInline): model = MyModel extra = … -
EuroPython 2008, day 2
I skipped most of the sessions for the day as they didn't seem even remotely interesting to me. But, the ones I did attend where really good. [Last nights partying](http://www.flickr.com/photos/uninen/2647190250/) kept me pretty much in bed for better part of the morning. **Descriptor tutorial** by Raymond D. Hettinger was very good and I think it was actually the first conference tutorial ever that actually teached me something about programming and Python in general. There was quite a bit testing-related material on the **Lightning talks**. One thing I wrote down on my notes was the phrase "Given enough tests, all bugs are shallow" (originally from Linus Torvalds in a form "Given enough eyeballs, all bugs are shallow"). The **keynote talk** for the day was something that absolutely blew my mind. Hans Rosling talked about [Gapminder](http://www.gapminder.org/) and how statstical data and databases should be free. First thing that crossed my mind when listening to him was that "I wonder if Adrian Holovaty has ever talked to this guy -- they'd have much to talk about". If you havent heard about Gapminder or Hans Rosling before, you should definitely [see his talk on last years TED conference](http://www.ted.com/index.php/talks/hans_rosling_shows_the_best_stats_you_ve_ever_seen.html). In Django-terms, thats some cool shit … -
Legibilidade e reaproveitamento de código na "URLConf"
É comum nas configurações de URL (URLconf) [1] do Django, patterns como este abaixo: urlpatterns = patterns( 'django.views.generic.date_based', (r'^(?P<year>\d{4})/(?P<month>[0-9]{2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, slug_field='slug', month_format='%m')), (r'^(?P<year>\d{4})/(?P<month>[0-9]{2})/(?P<day>\d{1,2})/$', 'archive_day', dict(info_dict, month_format='%m')), (r'^(?P<year>\d{4})/(?P<month>[0-9]{2})/$', 'archive_month', dict(info_dict, month_format='%m')), (r'^(?P<year>\d{4})/$', 'archive_year', info_dict), (r'^/?$', 'archive_index', dict(info_dict, num_latest=5)), ) Apesar da modificação nas URLs serem raras, a legibilidade da forma acima, queira ou não, prejudica numa eventual manutenção e a probabilidade de ocorrer um erro aumenta. Uma solução que ao meu ver facilita muito a leitura seria utilizando a função url(), como no código abaixo, retirado do django-fleshin: photo_detail = url( regex = '^(?P<album>[-\w]+)/(?P<slug>[-\w]+)/$', view = 'fleshin.views.photo_detail', kwargs = dict(photo_info_dict, slug_field='slug'), name = 'fleshin-photo' ) photo_list = url( # all photos + album list regex = '^$', view = 'django.views.generic.list_detail.object_list', kwargs = dict(photo_info_dict, paginate_by=FLESHIN_NUM_LATEST, extra_context={'album_list': Album.objects.all}), name = 'fleshin-photo-list' ) photo_album_list = url( # only photos in ``album`` regex = '^(?P<album>[-\w]+)/$', view = 'fleshin.views.photo_list', kwargs = dict(photo_info_dict, paginate_by=FLESHIN_NUM_LATEST), name = 'fleshin-photo-album-list' ) urlpatterns = patterns('', photo_detail, photo_list, photo_album_list) Perceba também que a forma acima facilita a reutilização dos patterns pelo seu projeto, não ficando preso ao que foi definido no django-fleshin, reaproveitando, por exemplo, o mesmo padrão de URL para o detalhamento de uma Photo (photo_detail) e alterando o padrão … -
EuroPython 2008, day 1
After a long year of exiting projects and neverending days at the office, I found myself again from EuroPython conference at Vilnius. The first conference day was full of interesting happenings, mainly reviving old and creating new connections. For all the sessions I attended during the day, I made some notes on few of them. Here are some basic notes about selected ones: ###Build an App in a Week by Marcin Kaszynski - [favpico.com](http://favpico.com/) etc - Suprisingly many of the attendees (about half) use Django - Use aDjango admin for users, too (not only for admins) - "Commit early, commit often" - Share code only via vcs - Use conventions - @with_template decorator - Note: you can use admin docs (template name) - Tests Do save time - self.login(), get, find - coverage.py - Instant Django This talk was interesting but didn't really give much new stuff (at least for me). There was a discussion about how it makes sense to use convention of naming templates like `app/viewname.html` but I pointed out that if you for some reason want to part from that convention (that I believe most Django developers use), you can just point Django admin site help section … -
Launching a High Performance Django Site
Are the brakes on your Django app? When building an application using an application framework like Django... the priority is often to get the application working first and optimize it later. The trade off is between getting it done and getting it done for 1 million users. Here's a check list of things you can do to make sure your application can be optimized quickly when you put on your optimization hat. Note, most applications don't need all of this since most applications do not get anywhere near enough traffic to justify even bothering. But if you're lucky enough to need to optimize your Django app, I hope this post can help you. Note, my background is in building very large high traffic sites for companies such as Fanball.com, AOL Fantasy Sports, eBay.ca, PGATour and NASCAR. All of those sites were built using ColdFusion/Microsoft SQLServer or MySQL or Oracle and I only recently jumped into Django. If you're familiar with fantasy sports, you know that you usually rush to a site to set your line up just before a sporting event starts and then you check your score when an event is live. This traffic is extremely high during those … -
Managing Database Changes in Django
Introduction Managing database changes in a team environment working on a django project can be complicated. I would imagine that there is no one size fits all solution and it would depend on team size and configuration, production database size, etc. What I will outline here is a solution I developed for a small team that I work with on a django based web application. So far it has worked really well for allowing us to streamline database changes so we can stay in sync, deploy easily, and add small tweaks to the database (indexing, data manipulation, etc.) that is semi-automated. The idea is based partly on Rails database migrations (though not has sleek and well put together) and a database versioning system that was used on a team that I have worked on previously using MS SQL in a corporate environment and a fairly decent team size. In one sense it is not nearly as well put together as either of these two solutions, but at the same time, it is pretty much hands off and has been working well for us for a number of months now. Why not just use syncdb? As nice as python manage.py syncdb … -
Managing Database Changes in Django
Introduction Managing database changes in a team environment working on a django project can be complicated. I would imagine that there is no one size fits all solution and it would depend on team size and configuration, production database size, etc. What I will outline here is a solution I developed for a small team that I work with on a django based web application. So far it has worked really well for allowing us to streamline database changes so we can stay in sync, deploy easily, and add small tweaks to the database (indexing, data manipulation, etc.) that is semi-automated. The idea is based partly on Rails database migrations (though not has sleek and well put together) and a database versioning system that was used on a team that I have worked on previously using MS SQL in a corporate environment and a fairly decent team size. In one sense it is not nearly as well put together as either of these two solutions, but at the same time, it is pretty much hands off and has been working well for us for a number of months now. Why not just use syncdb? As nice as <code>python manage.py syncdb</code> … -
Django Unit Tests and Transactions
While these are more properly integration tests than unit tests, it can be handy to have Django roll back the database transaction after each test method runs. -
Django Unit Tests and Transactions
Coming to automated testing in Django from the Zope and Plone world, I was pleased to find full support for all the testing machinery that I've become used to: regular Python unit tests, and doctests. Of course, these being unit tests, they don't do any 'framework' management out of the box. Unit tests are supposed to test your code, and just your code. However, once you're in a framework environment (be that Zope and Plone, Django, or anything else) then testing how your code integrates with that framework is vital. Zope and Plone provide unittest.TestCase subclasses (ZopeTestCase and PloneTestCase respectively) which provide a lot of scaffolding for you to be able to run integration tests. Part of that scaffolding is automatic transaction management. This hooks into Zope's transaction API to roll back the transaction after each test runs. I wanted to do something similar for my Django test cases; I was finding 'state pollution' between my unit test runs, since data created by one test method isn't automatically cleaned out. Django's transaction handling is much simpler than Zope's: it cares only about the one database transaction that the current request has, and only if the transaction support middleware is installed. … -
Django Unit Tests and Transactions
Coming to automated testing in Django from the Zope and Plone world, I was pleased to find full support for all the testing machinery that I've become used to: regular Python unit tests, and doctests. Of course, these being unit tests, they don't do any 'framework' management out of the box. Unit tests are supposed to test your code, and just your code. However, once you're in a framework environment (be that Zope and Plone, Django, or anything else) then testing how your code integrates with that framework is vital. Zope and Plone provide unittest.TestCase subclasses (ZopeTestCase and PloneTestCase respectively) which provide a lot of scaffolding for you to be able to run integration tests. Part of that scaffolding is automatic transaction management. This hooks into Zope's transaction API to roll back the transaction after each test runs. I wanted to do something similar for my Django test cases; I was finding 'state pollution' between my unit test runs, since data created by one test method isn't automatically cleaned out. Django's transaction handling is much simpler than Zope's: it cares only about the one database transaction that the current request has, and only if the transaction support middleware is installed. … -
Django Unit Tests and Transactions
Coming to automated testing in Django from the Zope and Plone world, I was pleased to find full support for all the testing machinery that I've become used to: regular Python unit tests, and doctests. Of course, these being unit tests, they don't do any 'framework' management out of the box. Unit tests are supposed to test your code, and just your code. However, once you're in a framework environment (be that Zope and Plone, Django, or anything else) then testing how your code integrates with that framework is vital. Zope and Plone provide unittest.TestCase subclasses (ZopeTestCase and PloneTestCase respectively) which provide a lot of scaffolding for you to be able to run integration tests. Part of that scaffolding is automatic transaction management. This hooks into Zope's transaction API to roll back the transaction after each test runs. I wanted to do something similar for my Django test cases; I was finding 'state pollution' between my unit test runs, since data created by one test method isn't automatically cleaned out. Django's transaction handling is much simpler than Zope's: it cares only about the one database transaction that the current request has, and only if the transaction support middleware is installed. … -
Plugging a RSS feed into a Django template
As some of you may have noticed, I've added my latest notes at byNotes in the sidebar. I wanted to do it in the template side, because I like to keep my views as clean as possible, so I wrote a template tag for fetching a RSS feed and displaying it. Here is the code: from datetime import datetime import time from django.core.cache import cache from django import template import feedparser register = template.Library() @register.filter def todatetime(value): return datetime(*time.localtime(time.mktime(value))[:6]) @register.tag def rssplug(parser, token): try: tag_name, address, template = token.split_contents() except ValueError: raise template.TemplateSyntaxError('%s tag requires 2 arguments' % token.split_contents()[0]) return RssPlugNode(address, template) def resolve(var_or_value, ctx): if var_or_value[0] == '"': return var_or_value[1:-1] return ctx.resolve_variable(var_or_value) class RssPlugNode(template.Node): def __init__(self, address, templ): self.address = address self.templ = templ def rss(self, addr): ckey = 'rssplug_%s' % addr data = cache.get(ckey) if data: return data data = feedparser.parse(addr) cache.set(ckey, data) return data def render(self, context): address = resolve(self.address, context) tmpl = resolve(self.templ, context) t = template.loader.get_template(tmpl) return ''.join([t.render(template.Context({ 'item': item })) for item in self.rss(address).entries]) As you can see, this tag uses a template for rendering every feed item, making it very flexible. You can output any information you want, as long as feedparser supports … -
Por: Juanjo
Creo que los dos enfoques tienen ventajas. -
Por: Gonzalo
¡Perdón! Confundí django-messages con django-notification, que no me gusta que la forma de usarlo sea inconsistente con la de una aplicación Django “normal” (qué se yo, pondría create_notice_type en un manager, y usaría get_or_create en vez del try/except que usa esa función), pero es solo gusto mío, nada para escandalizarse. Recién estuve viendo django-messages y ¡me parece genial! -
Por: Juanjo
Qué cositas? A mi, por ejemplo, me gustaría que se puedan mandar mensajes a muchos usuarios a la vez. No lo probé mucho aún como para encontrar otras cosas De todas formas, siempre se pueden enviar parches. -
Python and Django Setup for Mac OS X Leopard
Python and Django Setup for Mac OS X Leopard -
Por: Gonzalo
¡Qué bueno! No me gustan algunas cositas de esa aplicación en particular, pero es genial que se vayan traduciendo los ‘pluggables’ que hay para Django -
Edit Inline Support for Generic Relations
Introduction I've recently (past week or so) been digging into the newforms-admin branch of django. I am really looking forward to this code line getting merged into trunk as there are tons of great work in this branch. I especially like the separation of the admin code from the models. Well, I'll get to my point. The Problem I needed to be able to edit child records in the admin that were children through the use of GenericRelations. I was told about a solution on Google Code called django-genericadmin, but it seemed dead and I could not get it to work. The thing that seemed the closest to working was a patch on ticket 4667 by Honza Kral and a variation on this patch in the Django Snippet 765. Neither of these worked for r7771 of branches/newforms-admin. The Solution I put the 765 snippet in a file called generic.py in the root of the django project I was working on and fiddled with it until I got it working. I ended up needing to change an import, fix some variable names, and change the argument list order in one of the init methods. I also added the can_order and can_delete … -
Edit Inline Support for Generic Relations
Introduction I've recently (past week or so) been digging into the newforms-admin branch of django. I am really looking forward to this code line getting merged into trunk as there are tons of great work in this branch. I especially like the separation of the admin code from the models. Well, I'll get to my point. The Problem I needed to be able to edit child records in the admin that were children through the use of GenericRelations. I was told about a solution on Google Code called django-genericadmin, but it seemed dead and I could not get it to work. The thing that seemed the closest to working was a patch on ticket 4667 by Honza Kral and a variation on this patch in the Django Snippet 765. Neither of these worked for r7771 of branches/newforms-admin. The Solution I put the 765 snippet in a file called generic.py in the root of the django project I was working on and fiddled with it until I got it working. I ended up needing to change an import, fix some variable names, and change the argument list order in one of the init methods. I also added the can_order and can_delete … -
LaunchPad
I signed up with Launchpad today – don’t know why I hadn’t really done it earlier, other than I just didn’t think to or have any projects that drove me there. The project du jour that lured me in was … Continue reading → -
Reversed publishing with Django
>>> from django.core.template import * >>> c = Context( { 'ctnt': 'this is a test' } ) >>> t = Template( """ {{ ctnt|slice:"::-1" }} """ ) >>> t.render( c ) ' tset a si siht ' >>> badum-dum-chh. Post to Del.icio.us -
Introducing FRF, the Fiam's RSS Framework
I'm starting to notice a problematic pattern in Django: some components are not extensible at all. There's no problem when you are using it in the same way the framework developers intended, but when you want to do something which deviates from the Django standard, you're screwed. That's what happened to me yesterday. I wanted to add a RSS feed for public notes at byNotes, featuring GeoRSS information, but as far as I'm concerned Django Syndication Framework doesn't allow the framework user to define new fields. So I've choosen to write a simple but extensible RSS Framework. Each new field is a class, which can be plugged inside a channel or inside an item. In addition, I've also used a view-as-class approach without any templates, requiring the application feed class to return the field contents. However, every field also defines its own formatter, so the application feed class does not need to return the text, only the object the formatter expects (e.g, the pubDate field expects a datetime object, while the link field expects an URL). There are some things I like in the Django Syndication Framework, so I've kept them. For example, feeds can receive parameters via get_object() and … -
Immutable Django model fields
I wanted to make a field on a Django model read-only after it was assigned an initial value. Maybe I was having a slow day, or my Google-fu was especially lacking, but I couldn't find a documented way to do this. There's the editable Field option, but I wanted to ensure I couldn't mistakenly overwrite the initial value anywhere — not just in the admin interface or form processing. It turned out to be pretty easy. -
PyCon teraz w Polsce
Autorem poniższego tekstu jest Katharsis Rybnik pozazdrościł Pcimowi Pythona i organizuje po raz pierwszy polską edycję konferencji PyCon. PyCon PL, jedyna w Polsce konferencja poświęcona w całości językowi programowania Python odbędzie się w dniach 18-19 października 2008. Celem... -
Wersja 1.0 już niedługo!
Niedawno pojawiła się informacja, że już niedługo wyjdzie bardzo oczekiwana wersja 1.0 Django. Termin został ustalony na 2. września. Dokładna lista rzeczy, które będą dodane i te które zostaną być może dodane wraz z dokładnymi terminami znajduje się na stronie: VersionOneRoadmap