Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
{% tree %}: деревья в Джанго-шаблонах
Буквально вчера ночью, вместо того, чтобы рисовать слайды для выступления на 404fest я как-то неожиданно написал кусок кода, который может кому-то ещё пригодиться. Это шаблонный тег и вспомогательный фильтр, которые умеют выводить в шаблон древовидные структуры в виде вложенных списков <ul> (вот таких, например). Несмотря на то, что изначально я написал его "неожиданно", потом долго сидел и боролся с не очень хотящей думать головой, чтобы на этот код не противно было смотреть. И я победил! Так что код теперь production-качества, что в переводе означает "уже один раз исправлялся". Тег {% tree %} На самом деле, в Джанге уже есть встроенное средство для вывода древовидных структур в список: фильтр "unordered_list". Но он не подошёл, потому что умеет выводить только строчки, а мне хочется в шаблоне как-то влиять на то, что лежит в отдельных <li>: ссылку сделать, дописать что-то. Поэтому я сделал тег, который работает так: {% tree some_list %} <a href="{{ item.get_absolute_url }}">{{ item }}</a> {% endtree %} Переменная "some_list" — структурированное дерево в том же формате, что принимает и "unordererd_list" (кому лень было ходить по ссылке, это вот такое: ['item 1', ['subitem 1', 'subitem 2'], 'item 2', 'item 3]). Между открывающим и закрывающим тегами находится микрошаблон, который используется для одиночного … -
Django Master Class, October 16
I’m pleased to announce that I’m teaming up with Steve Holden and Holden Web to teach a one-day Django Master Class. The class’ll be in Washington, DC on October 16th, 2009. I’ll be covering a grab-bag of advanced Django tricks, including AJAX, REST, schema migration, testing, caching, code quality, and more. Hopefully there’ll be something there for everything. For more info or to sign up, head on over to Holden Web -
Django 1.0 Template Development Review
Django 1.0 Template Development by Scott Newman actually surprised me in it's depth of covering the topic. I assumed it would be written with the absolute Django Template beginner in mind. While it is definitely an appropriate book for beginners, it also covers more advanced topics such as: Writing custom template tags and filters, Chapter 7 Covers pagination quite well in Chapter 8 Customizing the Django admin's look and feel in Chapter 9 And gives a good designer intro to caching in Chapter 10 This book should definitely be required reading for web designers that are looking to use Django. As someone who has read and re-read the wonderful Django Documentation many times this book does a great job of distilling all of that reference knowledge into book form. -
Contributor License Agreements
Mike Malone emailed me an interesting question, which I thought I’d answer publicly: [We’ve released code] under the BSD license. We want to accept patches from the community, but were wondering whether we need to get everyone who submits a patch to sign a release or something saying that their patch is BSD too. [Does Django] require everyone who submits a patch to sign that sort of release? The Right Way is to require that all contributors sign a contributor license agreement (CLA). -
Request for Comments: Auto-Installation of Apps in Django
The problem of pluggable Django apps Lately we’ve come across a bit of an issue with dependencies. We use pip and virtualenv for our projects and it works great for installing Python dependencies. However it is not so great if the dependency is a Django pluggable application. There is more you have to do: add all the dependent apps in INSTALLED_APPS and add the appropriate entry in your base urls.py. This can be a problem if you aren’t familiar with the app, let alone its dependent apps. Recently I used pip to test out what I thought was a stand-alone Django pluggable app, only to discover dependency after dependency. This isn’t very pluggable in my book. Proposal: A method of auto-installing apps The Django community has developed several patterns that make development easier. Many of them are related to how you configure the settings.py file for your project. See examples from Usware and this presentation from EuroDjangoCon. I’m proposing a new one, and would like assistance in refining it. A pluggable application would contain its own settings.py file containing one or more standard settings: APP_NAME, VERSION, and BASE_URL_CONF. In the project’s settings.py file, you would loop through one or more paths containing Django apps/Python packages. For each … -
Fabric factory
This is a project I have been working on recently after I spent a day to look at the existing solution to run periodically a test suite. Most of the project I look at were either difficult to setup or require to learn yet another specific domain specific language or had dependency on a larger software stack.As a reaction to this situation I have decided to see if I could write something simple that achieves gracefully this task. I also try to make it as easy to setup as possible. I have decided to use cpython as platform, django as web framework for the server and Fabric as library to automate the task execution.The result of this mix can be found on bitbucket in a project called Fabric Factory. This will eventually become a complete Job Server that could be used to distribute any kind of task scripted in Fabric.InstallationThis assumes that python is installed on your computer and that you have an internet conection.You can download the code using mercurial:* hg clone http://bitbucket.org/yml/fabric_factory/A fabfile will help you to quickly setup your environment.* fab quickstartNote : In order to run the command above you will need the latest version of … -
Evolution of an Auto-Complete
My latests hobby-project has been pushed live, in invite-only beta form. Previously known as Links Desktop, I have now dubbed it Loci Desktop, after the Loci Method. Auto-complete in Loci Desktop One feature of Loci Desktop is that it will auto-complete URLs when you add new icons to your ‘desktop’. Auto-complete is one of those features that users expect these days. They want the app to figure out what they want with as few key-presses as possible – and quite rightly so, typing is such a chore! The auto-complete system for Loci Desktop, in its initial state, was straight-forward to implement. The javascript and front-end was the most time-consuming part of the job, but the back-end Python code was trivial. Amoeba Alas, it was too slow to be practical. The list of URLs that I was auto-completing from came from a list of the top one million sites from Alexa.com, stored in MySQL and queried with the Django ORM. The query searched the urls for a substring, and sorted by the Alexa rank so the most popular sites were listed first. Although it worked perfectly, the auto-complete code at the back-end hammered the server and took to long to return … -
Evolution of an Auto-Complete
My latests hobby-project has been pushed live, in invite-only beta form. Previously known as Links Desktop, I have now dubbed it Loci Desktop, after the Loci Method. Auto-complete in Loci Desktop One feature of Loci Desktop is that it will auto-complete URLs when you add new icons to your ‘desktop’. Auto-complete is one of those features that users expect these days. They want the app to figure out what they want with as few key-presses as possible – and quite rightly so, typing is such a chore! The auto-complete system for Loci Desktop, in its initial state, was straight-forward to implement. The javascript and front-end was the most time-consuming part of the job, but the back-end Python code was trivial. Amoeba Alas, it was too slow to be practical. The list of URLs that I was auto-completing from came from a list of the top one million sites from Alexa.com, stored in MySQL and queried with the Django ORM. The query searched the urls for a substring, and sorted by the Alexa rank so the most popular sites were listed first. Although it worked perfectly, the auto-complete code at the back-end hammered the server and took to long to return … -
Evolution of an Auto-Complete
My latests hobby-project has been pushed live, in invite-only beta form. Previously known as Links Desktop, I have now dubbed it Loci Desktop, after the Loci Method. Auto-complete in Loci Desktop One feature of Loci Desktop is that it will auto-complete URLs when you add new icons to your ‘desktop’. Auto-complete is one of those features that users expect these days. They want the app to figure out what they want with as few key-presses as possible – and quite rightly so, typing is such a chore! The auto-complete system for Loci Desktop, in its initial state, was straight-forward to implement. The javascript and front-end was the most time-consuming part of the job, but the back-end Python code was trivial. Amoeba Alas, it was too slow to be practical. The list of URLs that I was auto-completing from came from a list of the top one million sites from Alexa.com, stored in MySQL and queried with the Django ORM. The query searched the urls for a substring, and sorted by the Alexa rank so the most popular sites were listed first. Although it worked perfectly, the auto-complete code at the back-end hammered the server and took to long to return … -
Early thoughts about Tornado, and what I might use it for
Today I tried out Tornado, the Python non-blocking web server optimized for speed & traffic. [Note: the confusing social media buzz around Tornado might make you think it includes social networking or twittering functionality. That's incorrect...just setting the record straight here.] Their chat demo seems pretty snappy, although I didn't see it under large loads or anything stressful. The long polling stuff is super-cool. You can start a request and leave it open for awhile, specifying a callback method to go to later. It's like ajax inside out and backwards. Testing out their framework...I like their blog demo. There's a Tornado-App Engine version, which I modified slightly to create a blog to keep track of my canvas experiments (totally unrelated, just killing two birds with one stone) Check it out: http://labs.fuzzyrainbow.com/graphicsexperiments/ [Note: if you're using Tornado with App Engine, you lose much of the functionality of Tornado that makes it interesting in the first place. WSGI doesn't support non-blocking requests. You'll want to use Tornado's own HTTP server.] Tornado comes with a really simple web framework along the lines of Google App Engine's "webapp" framework. I already like to use GAE+webapp for really simple projects, like basic API servers, and … -
Write your own ReStructuredText-Writer
Some time ago I decided to use ReStructuredText as the universal Format for nearly all content on my website. This includes not only all pages but also all blog entries like this one you are currently reading. Soon after I had implemented the Django backend for my website and started hacking together some HTML and CSS, I felt the need to manipulate the generated HTML from the docutils package. Don't get me wrong, theres nothing wrong with the HTML docutils created, but I'm a fan of very minimalistic but still semantic markup. Let me give you a few examples. While producing content for my website I make sure, that I only have one <h1> per page, which is the title of the page. Docutils creates the following HTML: <h1 class="title">Document Title</h1> But for me the extra class is redundant, because the h1 is unique on my pages. The output I want is: <h1>Document Title</h1> Doctils also wraps every section of the document into an extra div with an id to make it possible to provide anchor-links to specific sections. This is a nice-to-feature but I don't like it because it's not minimalistic, it creates to much extra-markup for me. Different … -
Facebook Connect - Django integration on filmaster.com
Integrating Facebook users with external website using Facebook Connect and Django -
Django: Testing Views
Although I usually begin writing tests for models, if I had to pick only one component to test I would pick The View. That is because testing views will give you the best coverage for a typical Django application. If your apps are not project specific you need to decouple tests from project particulars. While [...] -
Django and Google App Engine
Reading Jacob Kaplan-Moss's post Snakes on the Web my first thought was - why hasn't he mentioned Google App Engine? To be fair to Jacob, the GAE sdk when launched was pretty underwhelming but GAE is the ugly duckling that could very well grow into a swan. If Django is for 'perfectionists with deadlines' then GAE might be said to be for 'perfectionists with aspirations'. The growth of Django -
Произвести впечатление любой ценой
Вы когда-нибудь задумывались каким таким магическим образом джанговская админка сияет своим синим стилем в только что созданном проекте? Ведь одна из самых больших проблем у новичков в Джанге - это наладить отдачу статики в проекте, но её даже не надо настраивать чтобы правильно заработала админка! Это потрясающий маркетинговый ход - встроить глубоко во внутрь фреймворка костыль лишь для того, чтобы у человека, первый раз читающего и делающего туториал (или просто первый проект), уже на втором шаге случился культурный шок от админки, а точнее от её полу-магического появления и внешнего вида. Есть устоявшееся мнение, что у Джанги реальные проблемы с PR'ом и продвижением в массы. Что мол не кричат разработчики и члены сообщества, что вот она какая крутая и что всем надо ею пользоваться. Так у нас свой путь - не надо бить во все колокола, а лишь в нужных местах сгладить углы и сделать вхождение новых людей плавным и беззаботным. Благими намерениями - дорога в ад! Проза в том, что медиа админки в runserver хендлится специальной WSGI мидлвариной. Причем даже в основном хендлере есть проверка на наличие в урле префикса медии админки и подавлении нотификации о запросе в консоле - чтобы не пугало неподготовленное сознание!:-) Всё это чревато, т.к. кто-то … -
South 0.6.1
South 0.6.1 is now available for public consumption; it fixes quite a few bugs.If you want to see what's been fixed, have a gander at the Release Notes - there's a few significant bugs that have been fixed, including problems with SQLite, GeoDjango, and M2M fields.Sorry for the short but sweet post - I'm in the process of writing my talk for DjangoCon! I'm giving a talk about South, with both a good grounding for those who haven't grokked migrations yet, as well as some tips on more advanced usage. Come watch it on Tuesday morning! -
Snakes on the Web
A talk given at PyCon Argentina and PyCon Brazil, 2009. Web development sucks. It’s true: web development, at its worst, is difficult, repetitive, and boring. The tools we have suck. At best, they make web development slightly less painful, but we’re a long way from making web development awesome. The history of web development tools is a history of trying to solve this problem. It’s a history of asking, “how can we make this suck less? -
First things to do on a Django project...
Call them best practices if you like, but here's the things I do when starting a new Django project. -
zoe.vc is back
Finally we made it to the new server. Unfortunatly all special characters are broken, but I'll fix that later. And hopefully I'll have same time to post new content -
Django ... an outlier
While analyzing the development activity and code metrics for over 240 of the most actively developed FLOSS projects, guess which project popped out? Yes Django! Its an outlier in terms of its activity. It’s influencing the results of my statistical analysis more than any other project as per the Cook’s distance diagnostic index. Let me bring your attention to the lonely dot that is close to the value 1 at the top right corner. I missed it at first, but noticed it when I looked at the sorted values. This is telling us that at least among the sample that I have ,Python, C and C++ based actively developed FLOSS projects, Django (including its community) is quite unique. I leave you with the graph of sorted Cook’s D values from my analysis: Click to Enlarge Image -
Formulários elegantes com Django
Não poupo críticas ao Django, este excelente framework em Python tem me ajudado a concluir todos meus projetos relacionados a web, se tornou o padrão de desenvolvimento da Trianguli, empresa onde trabalho. O lema do Django “The web framework for perfectionists with deadlines” faz muito sentido e tem auxiliado muito a Trianguli a cumprir seus deveres para com seus clientes. Confesso que nunca gostei muito dos módulos de formulários (forms) do Django, sempre optei em fazer meu formulários na mão para adapta-los melhor ao layout e não correr riscos de ter algum resultado inesperado de layout, mas os formulários são uma mão na roda para validação e até melhorar a segurança do site. Outro dia estava realizando uma pesquisa rotineira e acabei encontrando o Uni-Form, um conjunto de CSS e JavaScript (depende do jQuery) que cria formulários de uma maneira mais elegante, incluindo sua validação. O Uni-Form é altamente personalizável e seu código está muito bem elaborado e validado via W3C. Pesquisando mais um pouco, encontrei o django-uni-form, que faz a integração do Uni-Form ao Django, permitindo seu uso rapidamente em um projeto Django existente, com poucas modificações no código. O django-uni-form pode substituir o modelo de formulários do Django … -
A Civilized Way Display Lots Of Data
Django is a civilized way to build web applications. Pagination is a civilized way to display lots of data. There are still people developing websites with tens of thousands of items crammed in a single page. Even if you use JavaScript to paginate client-side, never ending download results in poor user experience. Django has pagination [...] -
Primeros pasos con geodjango
Este es un minitutorial "expreso" para probar geodjango en debian testing con postgres 8.3, postgis y django 1.1Pues lo primero es instalar los "juguetes":$ apt-get install postgis postgresql-8.3 postgresql-plpython-8.3 $ apt-get install python2.5 python-psycopg2 python-django ipython $ apt-get install gdal-bin python-gdal Ahora debemos configurar un poco postgres asi:Debemos volvernos root y luego el usuario postgres$ su $ su postrgres$ psql template1Este úlrimo comando nos conecta a postgres como el usuario postgres (el root del servidor de bases de datos), luego configuramos una plantilla para postigs (esto lo hacemos una sola vez)template1=# ALTER USER postgres WITH PASSWORD 'postgres';ALTER ROLETemplate1=# \qLuego:$ cd /tmp$ wget http://geodjango.org/docs/create_template_postgis-debian.sh$ bash create_template_postgis-debian.shEsto nos crea la plantilla template_postgis, ahora volvemos a postgres: $ createdb -T template_postgis geodjangoSalimos de postgres y del usuario root.Ahora creamos un projecto y la app:$ djano-admin startproject geodjango$ cd geodjango$ python manage.py startapp world Luego editamos el settings de nuestro proyecto con el editor de nuestra preferencia (sugerencia rapida gedit)$ gedit settings.py &Dejamos las siguientes variables así DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'geodjango' # Or path to database file if using sqlite3.DATABASE_USER = 'postgres' # Not used with sqlite3.DATABASE_PASSWORD = 'postgres' # Not used with sqlite3.DATABASE_HOST = 'localhost'LANGUAGE_CODE = 'es'INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', … -
Probably Site Downtime
Howdy! As I'm moving the domain to a new server these days it could be possible that zoe.vc isn't reachable for some hours or even days. So don't be confused - everything will be alright after the movement is finished. Comments are disabled meanwhile. Thanks for your understanding! -
Annoying things about Django
Annoying things about Django