Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Why I'm excited about Python 3
This is a rough transcript, with links, of a 3-minute lightning talk I gave at LCA. It’s obviously not a complete argument; just a 180-second pitch for why the drama about Py3k is all smoke and no fire. I’m excited about porting my code to Python 3, and you should be, too. I’m sure all the Python users here are aware of the recent release of Python 3.0. Python 3. -
Pré-inicializando formulários de um FormWizard
Se você precisa pré-inicializar dados de formulários num FormWizard do Django, você consegue da seguinte forma: my_wizard = MyWizard( [StepOneForm, StepTwoForm], initial={ 1: {field_x: data, field_y: data, ...}, 2: {field_x: data, field_y: data, ...}, ... } ) Certo? Ok, mas e se eu quiser inserir estes dados dinamicamente, de acordo com o usuário logado no site? A forma que eu encontrei de fazer isso foi sobrescrevendo alguns métodos da classe FormWizard. Veja um exemplo: from django.contrib.formtools.wizard import FormWizard class MyWizard(FormWizard): def parse_params(self, request, *args, **kwargs): self.user_data = { 'first_name' = request.user.first_name, 'last_name' = request.user.last_name } def get_form(self, step, data=None): if step == 1: return self.form_list[1](data, prefix=self.prefix_for_step(1), initial=self.user_data) else: super(MyWizard, self).get_form(step, data) ... Não conhece o form wizard do Django? Leia mais a respeito na documentação oficial do utilitário. -
Wsparcie dla agregacji w Django
Ten wpis dotyczy czegoś, co wydarzyło się tydzień temu (tak to jest, jak się nie przegląda na bieżąco rzeczy, które się dzieją w świecie). Otóż do najnowszego kodu Django zostało dodane wsparcie dla agregacji danych (commit: 9742). Polega to na tym, że możemy wyciągnąć z bazy... -
Como usar el poderoso ORM de django en una aplicación de Escritorio
Alguna vez alguien me preguntaba que tan complejo seria usar el poderoso ORM de django en una aplicación de escritorio, lo cual me pareció una cuestión interesante pero debido al trabajo y la procrastinación™ lo dejé a algún lado, en estos días como ando melómano he estado dedicándole mucho tiempo a la musica, por cierto el reproductor que yo uso es Amarok, aunque también decidí probar el mpd, en fin cada cual tiene lo suyo y amarok me parece muy poderoso, probé otros mas como exaile, que intenta ser como amarok pero esta escrito en python con librerías gtk y este muy biche, entonces curioseando y por algunos errores de comportamiento en el amarok, me dio por revisar la estructura de la base de datos, y sinceramente no es lo mejor en modelos E-R, entonces quería ver que tan complejo sería hacer un nuevo reproductor de musica, principalmente que sea un frontend a los más comunes, amarok, banshee, mpd, y demás, incluso con una interfaz web al estilo ampache, pero pues obviamente en python y usando django, entonces empecé a realizar el esquema y de repente se me ocurrio la idea de tambien hacer un cliente de escritorio y volvio … -
Rails versus Django
I attempted to gather my thoughts into some elaborate explanation, delving into the subtleties and intricacies surrounding the question. However, upon reflection my response is a simple one and should be taken lightly. -
Display Children of One-To-Many or Many-To-Many Relationships in your Django Templates
For items you’ve defined in the parent model, such as this: class Project(models.Model): tasks = models.ManyToManyField(Task, blank=True) You use parent.children.all, like so: {% for task in project.tasks.all %} <li>{{ task.title }}</li> {% endfor %} For items defined outside of the parent model with a foreign key pointing back to the parent model, such as this: [...] -
Cambiar permisos de archivos con python
Pues bien la historia comienza así:Estoy desarrollando una aplicación con django para una galeria de arte, la url de la pagina en desarrollo es http://laotraferia.nodo-lab.com que después apuntará a http://www.laotraferia.com y pues probé con django-audioplayer que es un tag para embeber un reproductor de mp3 en la pagina, y no me funcionaba porque por algun motivo extraño al subir el mp3, me quedaba sin permisos de lectura en el servidor, por lo cual decidí que debia cambiarle los permisos cada vez que suban el archivo por lo cual debia reescribir el metodo save en el modelo:def save(self,force_insert=False, force_update=False):super(Audio,self).save(force_insert,force_update)Y allí cambiar los permisos cada vez que guarden el objeto, por lo cual busque en la pagina de python, y encontre el metodo chmod en el modulo os, y primero intenté:>>> import os>>> os.chmod("archivo","777")Al viejo estilo de linux, pero esto me genera un error pues el modo debe ser un entero y no una cadena, hice este cambio y no me genero error pero me cambió los permisos de una forma extraña, luego lei un poco más y es que esto debe hacerse usando otro modulo stat, de la siguiente manera:>>> import os>>> import stat>>> os.chmod("archivo",stat.S_IRUSR+stat.S_IWUSR+stat.S_IRGRP+stat.S_IXGRP)y de esta manera me deja los … -
How to use the same widget as GeoDjango
At the end of this post you will be able to use the same widget than the automatically generated admin interface in geodjango. I spent quite sometimes today to rediscover how to do this. Yes, rediscover because I have already written about this a couple of month ago. My first post on that topic can be read there. Happily "jbronn" on #geodjango gave the solution to me.# Getting an instance so we can generate the map widget; also# getting the geometry field for the model.admin_instance = PointAdmin(Point, admin.site)point_field = Point._meta.get_field('point')# Generating the widget.PointWidget = admin_instance.get_map_widget(point_field)In fact all the complication at the moment there is no static widget that widget you could use in your own form. You have to build them dynamically.I am now going to break down the 3 lines of code.PointAdmin is the ModelAdmin class which is a representation of a model in the admin interface. Here it is an example :from django.contrib.gis import adminfrom geotagging.models import Pointclass PointAdmin(admin.GeoModelAdmin):list_filter = ('content_type','point' )list_display = ('object', 'point', 'content_type', 'object_id')Point in the model we are working on so Point._meta.get_field('point') is accessing the field called point of the Point mode. The code below should help you to understand :class Point(models.Model): """ """ … -
Open Source Communities
Open source projects should be judged as much by their community as by their technological achievements. The code tells you what it’s good for, but the community tells you what its future is. Communities need to be active to continue improving the project, deal with bugs and changes to their ecosystem. If no one is [...] -
Django Site of the Week - ShutterCal
ShutterCal is a photo sharing site with a difference - it encourages contributors to upload one photo every day to help people reach a goal: whether that may be to improve their photography, watch themselves evolve over a year, or remember people and places they visit. ShutterCal started in 2007, and this week I spoke to developer Dan Ferrante to find out why he chose Django, some of the challenges he's faced, and how he uses Django and other open-source software to make his life easier. You can read more over at the Django Site of the Week. -
Django Site of the Week - ShutterCal
ShutterCal is a photo sharing site with a difference - it encourages contributors to upload one photo every day to help people reach a goal: whether that may be to improve their photography, watch themselves evolve over a year, or remember people and places they visit. ShutterCal started in 2007, and … -
Django 2.0
So apparently some folks doing business as “Vyper Logix Corp” are peddling a thing they call “Django 2.0”. I’m not going to link it here since they don’t deserve the Google bump, but if you’re interested you can follow the link in Jannis’ tweet where he mentioned it. In fact, with any luck my Google juice will pop this article up above them. “Django 2.0” is, apparently, built on the Django 0.96 ... Read full entry -
Django vs Rails: The Dead-Tree Edition
Django Rails In Conclusion The difference speaks for itself. I’ll write about why this matters tomorrow. (Yeah, I used the Fancy Link Builder I posted yesterday about. It was infuriating to use, it has whiz-bang Javascript to open a product detail lightbox that served only to make it nearly impossible to copy cover images. New [...] -
Django 2.0
So apparently some folks doing business as “Vyper Logix Corp” are peddling a thing they call “Django 2.0”. I’m not going to link it here since they don’t deserve the Google bump, but if you’re interested you can follow the link in Jannis’ tweet where he mentioned it. In fact, with any luck my Google juice will pop this article up above them. “Django 2.0” is, apparently, built on the ... Read full entry and comments -
I'm lazier then django forms
When I started to learn django, i fell in love with django forms, or newforms as it was called then. It made writing forms a lot more enjoyable. So like many relationship, it started out great, we, (me and django forms), were having a great time together, having fun spending a lot of time together, great. Then we started to get serious and that’s when things became more complicated. I found myself using copy and paste a lot, from one form to another form. Sure it did the job, but it required more effort then I wanted to give. I had to give it a couple looks each time to ensure everything was correct. It got tedious, and i have to blame django forms for this. It has spoiled me, making things to easy to use. I can’t imagine trying to write out forms like I once did in .NET. So as our relationship continued we found our selves in the same cycle, everything the same. But I wanted more, I wanted to us to be in love again. Like we were when we first meet. Solution - Form Options class FormOptions(): """ FormOptions class gives Form extra properties so we can build a … -
Django SOTW Moving to Mondays
To better fit with both my own way of doing things and with general web browsing patterns of the Django SOTW public, I'm moving the SOTW to Mondays rather than Saturdays. You can expect new interviews to go live on Monday evenings (Australian EST) which means our US visitors should see them in their RSS feeds first thing Monday morning. Also, I've finally succumbed to the forces and I've joined Twitter so you if that's your kinda thing then come and say hi! -
Django SOTW Moving to Mondays
To better fit with both my own way of doing things and with general web browsing patterns of the Django SOTW public, I'm moving the SOTW to Mondays rather than Saturdays. You can expect new interviews to go live on Monday evenings (Australian EST) which means our US visitors should … -
Django ma teraz szybsze testy
Do trunk'owej wersji Django został zakomitowany mechanizm testów działający na transakcjach, przyśpiesza wykonywanie testów o ok. 8 do 40 razy. Funkcjonalność ta znajdzie się w wersji Django 1.1 która będzie wydana marcu. Aby skorzystać z tej funkcjonalność należy używać silnika baz danych który obsługuje tranzakacje. Mam nadzieję że teraz już nikt nie będzie miał wymówek aby nie pisać testów :) -
Джанговские агрегации
Сделали: http://docs.djangoproject.com/en/dev/topics/db/aggregation/! Особо приглянувшиеся мне вещи: Store.objects.annotate(Count('books__authors')) Store — это магазин, у него many-to-many на Book, у которого есть many-to-many на Author. Тут делается join по всем нужным таблицам и group by на них. Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1) Я очень рад, что having не стали делать отдельным понятием. Это просто фильтр. А уж ... -
From WordPress to Django – Part 1
Now don't get me wrong, there's nothing wrong with Wordpress. It's just that I like to play with stuff, so I thought it would be fun to create a blog in Django, copy all my Wordpress posts across, and add at least some of the functionality that Wordpress has built in. -
Washington Post Update
It’s been a long time since I’ve written about what I’ve been up to at the Washington Post, so let me run down the apps I’ve worked on since September 2007 in roughly linear order. Lots of these apps link different places, so if you don’t see projects.washingtonpost.com at the start of the URL, you’ve [...] -
Изменённые данные в форме
Когда-то я придумал для своего багтракинга фичу, которая мне казалась уникальной для багтракингов. Фича связана с тем, как обрабатываются изменения, которые человек сохраняет в тикет, в то время, как тикет уже успел поменяться кем-то другим за время с момента открытия того в окне браузера. И вот на днях, в процессе ... -
Django Gotcha: Never set a variable called ‘user’ in your RequestContext
Okay. So I was working on some view code in a Django project and I noticed something weird. The view started rendering as if the user was no longer logged in. Odd thing was that it was only doing that for that one view. I banged my head for a while and then I realized […] -
Descriptivists and Prescriptivists
In the world of grammarians there are two competing camps: descriptivists and prescriptivists. Edward Finegan of the University of Southern California sums up the difference: Descriptive grammarians ask the question, “What is English (or another language) like – what are its forms and how do they function in various situations?” By contrast, prescriptive grammarians ask “What should English be like – what forms should people use and what functions should they serve? -
Generic Collections in Django
Django‘s generic relations are a great way to connect an object to any other type of object. Django provides a GenericForeignKey field to connect one object to any other object. For a recent project I needed to create a Many-to-Many relationship between an object and certain types of other objects, and have them editable in the admin. Here’s how I did it. The Models For this example we’ll create several simple models. class Photo(models.Model): "A simple photo model" title = models.CharField(max_length=50) image = models.ImageField(upload_to='img/photos/%Y/%m/%d') class Audio(models.Model): "A simple audio model" title = models.CharField(max_length=50) image = models.ImageField(upload_to='audio/%Y/%m/%d') class Link(models.Model): "A simple link model" title = models.CharField(max_length=50) link = models.URLField() class BlogEntry(models.Model): "A simple Blog Entry model" title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) body = models.TextField() Now let’s find a way to relate any number of these objects to a single Blog Entry. To do that we are going to need an intermediary table that will handle the relations. blogentryrelation_limits = {'model_in':('photo', 'audio', 'link', 'blogentry')} class BlogEntryRelation(models.Model): "A simple photo model" blogentry = models.ForeignKey(BlogEntry) content_type = models.ForeignKey(ContentType, limit_choices_to=blogentryrelation_limits) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') The blogentryrelation_limits variable enables you to allow the selection of certain models in the admin. The Admin To see everything properly in the …