Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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 … -
Django on Jython
It's on! Leo writes about his experience porting Django to Jython and there's a thread on the django-developers group too. Funny how things seem to click for a bunch of people all at once - the release of Jython 2.2 seemingly the catalyst. For my part I've been working on porting sections of Django to Jython on and off for a couple of weeks. Whilst Java is great for paying the bills, developing web applications with it is pretty slow (by comparison). My stack from bottom up looks something like this MSSQL -> {Spring: [Hibernate , Service tier]} -> Web framework. Yes, it's Enterprisey in the pejorative sense! ;) One of the web frameworks is actually Flex Data Services, which is great for RIAs but terrible where you want to bang together a quick admin app. I figured the architectural gaps between Velocity templates and the enterprise business tier I mentioned above could be filled very nicely with parts of Django, such as New Forms: Where Leo adopts a more holistic approach outside of the container, I've been fiddling around with the appealing concept of Django MVC as Struts 3.0!! Lessons Today, Django in Jython not only involves not only … -
Texas Python Regional Unconference
Just a quick announcement for all the Houston and surrounding area Python lovers out there. There is a Texas Python Regional Unconference being held in a couple weeks (Sept. 15 – 16) at the University of Houston main campus. Registration is free and as simple as adding your name to the registration wiki page. I’ll [...] -
Django vs feedparser on dates
I'm having trouble storing feedparser results in a Django model. It's all about timestamps. Feedparser returns timestamps in a standard time nine-tuple, asserting UTC. Django wants datetime objects. So, I'm trying to translate: django_timestamp = datetime.datetime.fromtimestamp(time.mktime(feedparser_timestamp)) feedparser_timestamp = django_timestamp.utctimetuple() This works fine for the majority of timestamps, but sometimes translating to datetime and back mutates the timestamp. In turn, that makes get-if-modified-since somewhat unreliable. Here are some examples, from my log file: WARNING: (2004, 11, 19, 5, 13, 31, 4, 324, 0) => datetime.datetime(2004, 11, 19, 6, 13, 31) => (2004, 11, 19, 6, 13, 31, 4, 324, 0) WARNING: (2005, 11, 2, 2, 17, 55, 2, 306, 0) => datetime.datetime(2005, 11, 2, 3, 17, 55) => (2005, 11, 2, 3, 17, 55, 2, 306, 0) WARNING: (2006, 12, 13, 0, 21, 25, 2, 347, 0) => datetime.datetime(2006, 12, 13, 1, 21, 25) => (2006, 12, 13, 1, 21, 25, 2, 347, 0) WARNING: (2004, 11, 14, 23, 55, 31, 6, 319, 0) => datetime.datetime(2004, 11, 15, 0, 55, 31) => (2004, 11, 15, 0, 55, 31, 0, 320, 0) I'm off by an hour. I smell a problem with daylight savings. I just wish I knew what to do … -
My "personal security" plan
My personal security plan Prompted by recent reading on cryptography and computer security, I’ve been rethinking my pretty lax personal security plan. Right now I’m doing a number of pretty stupid things, including reusing just a couple passwords (“high” and “low” security), using browser/keychain password remembering too much, and storing important documents (tax returns, etc.) unencrypted. A co-worker just had his laptop stolen, and I’ve realized just how screwed I could be if that happens to me. -
Of Meta Tags and Context Processors
We just launched a site that required heavy utilization of <meta> tags. The most demanding aspect of this process was ... -
Edit inline with ImageField or FileField in Django admin
Django admin lets you edit related model objects “inline”. For example when editing a Recipe you can add/eding a group of Ingredient models. Core fields for edit_inline The related model being edited inline must specify one or more “core” fields using core=True. If the core fields are filled in, the related model is added. If the core fields are empty, the related model is removed. This works great for normal objects with CharFields, etc, but not so well if you want to have images or files uploaded using inline editing. If the only core field is a FileField or ImageField, you’ll get strange behaviour like the file/image being removed when you edit an existing model in the admin. Using inline editing with ImageField or FileField In a recent project I wanted to have an item with title and description and zero or more photos. The Photo model just has an ImageField. To make it easy to edit, I wanted the photos set to edit_inline. Here’s my first attempt: class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() class Admin: pass class Photo(models.Model): item = models.ForeignKey(Item, related_name='photos', edit_inline=models.STACKED) image = models.ImageField(blank=False, upload_to='items', core=True) Notice that the ImageField in Photo has core=True to … -
iPhone says Welcome to Django
-
iPhone says Welcome to Django
-
Custom Python installation for Django on Dreamhost
Now that my MBA class is finally done for the summer, I can focus on more important things… like upgrading my Python installation on Dreamhost for my Django application. Seeing as how Dreamhost is still behind the Python times, with Python 2.4 hidden in Dreamhost obscurity, I figured I’d blog about updating your Dreamhost Python installation (and subsequent MySQLdb libraries) to Python 2.5. The very first thing I did was search Google. You know, I really don’t know how people lived pre-Googs. In any case, I found this blog posting describing exactly what I wanted to do. Thanks Ben! Since I’m not a big fan of running one large batch script people create in their blogs, I’ll break it down for the non-*nix fans out there. Before I begin, I’m assuming that you already have Django running on Dreamhost. If you’re having a “wtf” moment, make sure to stop by Jeff’s blog and read “Setting up Django on Dreamhost“. (This is how I set mine up). To follow my short tutorial, you’ll need shell access to your Dreamhost account. After ssh’ing into your Dreamhost account, you should be in your home directory (/home/username). According to the Filesystem Hierarchy Standard, the … -
Permalink decorator pt. 2
Since writing briefly about Django's permalink decorator I've had quite a few emails regarding the use of the permalink decorator and generic views. Here is what works for me... I often have the following urlconf in urls.py: urlpatterns = patterns('django.views.generic.date_based', (r'^(?P<year>d{4})/(?P<month>d{1,2})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, month_format='%m')), ) And the corresponding get_absolute_url method cut straight from my class looks like this: @permalink def get_absolute_url(self): """ return absolute url of this object """ #pylint: disable-msg=E1101 return ('django.views.generic.date_based.object_detail', None, { 'year': self.create_date.year, 'month': self.create_date.strftime('%m'), 'day': self.create_date.strftime('%d'), 'slug': self.slug}) This is already well documented here and here, but I hope this extra example helps. Note: For completeness, I use Eclipse with Emacs key bindings and the Pydev plug-in with pylint activated - hence the pylint ignore directive. Posted by Cam on Mon, 20 Aug 2007 13:47:02 +1000 -
Mixing OpenID into Django's authentication system
NOTE: This code is now outdated, and it's certainly not the best way to do OpenID in Django. I recommend you take a look at django-authopenid, a fantastic registration system that combines Django's authentication framework with OpenID sign-in. Ross, 17th April 2008 According to the OpenID website, from a consumers point of view OpenID is "the elimination of multiple user names and passwords and a smoother, more secure, online experience. ". What it provides is a single identity for you to use at multiple websites. Instead of having a username and password for each website you peruse, you have an identity (usually a URL to your blog or an OpenID provider) that you use to login. The only password you have to remember is that of your OpenID provider - and you don't have to provide your password to any websites you visit. Simon Willison has been a fantastic campaigner for OpenID, especially for integration with Django. He's written the fantastic django-openidconsumer package which provides the framework for a Django Application to act as an OpenID consumer (that is, people login to your Django app using their OpenID). Simon's package creates a new OpenID object within your application, but is …