Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
CouchDB first impressions
I’m playing with CouchDB tonight. Some first thoughts, as they occur to me: The build process was very easy. I already had Erlang and all the standard automake/autoconf crap installed, so it was just a matter of installing something called icu and going from there. Something like 10 minutes from svn checkout to relaxing. Anything I can poke at with curl is pretty damn cool. Wow, I can just chuck arbitrary JSON objects up at this thing and it’ll store it. -
SQLAlchemy no Django com tranquil
Muitos programadores reclamam a falta de integração do Django com o SQLAlchemy. Há até um branch no projeto do Django para realizar essa integração, mas esse branch anda meio parado no momento.Em paralelo a isso foi criado um projeto chamado tranquil, que tem por objetivo integrar o SQLAlchemy no Django.As features mais legais desse projeto implementado até o momento são:Usar tables, objects e mapper objects do SQLAlchemy no DjangoManipular models do Django como se fossem objetos do SQLAchemyO projeto está no início ainda, mas será bem interessante quando for possível usar o Elixir no Django.O site do projeto é: http://code.google.com/p/tranquil/ -
Calling all (Django) programmers… (I need advice)
Update According to Max, it’s against Facebook’s TOS to cache the data. I’ve totally must’ve skipped over it in the TOS… ok, fine… I admit, I didn’t even read it. Thanks Max! And to think this response was less than an hour after my post! Yay, community. In any case, this problem is still relevant to many a graph-structured sites. Comment on! Since I don’t know of many techies in Hawaii, I figured I would post a blog in hopes of attracting a solution from the akamai Django community. The Background I’m currently writing a Facebook application in Django (which I’ll be blogging about later). The Problem I want to be able to programatically tell if you’ve updated your friends in Facebook. Basically, at the end of the day, Facebook provides an API call that allows you to retrieve a list of uid’s that represent your ‘friends’. I’m planning to cache this data within my own system. I was wondering how Pythonic people would solve the following: Is there a data type or algorithm (or combination thereof) I can use to compare the returned uids with my uid data cache? This comparison algorithm will tell me if you’ve added or … -
Getting started with WTForm
I found out that Clint mentioned the little pet project of mine on his weekly roundup of happenings in the Django world. So I thought this would be a great time to tell the world a bit more about the project, and do a little practical example for the readers. What does WTForm do? Basically, WTForm does the following: Widget and Field type as class names on field container div for easier CSS styling. (and a required indicator as well) Allows you to group your form fields and columns in fieldsets. Allows you to group your form fields and fieldsets in columns. (oh - the redunancy!) With regard to the last two points, WTForm allows for "infinite" nested structures. Enables you to insert arbitrary HTML snippets in the middle of your form. Project background The project was started as small hack when we (at GMTA) needed another output scheme (namely using div tags) and needed to allow for easier CSS styling using classes on every container div tag. The problem is that the "vanilla" newforms will output the form without any classes indicating whether the field is required or what kind of field we are working with. This resulted in … -
Lançado o e-book Diabetes na Prática Clínica
Ontem (8/10) foi o lançamento oficial do e-book "Diabetes na Prática Clínica". Esse e-book é um projeto pioneiro lançado pela Sociedade Brasileira de Diabetes para estimular a educação médica continuada.Toda a parte de programação e banco de dados projeto foi desenvolvido por mim, e eu utilizei o Django como ferramenta para o desenvolvimento. E o layout e desenvolvimento visual foi feito pelo Eduardo Frick.O mais interessante desse projeto foi a utilização do Django. Em todos os trabalhos que fiz em parceria com o Eduardo Frick sempre utilizamos PHP. Mas, como um bom pythonista e djanger, convenci o Eduardo a trabalharmos com Django nesse projeto e ele me deu seu voto de confiança.Essa escolha foi arriscada, mas eficaz! Com o Django foi possível solucionar problemas complexos de maneira simples e rápida.Nesse projeto eu usei e abusei do que mais gosto do Django: o newforms, ferramenta de serialização, template tags e template filters deixando de lado as generic views e o admin do Django. Fiz essa escolha pela necessidade de fazer um painel de administração bem específico.Usei também o Prototype para facilitar o trabalho com AJAX e Javascript.O resultado foi um sucesso e espero que vocês gostem! -
Including variables as templates
To manage the website content in a flexible way it's practical to have some portions of some pages generated from variables created as FlatPages. For example, in a frontpage I have a "featured item" section which renders a flatpage variable. def frontpage(request): fp = FlatPage.objects.get(url='featured') return render_to_response('frontpage.html', {'fp':fp }) then in the template ...<div id="featured">{{ fp.content }}</div> ... But sometimes it would also be nice to put some template tags inside those flatpages. Django does not seem to provide a tag for such task (most probably because it can be a bad idea from the security point of view), but the ssi tag does exactly the same thing for files in the filesystem. Based on ssi, the code bellow defines a new tag that includes the content of a variable as a template. def do_templatevar(parser, token): bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError, "%s tag takes one argument" % bits[0] return TemplateVarNode(parser.compile_filter(bits[1])) register.tag('templatevar', do_templatevar) class TemplateVarNode(Node): def __init__(self, content): self.content = content def render(self, context): content = self.content.resolve(context) try: t = Template(content) return t.render(context) except TemplateSyntaxError, e: if settings.DEBUG: return "[Included template had syntax error: %s]" % e else: return '' # Fail silently Now I can put … -
Displaying stars (with rounding) as a Django templatetag
Since my last post was quite popular (by my simple blogging standards), I’ve decided to post another Django snippet that I’ve used while coding WeGoEat. (I know, I know… one of these days I’ll finish. I’ve just been really, really lazy busy.) After reading Leah’s blog (of Pownce fame) about “rounding to the nearest half”, I was immediately struck by two sobering realities: I would need that exact same algorithm for my current site. A few years out of grad school, and I couldn’t even begin to fathom a solution. Thank you, Internet. In any case, I figured I’d wrap my solution into a template tag that people could use/steal/copy. Here’s a generated test page that illustrates what my template tag would display. You can even customize the display a bit: I know, I know… I can do a lot better. In any case, here’s the code snippet that I placed in a file called show_stars.py: import math from django.template import Library, Node, TemplateSyntaxError, VariableDoesNotExist, resolve_variable from django.conf import settings register = Library() IMG_TEMPLATE = '<img src="%s" alt="%s"/>' PATH_TO_WHOLE_STAR = IMG_TEMPLATE % (settings.MEDIA_URL + 'img/stars/star.png', "Whole Star") PATH_TO_THREE_QUARTER_STAR = IMG_TEMPLATE % (settings.MEDIA_URL + 'img/stars/three-quarter.png', "3/4 Star") … -
Django - Multiple Aliases for a Single Website
In these days of cheap domains, it's often desirable to own multiple domains for a single website. You've probably got each of the .com, .net and .org domain names, along with a country-specific domain. You want each of these to present exactly the same website to the world, but good … -
Django - Multiple Aliases for a Single Website
In these days of cheap domains, it's often desirable to own multiple domains for a single website. You've probably got each of the .com, .net and .org domain names, along with a country-specific domain. You want each of these to present exactly the same website to the world, but good design says that each web page should have one, and exactly one, URL. So what's the best way to serve this up without having an Apache config for each domain? I've come across this whilst building a website recently whereby the primary domain is mydomain.com.au, while I've got secondary domains in other popular TLD's to try and reduce domain squatting and the like. One option is to configure an Apache virtual host for each domain, which serves up a static redirect. Another is to have Apache aliases for the main host, so each of the domains serves up the same content. This works, but leaves each page with multiple URL's. My solution is to set up Apache aliases, and use a Django middleware to identify any requests that aren't for the main domain name, redirecting them as they're found. The middleware code I use is as follows: from django.http import … -
Django - A Diverse Community
Scott Barnham, one of the guys behind the recently-launched Django Gigs website, has posted some statistics from visitors to the Gigs website over the past few days. I've put together some similar stats for the Django Sites website, which has been online for a few months now. Note: All figures … -
Django - A Diverse Community
Scott Barnham, one of the guys behind the recently-launched Django Gigs website, has posted some statistics from visitors to the Gigs website over the past few days. I've put together some similar stats for the Django Sites website, which has been online for a few months now. Note: All figures are from Google Analytics, and percentages are rounded to make life easier. Summary 70% of our visitors are new, 30% are repeat-business. The average visitor views 5 pages, staying on the site for 3 minutes The most popular page, with 20% of page views, is the latest additions, followed by the listing of django-powered sites with source-code available at 5% of page views. Django Developers: newcomers to the community want to see source code! Operating Systems Windows 60% Linux 21% Macintosh 18% Others 1% The operating system split is very much skewed towards Windows, almost all of the Windows users on Windows XP. It's nice to see higher-than-average (compared to my other sites) usage of Linux & Macintosh. Browsers Firefox 66% Internet Explorer 16% Safari 7% Opera 5% Others 6% No surprises here. Firefox figures are very similar to the Gigs site, with Safari & IE being a bit different. … -
Django developers: We are the world
An informal survey of the Django community This week, Andrew and I launched the Django Gigs website to help employers find Django developers. Andrew wrote about it and thanks to the Django Community feed aggregator we had quite a few visitors in the first couple of days. It’s clear that Django is catching on and growing in popularity. The djangoproject.com site is getting close to 8 million hits each month. I thought it would be interesting to analyse my logs and see what I could tell about the Django community, or at least the section of it that read the blog and visited the Django Gigs website. Visitors 1280 unique IP addresses The number of IP addresses seems a pretty good indication of how many unique visitors we had in about two days. Platforms 510 Windows 373 Mac OS X (including 4 iPhones) 312 Linux 85 Other (mostly bots, feed aggregator sites, a handful of BSD) The platforms is a pretty even split among Windows, Mac and Linux. Which given the dominance of Windows on the desktop suggests Django is disproportionately popular with Mac OS X and Linux users. I suspect this is the case with Python in general, but … -
Media URL on javascript files
Using the MEDIA_URL setting in a template context variable is a very practical way to have the media files being served from a location defined in the settings file. James Bennett explains here how to define and use this context variable. But, for example, if I need to have media urls in my javascript files, which are static files, I don't have access to this variable. Take this very simple example. I have a image placeholder in the markup. <h1>Test 01</h1> <img id="placeholder" src=""> And the image url is set with javascript. function set_image() { var placeholder = document.getElementById("placeholder"); placeholder.setAttribute("src","http://localhost:8000/static/django.gif"); } window.onload = set_image In this case the full url is hardcoded which, of course is not what I want. Like for the other media files I want to use the above url during development and in deployment switch to the media server url. Something like: http://media.someserver.com/django.gif I discuss bellow the approaches I have been trying. Always use the media server urls in the javascript Just always using the media server url in the javascript files. It's simple and works fine if I don't need to change the static resources. But changing the static files during development becomes a problem. … -
Instalando Django com Apache e Mod_Python no Ubuntu
Um servidor com Apache rodando Django através de mod_python é uma das melhores escolhas para se fazer um deploy de uma aplicação feita em Django. Devido a isso resolvi fazer através deste post um simples passo a passo de como fazer a instalação e configuração desse deploy.Como no Ubuntu Python já vem instalado, é uma coisa a menos a se preocupar. Outra vantagem em usar o Ubuntu, ou qualquer distribuição baseada em Debian e a possibilidade de utilizar o apt-get para facilitar a instalação dos programas.Então vamos aos passos:1 - Instalando o Apache 2Para instalar o Apache 2 no Ubuntu basta abrir o terminal e digitar apenas um apt-get#sudo apt-get install apache2Para ver se o Apache foi instalado com sucesso e está em funcionamento é só acessar http://localhost em seu navegador.2 - Instalando mod_pythonPara instalar o mod_python no Ubuntu não é muito diferente#sudo apt-get libapache2-mod-python3 - Instalando o Django#sudo apt-get install python-django4 - Configurando o ApacheComo o mod_python foi instalado via apt-get, o módulo já fica habilitado automaticamente.Mas é necessário configurarmos nossa aplicação no Apache. Para isso temos que editar o http.conf da seguinte maneira:Para editar o http.conf, é só digitar esse comando no terminal:#sudo gedit /etc/apache2/http.confE adicionar as linhas … -
Boxes as template tags
With CSS it's very simple to do the markup of a square box. But to make those popular boxes with round corners most approaches use nested divs. For a flexible size box the following markup is typical: <div class="box"> <div class="box-outer"> <div class="box-inner"> <h2>Headline</h2> <p>Content</p> </div> </div> </div> It's a bad idea to repeat this code all over the templates. So a template tag can be a good option. The kind of template that would be interesting to have is one that outputs the boilerplate divs given the headline and the content. Something like: {% menubox "Box title here" %} <p>Content here</p> {% endmenubox %} Django makes the writing of this tag very easy and the documentation is very clear. Bellow is the result for such tag. from django.template import Library, Node, TemplateSyntaxError register = Library() def do_menubox(parser, token): nodelist = parser.parse(('endmenubox',)) parser.delete_first_token() try: tag_name, title = token.split_contents() except ValueError: raise TemplateSyntaxError, "%r tag requires exactly two arguments" % \ token.contents.split()[0] return MenuboxNode(nodelist, parser.compile_filter(title)) class MenuboxNode(Node): def __init__(self, nodelist, title): self.nodelist = nodelist self.title = title def render(self, context): title = self.title.resolve(context) output = self.nodelist.render(context) return '''<div class="box"><div class="box-outer"><div class="box-inner"><h2>%s</h2>%s</div></div></div>''' % (title, output) register.tag('menubox', do_menubox) Update: The tag now also … -
Como aprender Django
Na minha ida à PyCon Brasil [1], e as ajudas que dou a iniciantes em Django, percebi que muitas pessoas tem interesse em aprender Django, mas não sabem por onde começar. Para suprir esse problema resolvi criar este post mostrando um caminho de como aprender Django. Com certeza deve haver outros caminhos, mas resolvi escrever sobre o a maneira que no meu ponto de vista é ideal.Antes de aprender Django é necessário que você tenha pelo menos um conhecimento básico sobre Python. O Gabriel Falcão escreveu em seu blog um ótimo post mostrando como aprender Python [2].A primeira coisa que alguém que quer iniciar no Django deve fazer (após instalar o Django, é lógico!) é ler e praticar o tutorial oficial [3] do Django, que é dividido em 4 partes. O tutorial oficial abrange o básico sobre o framework, e após finalizar ele, você estará apto a criar pequenas aplicações com o Django. Mas lembre-se, é importante que siga o tutorial até o final! Se você seguir até a parte 2 ou 3 do tutorial, conseguirá fazer algumas coisas em Django, e por isso muitos não terminam o tutorial.Após terminar o tutorial, o importante é praticar e ir estudando a … -
Django Sprint - status
Nesse final de semana (dia 14, 15 e 16 de Setembro) teve o Django Sprint e o Django Sprint Brasil [1].No meu ponto de vista, tanto o Sprint mundial e o Sprint nacional foram um sucesso!No Sprint mundial muitos tickets foram filtrados, vários erros resolvidos, novos itens criados e algumas coisas que não eram documentadas no Django agora tem documentação. Como os shortcuts [2], form preview [3]. Para conferir algumas coisas que foram feitas é só verificas os tickets com a palavra chave: sprintsept14 [4].Eu tive uma humilde participação, sugerindo e criando um DataTimeInput, mas o aprendizado foi grande! Me interei mais no processo de colaboração do Django, como triagem de tickets, por exemplo.Já no Sprint nacional, um dos grandes resultados é o site do DjangoBrasil que em breve deve estar no ar. Várias issues relacionadas ao desenvolvimento do site foram solucionadas [5]. Também foi criada a página sobre Django no Wikipédia, melhorada a página sobre Django no PythonBrasil, e algumas traduções foram feitas.Todos que participaram estão de parabéns!!!!Quem não pode colaborar não fique triste pois o trabalho não para por aqui! O Sprint foi apenas uma maneira de motivar os djangers a se unirem e a melhorarem o Django, … -
Django Buildbot
Some very cool news – Django now has a public build site up (http://buildbot.djangoproject.com/)and running, matching the trunk and one of the branches against an assortment of versions of python and databases. Matt Croydon and I are going to be … Continue reading → -
Python and Java
I wondering if http://sourceforge.net/projects/pyjdbc/ can be used to let django use http://sequoia.continuent.org/HomePage as a way to scale up postgres Post to Del.icio.us -
Django Sprint
Amanhã, dia 14 de setembro (extendendo para todo ofinal de semana) ocorrerá um Django Sprint[1] pelo mundo todo. Ouseja, será um dia onde os djangers focalizarão sua atenção em melhoraro Django.Um dos objetivos do Sprint é unir as features que estão prontas nobranch do django com o projeto atual, como o newforms-admin,GeoDjango, suporte a multi-databases entre outras features. Outroobjetivo é resolver os tickets em aberto no sistema de tickets doDjango que chegam a mais de 1000 tickets em aberto.Se você quiser participar é só acompanhar e adicionar seu nome napágina do wiki[1]. São mais de 100 pessoas do mundo todo inscritas!Entre elas 9 são brasileiros!Aproveitando o gancho do Sprint Mundial, a comunidade de Django aquino Brasil resolveu fazer um Sprint também, iniciando no mesmo dia (14) e prolongando até o dia 16. Esse Sprint tem como objetivo resolveralgumas coisas relacionadas ao site do djangobrasil, a tradução doDjango, tradução da documentação e alistamento e organização de dois projetos: bingo[2] ( um cms ) e ajaxforms[3] ( newforms + ajax).Se você deseja participar, acesse a página da Sprint do DjangoBrasil[4] para obter maiores informações e assinar a lista depresença.Eu já me inscrevi no Sprint Mundial e marcarei presença no Sprint dodjangobrasil também!!!E … -
The sorry state of database journalism
I’ve been following with interest as Derek Willis explores Caspio, a sort of hosted data-driven web app tool for journalists. The following started out as a comment on his blog, but soon ballooned, so I’m posting it over here where it’ll have more space to breathe. Of course, for this to make any sense, you should read Derek’s articles first: Outsourcing Database Development, or the Caspio Issue (be sure to also read Caspio CEO David Milliron’s comments, too). -
Django Rapidinhas (1)
Ordenar model's randomicamente no DjangoEu resolvi fazer uma série de post's rápidos de dicas sobre Django. As 'Django Rapidinhas'.E o tema de hoje é ordenar model's randomincamente no Django. Para isso precisamos de um model de exemplo. Vamos criar um model que represente um Aluno de uma escola ou faculdade.class Aluno(models.Model): nome = models.CharField(max_lenght=40) idade = models.IntegerField()Para retornarmos em uma lista todos os usuários usando o ORM do Django usamos o método all(): >> Aluno.objects.all()Para ordenarmos essa lista usamos o método order_by, que necessita de um parâmetro informando o nome do campo que será a referência para a ordenação. Para um ordenação descendente adicionamos o '-' ao início do parâmetro e para uma ordenação ascendente não adicionamos nada, só o nome do campo basta. Ordenar por nome, de forma ascendente:>> Aluno.objects.all().order_by('nome') Ordenar por nome de forma descendente: >> Aluno.object.all().order_by('-nome') E para ordenar randomicamente? É difícil?A resposta é não. Pelo contrário. É muito fácil. É só passar uma interrogação (?) como parâmetro. >> Aluno.objects.all().order_by('?') Fácil não? -
More on the two column layout
More tweaks on the two column layout. In addition to using multiple columns to pull the comments up alongside the original posting, I can use the second column for a single prominent ad and a few navigational tools. This gives the ad a persistent spot on the page in a location that doesn't compete with the content, but maintains a certain amount of weight and commands some attention in so far as there is a little animation involved without it actually competing with the content. Part of me wants to put the comment form over there as well. You might also notice that the system is now making recommendations for additional articles based on a combination of the current article and past articles you've read. Ultimately, I'm going to have a mix of strategies that build a single list. Right now, there are content targeted entries and behaviorally targeted ones. I want to add featured articles that I select, articles deemed most popular by page viewing, and articles that match whatever search term last brought you to the site. I'll be presenting them separately until I understand a little better how each performs, but I hope to ultimately have a … -
PyConBrasil
Uma semana após o PyConBrasil resolvi me pronunciar sobre o evento!Para começar, levei aproximadamente 30 horas de viagem para chegar em Joinville! Na viagem estava muito ansioso, por não conhecer ninguém da comunidade pessoalmente e por nunca ter participado de um PyCon e por começar dando um treinamento de um Framework Web que está iniciando em um ambiente onde há muitos desenvolvedores que utilizam Zope/Plone.Meu primeiro contato com o pessoal, na Assembleia tirou todas essas baboseiras da minha cabeça.Aliás a melhor coisa que estou trazendo do evento são as amizades que fiz lá. Realmente estava lá uma comunidade. Muito bate papo entre uma palestra e outra e nas palestras também. Muitas piadas e brincadeiras nos Happy Hour. O humor do pessoal é enorme.No primeiro dia, eu participei dos dois treinamentos: sobre programação com python em celulares nokia e sobre Grok. Os dois treinamentos foram conceitos introdutórios, mas foram muitos importantes para conhecer um pouquinho sobre cada ferramenta. No final do primeiro dia fui avisado que teria uma mesa redonda sobre Python para Web e eu representaria o Django, Dorneles o Plone e Luciano Ramalho o Grok. Nós três tivemos a idéia de falarmos sobre cada ferramenta de forma divertida e … -
Digg-style pagination in Django
Since I’ve finally been picked up by the Django community aggregator (Thanks Jacob!), I figured I’d put out a little snippet for people to use/critique; hopefully more use than critique. I really, really liked the PaginatorTag on the Django Wiki, but I’ve always wanted my sites to have configurable Digg-like behavior; if you wanna know what I’m talking about, just check out how pagination works on Digg. Here’s how the PaginatorTag looks compared to the Digg-style tags. Like the PaginatorTag, this tag is a very basic inclusion tag that builds on the variables already set on the context when paginating with the generic object_list view. There are a few additional context variables created: page_numbers – a list of page numbers to display in_leading_range – boolean if the page is within the leading range in_trailing_range – boolean if the page is within the trailing range pages_outside_leading_range – a list of page numbers outside the leading range pages_outside_trailing_range – a list of page numbers outside the trailing range If you don’t understand what these are, don’t worry – I don’t remember either. I could’ve just appended what needed to be displayed in page_numbers, but instead, I broke it out into what needed …