Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Smuggler 0.1.1 released!
Yesterday I published the first stable version of Django Smuggler. An pluggable application for easily export/import fixtures via the administration interface. Especially useful for transporting data in production for the development project and vice versa, but can also be used as a backup tool. Smuggler is in the Python Package Index (PyPI) and you can easily install it using the tools pip or easy_install. Try: pip install django-smuggler or: easy_install django-smuggler Feedback (with or without code) is always welcome! -
Django Smuggler 0.1.1 lançado!
Ontem publiquei a primeira versão estável do Django Smuggler. Uma aplicação plugável para, de maneira simples, exportar/importar fixtures via a interface de administração. Útil principalmente para transportar dados do projeto em produção para o de desenvolvimento e vice-versa, mas também pode ser utilizado como ferramenta de backup. O Smuggler está disponível no Python Package Index (PyPI) e você pode instalá-lo facilmente via pip or easy_install. Experimente: pip install django-smuggler ou: easy_install django-smuggler Feedback (com ou sem código) é sempre muito bem-vindo! -
django-couchdb не взлетел
django-couchdb это ДБ бекэнд для Джанги с поддержкой CouchDB, разработанный командой 42cc. Начиная новый проект, я очень рассчитывал на это решение, но увы оно совсем не оправдало надежд. Основная цель была, используя CouchDB не отказываться от стандартной джанговской админки и попробовать её заставить работать при помощи это бекэнда. Любовь к админке обусловлена тем, что она уже написана и её не надо изобретать с квадратными колесами нам самим, то что наши контент-менеджеры уже отчасти привыкли к ней и не хочется сбивать им workflow. Авторы django-couchdb не скрывают что эта их реализация больше академическая и какого-то реального юзкейса у них не было. Что и проявилось в итоге. Сразу надо сказать, что на данный момент основная гитхабовская ветка не работает с текущей Джангой и свежим CouchDB. Это связано с тем, что в Джанге в последнее время серьезно переработали внутренний API бекэндов баз дынных, а новый CouchDB чуть более строг с структуре документов чем раньше. Но ладно, завести этот бекэнд вполне можно, что силами Кости Меренкова мы и сделали. Как и предполагалось, заработал базовый ORM, админка, а следовательно и приложения из contrib. Пожив какое-то время с таким решением, мы поняли, что во многих местах для нашей задачи оно избыточно, а в других просто неудобно … -
Pingdjack
Понадобился мне недавно pingback-сервер, и я, посмотрев на django-pingback, в приступе NIH-синдрома написал своё приложение -- pingdjack. За название спасибо Михаилу Лукьянченко. Отмазка Более-менее реальные претензии к django-pingback у меня тоже есть. Хотя я сразу признаюсь, что не пробовал во что бы то ни стало с ней ужиться, просто код почитал. Претензии такие: Зависит от django-xmlrpc, хотя на мой взгляд XML-RPC в Питоне и так достаточно простая вещь, чтобы не городить для неё Джанго-специфичного слоя. Использование обобщённого XML-RPC-слоя тянет за собой необходимость делать в нём регистрацию pingback-хендлеров или регистрировать middleware, которая будет делать это за вас. В качестве цели пинга регистрируются объекты моделей, а не любой произвольный URL сервера. У приложения есть свои модели, и как я понимаю, пингбеки оно хранит как само хочет, а не так, как мне надо. Библиотека не ищет цитату из поста и автора так, как мне давно хотелось. Pingdjack Получилась библиотечка из двух модулей: клиента и сервера. Единственная внешняя зависимость -- html5lib, без неё нынче никуда :-). Клиента я просто выдрал из Cicero. Он состоит из трёх функций: external_urls, которая ищет внешние ссылки в куске HTML'а ping, которая пингует один URL от имени другого ping_external_urls, которая соединяет одно с другим, пингуя все внешние ссылки из … -
Testing your first Django app
This is my unofficial part five for the Django tutorial. I've attempted to write this in a similar style to the Django documentation and hopefully this will be useful for those looking for the next step after the tutorial or trying out testing with django for the first time. Testing is something I think we can all do better, I certainly know I could do better testing my code sometimes. If you don't have the polls app from the end of part four and don't want to do it again you can grab it from my github. The code added in this tutorial is also available in the master branch of the repository. This tutorial begins where Tutorial 4 left off. We're continuing the Web-poll application and will focus on testing our application and proving that it works as expected. The testing environment Let's first look at how you run the tests, make sure you are in the mysite directory and run the command python manage.py test. You will see output similar to this: Creating test database... Creating table auth_permission Creating table auth_group Creating table auth_user Creating table auth_message Creating table django_admin_log Creating table django_content_type Creating table django_session Creating table … -
Testing your first Django app
This is my unofficial part five for the Django tutorial. I've attempted to write this in a similar style to the Django documentation and hopefully this will be useful for those looking for the next step after the tutorial or trying out testing with django for the first time. Testing is something I think we can all do better, I certainly know I could do better testing my code sometimes. If you don't have the polls app from the end of part four and don't want to do it again you can grab it from my github. The code added in this tutorial is also available in the master branch of the repository. This tutorial begins where Tutorial 4 left off. We're continuing the Web-poll application and will focus on testing our application and proving that it works as expected. The testing environment Let's first look at how you run the tests, make sure you are in the mysite directory and run the command python manage.py test. You will see output similar to this: Creating test database... Creating table auth_permission Creating table auth_group Creating table auth_user Creating table auth_message Creating table django_admin_log Creating table django_content_type Creating table django_session Creating table … -
Django Doc Wiki
I have been meaning to develop a simple Django-based wiki solution for a while. I prefer writing my notes and documentation in TextMate using Markdown, and keeping them in a public Git repo. However, I also need to share these files with other people every once in a while, and that’s why I wanted to be able to easily display this content in a wiki-like web site, without having to duplicate data. That’s how Django Doc Wiki was born today. I am aware that there are many other Python based wiki solutions out there. MoinMoinWiki seems like the most viable alternative, but it’s still too complex for my needs. Django-wikiapp looks like a useful app as well, but it doesn’t have any hooks for using it with a version control system outside the Django database. Django Doc Wiki is an extremely simple solution, but it works well for me, so I am going to open source it in the hope that other people might have a use for it as well. It comes with two main features: Detect new files in a directory (through a cron job, script included) and updates to existing ones, remove deleted files Support for Markdown … -
Sharding with Django on App Engine
When developing a scalable application for App Engine you need to pay attention to how often a database entity is updated because you can only update any single entity with a maximal frequency of 1-5 times per second. If the frequency of updates for any single entity is higher than this limit you can expect your application to have contention. In order to prevent such situations you can use a technique called sharding. Sharding takes advantage of the datastore's ability to handle many parallel updates on multiple distinct entities efficiently and to handle reads much faster than writes. Let's get to the example of a simple counter for which the frequency of updates is too high for a single entity (such a counter could be used for counting the number of views for a YouTube video): class SimpleCounterShard(models.Model): """Shards for the counter""" count = models.IntegerField(default=0) name = models.CharField(primary_key=True, max_length=500) NUM_SHARDS = 20 @classmethod def get_count(cls): """ Retrieve the value for a given sharded counter. """ total = 0 for counter in SimpleCounterShard.objects.all(): total += counter.count return total @classmethod @commit_locked def increment(cls): """ Increment the value for a given sharded counter. """ index = random.randint(0, SimpleCounterShard.NUM_SHARDS - 1) shard_name = 'shard' … -
Django Training in 2010
The new year's shaping up to be a great one for Django: Django 1.2 is on track to ship this March, and there's no doubt in my mind that it'll be the best release ever. Because of this, we expect to see a lot of new people wanting to learn Django next year, so we're stepping up our training offerings in the new year. This Friday, I'll be holding a one-day Django workshop in New York City. The class is mostly full, but a few spots are still available. This is the second in a series of workshops we've been holding in conjunction with HoldenWeb, and we plan to offer more (see below) In March, I'll be teaching a week-long advanced Django class in Kansas City. This class is perfect for folks who know Django but want to really learn all the ins and outs. We'll look at a whole bunch of advanced uses of Django, learn how to use optional add-ons like GeoDjango, Piston, Haystack, and even dig into the internals of Django a bit. We'll also spend a whole day setting up a real-world Django production environment and tuning it for performance. I'm really looking forward to this … -
OSError while installing Django with buildout and djangorecipe
A corrupted Django tarball can cause mysterious errors from djangorecipe. -
OSError while installing Django with buildout and djangorecipe
Sometimes, I see the following error when trying to run a Django buildout: File "/Users/dan/.eggs/djangorecipe-0.20-py2.6.egg/djangorecipe/recipe.py", line 271, in install_release os.listdir(extraction_dir)[0] OSError: [Errno 2] No such file or directory: '/Users/dan/.downloads/django-archive' After a bit of poking around, I found that this is to do with a corrupted Django tarball. In my case, this is usually because I've interrupted a download with Ctrl-C. Unfortunately it seems that the tarfile module in the Python standard library (at least as invoked by setuptools) treats broken a tar.gz files as an empty archive, without throwing an exception. Since there's no exception, djangorecipe assumes everything was uncompressed without problems, and is therefore rather surprised when the unpacked Django package isn't where it expected it to be. The short term solution is to delete the bad Django archive from your download cache. This will likely be a 'downloads' directory in your buildout, or you may have a global one (as I do). When you next run buildout, the tarball will be freshly downloaded. When I get a moment I'll see if I can modify djangorecipe to notice this condition and not proceed with the build. -
OSError while installing Django with buildout and djangorecipe
Sometimes, I see the following error when trying to run a Django buildout: File "/Users/dan/.eggs/djangorecipe-0.20-py2.6.egg/djangorecipe/recipe.py", line 271, in install_release os.listdir(extraction_dir)[0] OSError: [Errno 2] No such file or directory: '/Users/dan/.downloads/django-archive' After a bit of poking around, I found that this is to do with a corrupted Django tarball. In my case, this is usually because I've interrupted a download with Ctrl-C. Unfortunately it seems that the tarfile module in the Python standard library (at least as invoked by setuptools) treats broken a tar.gz files as an empty archive, without throwing an exception. Since there's no exception, djangorecipe assumes everything was uncompressed without problems, and is therefore rather surprised when the unpacked Django package isn't where it expected it to be. The short term solution is to delete the bad Django archive from your download cache. This will likely be a 'downloads' directory in your buildout, or you may have a global one (as I do). When you next run buildout, the tarball will be freshly downloaded. When I get a moment I'll see if I can modify djangorecipe to notice this condition and not proceed with the build. -
OSError while installing Django with buildout and djangorecipe
Sometimes, I see the following error when trying to run a Django buildout: File "/Users/dan/.eggs/djangorecipe-0.20-py2.6.egg/djangorecipe/recipe.py", line 271, in install_release os.listdir(extraction_dir)[0] OSError: [Errno 2] No such file or directory: '/Users/dan/.downloads/django-archive' After a bit of poking around, I found that this is to do with a corrupted Django tarball. In my case, this is usually because I've interrupted a download with Ctrl-C. Unfortunately it seems that the tarfile module in the Python standard library (at least as invoked by setuptools) treats broken a tar.gz files as an empty archive, without throwing an exception. Since there's no exception, djangorecipe assumes everything was uncompressed without problems, and is therefore rather surprised when the unpacked Django package isn't where it expected it to be. The short term solution is to delete the bad Django archive from your download cache. This will likely be a 'downloads' directory in your buildout, or you may have a global one (as I do). When you next run buildout, the tarball will be freshly downloaded. When I get a moment I'll see if I can modify djangorecipe to notice this condition and not proceed with the build. -
Learn something new every year
As developers, we all make that pledge, don't we? Some of us learn new languages, new frameworks, new APIs, new methodologies. Rarely do we learn a new operating system.30 years ago I was using whatever they called the operating system on the Apple ][ series of computers. 20 years ago I learned to use MS-DOS. 17 years ago I added Windows 3.1 to that mix. 15 years ago I ran into Windows 95 and the subsequent set of 98, 2000, Me, and XP. 10 years ago I started to play with Linux and Unix, mostly learning the simple shell commands needed to shuffle files around. 3 years ago I commenced working on Mac OS X. During my Windows 98 days I was forced in doing help desk and system administration work. I hated it. The pop-up menus were not intuitive. Documenting what you did was hence agony. I begged my job to make me a pure developer but they forced me to continue down the path of Windows administration. Eventually I left that job and became a pure developer.Over the years I got better at Unix and Linux. I even set up two servers for production use, one running Apache … -
Doing things with Django models – aka – Django models tutorial
Django abstracts most of the actions you would be doing with the Database. What it doesn’t abstracts, and doesn’t try to abstract is the Database modelling part. This is a quick tutorial describing to how model your data in Django models.py, and how to access and modify them. Consider a hypothetical HR department, which wants [...] Related posts:Django aggregation tutorial The Rails and Django models layer Rosseta stone Dynamic forms with Django -
WordPress and Django: best buddies
Summary: How to integrate a non Django database system in your Django code, using WordPress as example. The completed code is available at github or you can see some screnshots Though there are quite a few good Django blog applications, our blog is based on WordPress. A number of plugin’s make moving to a Django [...] Related posts:Doing things with Django forms Doing things with Django models – aka – Django models tutorial -
Self-referencing many-to-many through
How to implement self-referencing many-to-many relationships in Django. Example use cases are modeling asymmetrical following (a-la twitter) or symmetrical friendship (a-la facebook). -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Self-referencing many-to-many through
Django's ManyToMany through attribute allows you to describe relationships between objects. I've written a post about this - (Describing Relationships, Django's ManyToMany Through) - and so I won't cover here the details of its implementation or usage. What I want to talk about in this post is how to create ManyToMany relationships between objects of the same kind, and more than that, to show how those relationships can be described using through models. Asymmetrical Relationships - the Twitter model On twitter you follow people. Maybe some people follow you, but the relationships are all in one direction, asymmetrical. In Django you can implement this using a ManyToMany relationship. We don't need a special through model for this, but suppose we wanted to attach some metadata to those relationships. Below is sample code for a twitter-style database of people and their relationships with one another. The relationships carry a status column denoting whether a particular user is following another or blocking another: class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') … -
Django render_to_response
It is important to see how django doesn’t automatically appends the context variables to the request object. Say you want to access MEDIA_URL in your templates, using the following code will not work since the context is not created and it is not passed to the render_to_response function def my_view(request): return render_to_response('my_template.html', my_data_dictionary) The first [...] -
FireLogger per Python
Quan hom fa feina amb Django una de les primeres coses que aprèn és a mirar la consola del servidor de desenvolupament. Al la consola hi apareixen els missatges d'error i els logs bé en forma de prints o com a logs de Python. Convé evitar fer prints i fer servir els logs. Aprofitarem el funcionament del logger per tal de discrimitar els tipus de log i distingir entre els missatges que volem que es mostrin sols en depuració (DEBUG), errors o informatious. Una configuració molt bàsica del logs és la que propòs a projecte base d'appfusedjango, molt ràpidament: Al properties.py o al settings configuram el sistema de log 1 2 3 4 5import logging logging.basicConfig( format="%(asctime)s-%(levelname)s-%(name)s-%(lineno)s-%(message)s", level = logging.DEBUG, ) i a cada arxiu on el volguem fer servir 1 2import logging log = logging.getLogger(__name__) Això ens permte configurar a un sols lloc el nivell de log que volguem i a més saber des d'on s'estan generant els missatges. Com a retruc, a més ens servirà per poder mostrar els logs a la consola del Firebug gràcies a l'aplicació FireLogger. Aquesta aplicació té una instal·lació en dues parts, ja que hem d'instal·lar el plugin de Firefox que hi trobareu … -
Migrating to Django Mingus
I've migrated my blog from a creaking Plone 2.5 to a fork of Django Mingus. This is the process I went through. -
Migrating to Django Mingus
I've been running a blog since 2007 (check the archives!). At the time, it made most sense for me to go for a Plone-based blog. Plone was what I was most familiar with, and there was a simple blog product out there that I could use called, sensibly enough, SimpleBlog. In fact, you can still grab it - it's where you'd expect on the Plone Products section. And as you can see, the release there was the one that I used at the time - SimpleBlog 2.0, for Plone 2.5 Fast-forward to the start of 2010, and things have moved on. Plone's moved on, for sure. Plone 4 is just around the corner, and there's some really, really cool stuff in there: Dexterity, a new content types framework, finally looks like it'll make content type creation as easy as it should be, and simple types and behaviours can be created through the web. Deco, slated (last time I heard) for Plone 5, is quite literally going to make publishers wet themselves. And Deliverance has got great potential in helping to unify the many disparate systems which makes the typical corporate user's daily life such a grind. Thing is, I'm not …