Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
URL Pet Peeves
One of the best features of Django is the clean URL structure. The following is an example of what could ... -
Building My Django Weblog: Part 5
The time came for me to start thinking about where to host my site. And although I have some experience with using dreamhost to host sites, I wasn't particularly thrilled with that idea. Instead, I started thinking about using a VPS. That would allow me to use gentoo linux as my hosting environment, and it meant that I wouldn't have to hack around and do clever things just to run django behind apache and mod_python. Added to that, regular hosting is about 10 US dollars a month, while a VPS is about 20 a month. I decided to go with VPS Land because they offered the best price point for the feature list. And they've proved to be an excellent provider in all the time I'd been with them. (I switched out to linode simply because a friend of mine is there, and I have to represent and keep it real). Anyway, after upgrading gentoo and installing django on my VPS it was time to start opening up the testing to other people to get their feedback on various features. One of those features was the look of the site. Since I'd already decided on a layout, it was time … -
Building My Django Weblog: Part 4
In one of my earliest blog posts, I wished my sister a happy birthday. Today is exactly two years since, so Happy Birthday to Sindhu :) Edit: My sincerest apologies to all your feed readers -- my blog programming skills are not good enough, apparently, to keep drafts from getting published. I thought I'd fixed the problem this morning, before getting on the plane in San Jose to return Boston, but apparently not. I don't think I even fixed the feed, so I'm not entirely sure what it was I fixed. In any case, my humblest apologies to everyone for the inconvenience caused. I hope it doesn't put you off my blog. It definitely shows how much I have yet to learn. I like to get my news from reddit usually. The nice thing about reddit is that there tends to be a variety of stories, and every so often you get a gem of an article about CSS. So, for example, you get a menu of css techniques, or you find out about Yahoo's javascript and CSS library--yui, and reading these open up possibilities. So, I've never delved into web-two-point-oh stuff yet. The last line of Javascript I ever … -
O MVC, o MTV e o Django
Como muitos sabem, MVC ( Model – View – Controller ) é um padrão de desenvolvimento, que é um padrão que separa o desenvolvimento nessas 3 camadas. Model – nessa camada é implementada o banco de dados ou o modelo objeto-relacional. Controller – nessa camada é implementado as regras de negocio, onde são processados os dados vindo camada Model e passados para a camada View. View – nessa camada é onde fica a interface do sistema. O MVC é muito utilizado nos dias de hoje e tem agradado a muitos desenvolvedores para web por separar a parte de programação de dados da parte da programação visual de um sistema feito para web, onde geralmente essas partes de um sistema são feitos por pessoas diferentes. Em conseqüência ao aceitamento desse padrão pela comunidade, surgiram muitos frameworks que implementam esse padrão como o Ruby on Rails, Struts, Mentawai, TurboGears, Django entre muitos outros.Como citado acima o desenvolvimento usando o django é feito de acordo com o MVC separado nessas 3 camadas. Até ai tudo perfeito, mas há um problema. Qual problema? O django usa as nomenclaturas para as camadas,diferente do modelo MVC. Para modelo o django usa model, para view ele usa … -
Building my Django Weblog: Part 3
One day, while searching for something Django related, I ran into a really nicely done Django weblog. What caught my attention here, is that he came up with a way to spiffy up his comments display by showing a country flag for each commenter. It looks really spiffy. So I decided to play copycat. Well, it only took a few minutes to implement it in the testing version of my own blog, and I showed it off to a couple of my friends in IRC. One of them, tjfontaine, said something along the lines of "oh neat, libgeoip." Obviously, I hadn't seen or heard of this libgeoip thing so I asked him about it and he linked me to it. Now this was interesting, because it comes with python bindings. And the best part, of course, is that it is in portage. So I installed it, and had a look at their usage sample. Essentially, you just download their ip to country map, which they update once a month, and so you don't have to hit their servers everytime you do a lookup. Next up, I wrote the templatetag to use GeoIP. In its entirety, it looks like this: from … -
Building my Django Weblog: Part 2
Up until a few days ago, my Django blog application was violating DRY. Well, let's be honest, it probably still is, but this one was a blatant violation. What happened was that I wanted to be able to add users to my system without necessarily having them listed as bloggers, since I'm hoping to provide, in the future, gallery, mail and other miscellaneous services to the extended Kulleen clan. To solve that I created a Person class which had a foreign key into Django's own user class, plus some extra fields. Two of those fields were first_name and last_name, so that meant that for each blogger, I had to enter their names twice. Silliness, I tell you! Now, I'd read James' article about extending the User model late last year, during the early stages of my django learnings. And to be honest, I didn't really understand the implications. All of a sudden, two days ago, it hit me! So, I made a few changes to my blog to make use of that technique. My code went from this: class Person( models.Model ): first_name = models.CharField (maxlength = 100) last_name = models.CharField (maxlength = 100) user = models.ForeignKey ( User, verbose_name="Associated … -
Django Registration for Newbies
I recently turned my attention to user account management in Django and what follows are (cleaned-up) notes I made while exploring the django-registration contribution. As a result, this post is very introductory and task oriented, but hopefully, it will help orient newcomers like me to what's available and provide a foundation for exploring these topics in more depth. -
A Quick Note About my Feeds and Blogs
Hi Everyone, I've just finished rebuilding the feeds on this site, and I thought I'd let you all know of some changes. The feeds I put in place when the website launched are still active and will continue to be for a while (for your convenience). However, the links to those feeds are no longer being advertised. I have switched the url layouts now to be hopefully a little more consistent and a little more intuitive. The story is is basically this: any link under the "Weblogs" link will have an associated feed, accessible by appending "/rss/" or "/atom/" to the end of the URL. The feeds page explains this with examples. The available types of feeds are: the entire blog the entire per-person blog the entire tagged blog per-person tagged blog comments for a specific blog I've added feed icons on all the relevant pages so as to make it more accessible. Additionally, you'll notice the introduction of a new blogger: my sister. She'll start blogging some time soon, hopefully. So, now, while the tag cloud situation still remains, the tags will at least link to the specific blogger (and give you a 404 if that blogger hasn't made … -
Building My Django Weblog
For quite a few months, I'd been wanting to build my own weblog. You might recall that I had started using Django to code up my ex-employer's websites. Well, that was a fantastic experience, educationally, because I got exposed to a really great framework. As part of that effort, I rebuilt their rather simple blog (which was -- and probably still is -- hosted at Typepad, leaving the website interface a little klunkily inconsistent) Anyway, Aimee and I started talking about having our own web space. Otherwise, her blog and my blog would be hosted in separate neighborhoods on the web, which does nobody any good, really. So, I decided to take the code I'd written up for StreamBase and use it for my own site. Along the way, I kept reading James' blog especially the bits about generic views and application/project layout and, of course, hacking the FreeComment model. In the #django channel, bitprophet would teach me how to wrap generic views and do other tricky (for me!) things. Meanwhile Colin (Magus-) would help me with basic Django things that everyone should know, but I didn't. So, I started hacking away at it. Every day, I would upload a … -
Django serialization.
Bastante usado em unittest e doctests.wiliam@wiliam:~/dev/myapp$ python manage.py shell>>> from myapp.purchase.models import Country>>> from django.core import serializers>>> f = open('countries.json', 'w')>>> data = serializers.serialize("json", Country.objects.all())>>> f.write(data)>>> f.close()Você pode carregar manualmente usando python manage.py loaddata:wiliam@wiliam:~/dev/myapp$ python manage.py loaddata fixtures/countries.jsonLoading 'fixtures/countries' fixtures...Installing json fixture 'fixtures/countries' from absolute path.Installed 242 object(s) from 1 fixture(s) -
django queryset weirdness
I needed to reset the django admin password and found this page which tells us how to do this. It did not work for me, however I tried to get the user object explicitly, reset the password and save it and it worked! Here is a session describing the behavior: > python manage.py shell In [1]: from django.contrib.auth.models import User In [2]: u=User.objects.all() In [3]: u[0].password Out[3]: 'sha1$0913d$6c5cfefb89b3c77dc8573e466a943c7acd177f6b' In [9]: u[0].set_password('testme') In [10]: u[0].save() In [11]: u[0].password Out[11]: 'sha1$0913d$6c5cfefb89b3c77dc8573e466a943c7acd177f6b' In [12]: q=User.objects.get(id=1) In [13]: q Out[13]: <user : root> In [14]: q.set_password('testme') In [15]: q.save() In [16]: q.password Out[16]: 'sha1$24e9c$868ff39f08c3bde96397e33ea6a8847a658a16bc' Maybe this is related to queryset caching, which would print the same password even after calling set_password. But it looks like in the first method, the password does not even get written to the database. This might be a bug. I will need to run more tests and report (or possibly patch) it... Update: Perhaps I am not clear in the above post. The weirdness is that in the above two scenarios u[0] and q should essentially reference the same user object, but calling set_password (and later save) method on the u[0] reference does not seem to work (i.e. the … -
First Post at the New Website
Welcome, everyone, to my new home on the web. I've built this site using django, with tonnes of help from all sorts of people. I've listed them on the about page for now. As this website gets fleshed out, I'll add more details. So, I'll be blogging here from now on, and not on planet gentoo any longer. I think the planet will be syndicating this feed for a while, though. Please do have a look around, and find me all the bugs you can find. Since this website is very much a work in progress, there will be several improvements over the next few weeks and months. So, I'll talk quickly about some of the design aspects of this site. Wherever possible, I've tried to output valid XHTML 1.0 code. If you find something invalid, please leave me a comment below. I've input all the posts and comments from Planet Gentoo here, so everyone who's ever chatted with me on that blog has their conversation carried over to here. In the next few posts, I'll go into more detail about this site, including the django backend code, the colours, the stylesheets, and artwork (yes, that includes the logo, which … -
django-restful-model-views contribution update
I've updated the django-restful-model-views contribution, based on feedback I've received, primarily to make this a more generic REST API (not just model based). This update also begins implementing some ideas borrowed from Ruby on Rails. -
Ticket #3882 (closed: fixed)
Já está disponível na versão de desenvolvimento do Django o localflavor BR.Ticket: #3882Changeset 4874 e 4908 -
django.contrib.localflavor.br
Primeira versão implementada, agora vem os teste."""BR-specific Form helpers"""from django.newforms import ValidationErrorfrom django.newforms.fields import Field, RegexField, Select, EMPTY_VALUESfrom django.newforms.util import smart_unicodefrom django.utils.translation import gettextimport rephone_digits_re = re.compile(r'^(\d{2})[-\.]?(\d{4})[-\.]?(\d{4})$')class BRZipCodeField(RegexField):..def __init__(self, *args, **kwargs): ....super(BRZipCodeField, self).__init__(r'^\d{5}-\d{3}$',....max_length=None, min_length=None,....error_message=gettext(u'Enter a zip code in the format XXXXX-XXX.'),....*args, **kwargs)class BRPhoneNumberField(Field):..def clean(self, value): ....super(BRPhoneNumberField, self).clean(value)....if value in EMPTY_VALUES:......return u''....value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))....m = phone_digits_re.search(value)....if m:......return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))....raise ValidationError(u'Phone numbers must be in XX-XXXX-XXXX format.')class BRStateSelect(Select):.."""..A Select widget that uses a list of brazilian states/territories..as its choices..."""..def __init__(self, attrs=None):....from br_states import STATE_CHOICES # relative import....super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES)Coisas pra resolver:>>> from django.contrib.localflavor.br.forms import BRZipCodeField, BRPhoneNumberField, BRStateField, BRStateSelect>>> from django import newforms as forms>>> class BRForms(forms.Form):... zipcode = BRZipCodeField()... phone = BRPhoneNumberField()... statef = BRStateField()... statec = forms.ChoiceField(widget=BRStateSelect)...>>> brf = BRForms()>>> print brf.as_table()...>>>>O widget BRStateSelect ainda não é renderizado corretamente, isso acontece com os fields que tem Select como classe base. A solução que vem sendo adotada usa o método __init__, que nesse caso não fica elegante pois teríamos que importa STATE_CHOICES de br_states.py. Bom o tempo está apertado, tenho que ir, aqui tem um exemplo de como usar o __init__, a única diferença e que os dados vem da banco de dados. -
Displaying High Resolution Images on the Web with Zoomifyer.
I recently wrote an article, due to be published in this month's Information Technologies and Libraries (ITAL) journal, about a project I started a few years ago called Zoomify Image. Basically, Zoomifyer is a Flash based image viewer that allows you to quickly view high resolution images over the Web. And I mean really high resolution images--files Gigabytes in size. It can do this because of a second piece of software that pre-processes images on the server, splitting them into tiles at various scales that the Zoomifyer viewer can then asynchronously request as needed to render the image in the browser. Zoomify Image is written in Python and makes Zoomifyer available across platforms. -
CZ | Django 0.96
Django má další pre 1.0 release. Jedná se o verzi 0.96, která zahrnuje dosud dělané změny v SVN:Testovací nástroje - dá se přímo psát testy založené na doctest nebo unittest, testovat pohledy (views) a automaticky natahovat testovací dataVerze 0.96 obsahuje také nové moduly pro formuláře - django.newforms., které nahrazují starý validační framework django.formsPříjemné úpravy v URL mapovánía samozřejmě další...Django 0.96 je propracovanější, než 0.95, ale já osobně stále doporučuji používat velice stabilní trunk ze SVN. -
My Dreamhost + Django + Subversion Setup
Since I haven’t put out a technical article in a while, this blog will explain how I’ve setup Dreamhost + Django + Subversion to play nicely together in a seamless development environment via a shared hosting provider. Hopefully – someone, somewhere can find this information useful and insightful in their own development environment. The very first thing I did was unleash my first Django web application on Dreamhost. Thanks to an excellent tutorial from Jeff Croft, a detailed explanation about FastCGI contained within the Django documentation, and a few helpful pointers on the Dreamhost wiki, I was able to get my application deployed in a matter of a few hours. You can check it out here! However, after going through Jeff’s excellent tutorial, I still wasn’t completely satisfied with my Django deployment on Dreamhost. Something was missing. There wasn’t a seamless way to continue development on my home machine, deploy to a test environment, and still keep my live site intact. After all, I’m a true believer in the open source dictum of ‘release early, release often‘, and without a way to test my application on a live server, I wasn’t happy with my configuration management. Ideally, I envisioned having … -
Ajuste inteligente do settings.py
Com essa dica, teremos dois arquivos de configuração que revezam entre versão de desenvolvimento e produção, o arquivo local_settings.py contém nossa configuração de desenvolvimento, assim não precisamos nos preocupar com settings.py na hora da distribuição, pois settings.py sabe quando deve dar passagem as configurações do arquivo local_settings.py. -
Convertendo a documentação do Django em HTML
A documentação do Django é escrita em formato reST (ReStructured Text). Então podemos gerar páginas HTML para uma leitura mais divertida, o script build_documentation.py é quem faz isso em djangoproject.com e pode fazer para você também, você só precisa criar um arquivo settings.py na mesma pasta do script contendo as variáveis DJANGO_DOCUMENT_ROOT_PATH e DJANGO_TESTS_PATH que indica onde estão seus arquivos reST e o diretório de testes do Django respectivamente .Conteúdo de settings.py:DJANGO_TESTS_PATH='/home/wiliam/dev/django/tests'DJANGO_DOCUMENT_ROOT_PATH='/home/wiliam/dev/django/docs'Dicas:Rode o comando svn update antes para atualizar seu código.Mantenha separados os arquivo .txt dos arquivos .html, crie uma pasta html dentro da pasta doc do Django e modifique build_documentation.py nas linhas 50 e 51 para fiquem com um + 'html' apos DJANGO_DOCUMENT_ROOT_PATH:50 - out_file = os.path.join(settings.DJANGO_DOCUMENT_ROOT_PATH + 'html', os.path.splitext(fname)[0] + ".html")51 - toc_file = os.path.join(settings.DJANGO_DOCUMENT_ROOT_PATH + 'html', os.path.splitext(fname)[0] + "_toc.html") -
Django e o quebra cabeça com newforms
Basicamente temos duas formas para usar o newforms a primeira consiste em usar as funções form_for_model() e form_for_instance(), para a primeira função você deve passar a classe que define seu modelo e para segunda você passa a instância desta classe e o newforms encarrega-se de gerar o formulário para você. Na segunda forma você define seu formulário como uma classe que herda de Form. Considere a definição do modelo abaixo:class Product(models.Model):..description = models.CharField(maxlength=200)..category = models.ForeignKey(Category)..quantity = models.IntegerField()..cost = models.FloatField(max_digits=10, decimal_places=2)..detail = models.TextField(maxlength=400, blank=True)Usando form_for_model:>>> from django import newforms as form>>> from warehouse.models import Product>>> ProductForm = form.form_for_model(Product)>>> pf = ProductForm()>>> print pf.as_table() # retorna nosso formulário como tabela, em branco.Usando form_for_instance:>>> from django import newforms as form>>> from warehouse.models import Product>>> p = Product.objects.get(pk=1)>>> ProductForm = form.form_for_instance(p)>>> pf = ProductForm()>>> pf.as_table() # retorna nosso formulário como tabela, com valores.Acompanhe agora a segunda forma de uso do newforms. O método __init__ serve para carrega todas as categorias disponíveis no banco. Considere a definição do formulário abaixo:class ProductForm(forms.Form):..def __init__(self, *args, **kwargs):....super(ProductForm, self).__init__(*args, **kwargs)....self.fields['category'].choices = [('', '----------')] + [.......(c.id, c.name) for c in Category.objects.all()]..description = forms.CharField(max_length=200)..detail = forms.CharField(max_length=400)..category = forms.ChoiceField(choices=())..quantity = forms.IntegerField()Testando 123:Mesmo conceito usado com form_for_model:>>> from warehouse.forms import ProductForm>>> pf = … -
Django permissões
O Django tem um esquema de autenticação onde podemos definir diferentes permissões, todos os modelos definidos em models.py por padrão tem três add, change e delete. No exemplo abaixo temos um modelo Pessoa como um único campo nome e através do uso do atributo permissions da classe Meta definimos duas novas permissões dirrigir_carro e dirrigir_moto.models.py:class Pessoa(models.Model):..nome = models.charField(maxlength=30)..class Meta:....permissions = (......("dirigir_carro", "Pode dirigir caro"),......("dirigir_moto", "Pode dirigir moto"),......)Quando definir novas permissões não esqueça de atualizar a base de dados usando o comando python manage.py syncdb. Podemos checar por permissões de duas maneiras diferentes, veja abaixo:views.py:def moto(request):..if request.user.has_perm('empresa.dirigir_moto'):....return HttpResponse("Você pode dirigir moto.")..else:....return HttpResponse("Tire sua carteira de moto antes")@permission_required('empresa.dirigir_carro')def carro(request):..return HttpResponse("Voce pode dirigir carro.")A função moto usa request.user.has_perm() para checar se o usuário tem permissão, a parte antes do .dirigir_moto é o nome da aplicação e não o nome da classe "Pessoa". Usando uma função como essa você pode redirecionar o usuário para uma página de mais erro explicativa.A função carro usa o decorator @permission_required() para checar por permissão e em casso negativo redireciona para página de login normalmente /accounts/login/. -
Evolving a RESTful Django Contribution
I posted an announcement to the django-users list about the django-restful-model-views contribution to get some feedback on the approach. The main responder, Malcolm Tredinnick, gave me a lot to think about and along with more research into how Ruby on Rails (RoR) implements REST, I have new ideas about how to improve the contribution. -
Circles of Django (2007)
So here’s a question I get asked a lot: “How big is Django’s community?” Anyone who works in open source knows that it’s basically impossible to know the size of any open source community. It’s easy with commercial programs – just look at the sales numbers – but since F/OSS is freely (and widely) available, there’s almost no way to know how many people are using your project. Still, the tie-wearing enterprisy business folks ask these types of questions, and it’s useful to have an answer ready. -
Portuguese translation of Django in the trunk
The Portuguese(pt_PT) translation of Django is now in the trunk. svn co http://code.djangoproject.com/svn/django/trunk/