Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
An if-substring-in-string Django Template Construction
Here's a quick tip for Django template hackers. It's a known fact of Django templates that the syntax is purposefully limited. I've been living with the need for an if-substring-in-string construction. Of course, I could write a custom template tag, but work is quitebusy. So on a whim and a 10 minute break I tried this yesterday, and it worked well for me. Take a look and let me know what you think.First, the problem.Bookmark FormattingI have a custom app for pulling in my Delicious bookmarks and formatting them as link posts here on this site. I include the HTML I want in the original bookmark and have a bit of template code to insert preview images generated by ShrinkTheWeb. When I link a YouTube video, I do a quick cut-n-paste of the video to embed the player, and in these cases, I don't want to include the preview image. In Python, this would be super simple: if 'http://www.youtube.com/' not in link_url: show_thumb() However, Django templates don't have a similiar syntax.A Solution Using {% with %}So here's what I did: {% with link_url|slice:":23" as short_url %} {% ifnotequal short_url "http://www.youtube.com/" %} My ShrinkTheWeb image goes here. {% endifnotequal %} Other … -
Django and nginx settings
Django and nginx settings -
EveryBlock libera su código fuente
Hace un par de días se ha liberado el código de EveryBlock bajo licencia GPL. EveryBlock ofrece noticias e información local sobre barrios de distintas ciudades de Estados Unidos. Se trata de uno de los sitios web más interesantes que utilizan Django. El código fuente se puede encontrar dividido en distintos paquetes en el sitio oficial. El código incluye paquetes que trabajan con información geográfica, el sistema de publicación completo de EveryBlock y hasta un paquete de blog y otro de wiki. -
AvaTint Launched!
The site very simply takes your avatar and turns it into any color you select. The online community is starting to do this to support and protest many things. This is the 2.0 way of making your page background black for a cause. We created this site in 90 minutes using Django on June 19th. I got home from dinner and noticed that some twitter icons were coming in green. This caught my attention because I had suggested yellow to protest Obama's massive government spending a few days earlier. I mentioned this to Rudy Menendez (yes related) and suggested it would be useful for the less tech savvy to create a page to change an avatar's color. We knew the Pyhon package PIL could do this and Rudy found jscolor as a color selection tool. Together we created and deployed this application. The timeline is roughtly as follows: 12:25am CT Floated the idea to Rudy via IM 12:30am CT Created local proof of concept that PIL could handle it 12:35am CT Created local project diretory 12:38am CT Download jscolor 12:56am CT Registered domain 1:14am CT Rudy jokes about test scripts 2:00am CT Start deploy to production server and test 2:10am … -
SVN usability
Okay, time to import this code into SVN. svn import, right? This should be easy! svn import https://...../trunk/ Oh crap, that tried to import everything. ^C Guess I’ll just set svn:ignore. svn propset . svn:ignore svn propset svn:ignore . svn propedit svn:ignore svn propedit svn:ignore . Okay. Can’t do that on a non checkout. Fine. cd .. svn co https://...../trunk/ myproject.svn cd myproject.svn/ mv ../myproject/* . Right, okay. Add some files now. -
MySQL Backup Skript mit Emailversand.
A while ago I found a good script for backing up a MySQL database and sending it via email to a recipient here. The script is cool, but I didn't like its structure and the fact, that you have to add the database values inline and that it can only backup a single database. For this reason I rewrote it a little and you can download it here. Features: Backup of mutliple databases Sending of backups to multiple users For every single database a mail is send and there is no file saved on the server. And wow: it's really easy to configure! How do I use it? Download the current version (0.1) Adjust the backup.php (you're getting help by my wonderful comments) upload everything to a directory of your choice if applicable, create a cronjob to periodically execute the script And here the backup.php that calls the appropriate classes and executes the backup (also included in the download): ini_set('error_reporting', E_ALL);// include the filesrequire_once 'MySQLConfig.php';require_once 'MySQLBackup.php'; // add some databases to backup// the domain will be appended to the email subject and is also included within the sql file for identification.$cfgHost0 = new MySQLConfig('username0', 'password0', 'database_name0', 'domain0');$cfgHost1 = new MySQLConfig('username1', 'password1', … -
MySQL backup script with emailing
A while ago I found a good script for backing up a MySQL database and sending it via email to a recipient here. The script is cool, but I didn't like its structure and the fact, that you have to add the database values inline and that it can only backup a single database. For this reason I rewrote it a little and you can download it here. Features: Backup of mutliple databases Sending of backups to multiple users For every single database a mail is send and there is no file saved on the server. And wow: it's really easy to configure! How do I use it? Download the current version (0.1) Adjust the backup.php (you're getting help by my wonderful comments) upload everything to a directory of your choice if applicable, create a cronjob to periodically execute the script And here the backup.php that calls the appropriate classes and executes the backup (also included in the download): ini_set("error_reporting", E_ALL); // include the files require_once "MySQLConfig.php"; require_once "MySQLBackup.php"; // add some databases to backup // the domain will be appended to the email subject and is also included within the sql file for identification. $cfgHost0 = new MySQLConfig("username0", "password0", … -
MySQL backup script with emailing
A while ago I found a good script for backing up a MySQL database and sending it via email to a recipient here. The script is cool, but I didn't like its structure and the fact, that you have to add the database values inline and that it can only backup a single database. For this reason I rewrote it a little and you can download it here. Features: Backup of mutliple databases Sending of backups to multiple users For every single database a mail is send and there is no file saved on the server. And wow: it's really easy to configure! How do I use it? Download the current version (0.1) Adjust the backup.php (you're getting help by my wonderful comments) upload everything to a directory of your choice if applicable, create a cronjob to periodically execute the script And here the backup.php that calls the appropriate classes and executes the backup (also included in the download): ini_set("error_reporting", E_ALL); // include the files require_once "MySQLConfig.php"; require_once "MySQLBackup.php"; // add some databases to backup // the domain will be appended to the email subject and is also included within the sql file for identification. $cfgHost0 = new MySQLConfig("username0", "password0", … -
MySQL backup script with emailing
A while ago I found a good script for backing up a MySQL database and sending it via email to a recipient here. The script is cool, but I didn't like its structure and the fact, that you have to add the database values inline and that it can only backup a single database. For this reason I rewrote it a little and you can download it here. Features: Backup of mutliple databases Sending of backups to multiple users For every single database a mail is send and there is no file saved on the server. And wow: it's really easy to configure! How do I use it? Download the current version (0.1) Adjust the backup.php (you're getting help by my wonderful comments) upload everything to a directory of your choice if applicable, create a cronjob to periodically execute the script And here the backup.php that calls the appropriate classes and executes the backup (also included in the download): ini_set("error_reporting", E_ALL); // include the files require_once "MySQLConfig.php"; require_once "MySQLBackup.php"; // add some databases to backup // the domain will be appended to the email subject and is also included within the sql file for identification. $cfgHost0 = new MySQLConfig("username0", "password0", … -
Link Exchange For Tough Times
Advertising on Google is getting expensive, very expensive. This year advertising costs for Adwords rose between 40% and 60% for some advertisers. Companies like eBags.com and Babyage.com have seen the cost of advertising online soar to 45% of the cost of the product they are trying to sell. Margins are diminishing and [...] -
Practical Django Projects
June 2009 News Update: The second edition of this book has been released! The 2nd edition of Practical Django Projects has been released making this series of posts redundant! Notes and a practical companion I've been reading James Bennett's excellent Practical Django Projects (PDP), which uncritically I think is the best python based book I've read since I picked up Mark Lutz's Learning -
Psychic IRC Support In 10 Easy Steps
This list is somewhat specific to Django and #django channel on freenode.net. Psychic support is what people are looking for when they expect others to just know their development environment and their code. If one doesn’t supply enough information on the problem, no matter how good a hacker the person on the other end of [...] -
Untitled
hej -
Untitled
hej -
Что такое pip?
Pip это альтернатива easy_install, а как говорят сами разработчики - замена. Как известно easy_install только часть глыбы под названием setuptools. Много копий сломано по поводу нужно ли такие двухголовое чудовище, которое позволяет продвинутым образом собирать питонячьи пакеты и их устанавливать. Или достаточно стандартного distutils. Вот тут pip выступает как противоположность, говоря - я сборкой пакетов не занимаюсь, а только их ставлю. Pip может поставить любой пакет собранный при помощи distutils. Причем только source-пакет - никаких бинарных яиц ему и прочих setuptools'овых прибамбасов. Эта концептуальная простота во многом помогла pip постепенно выйти на уровень широко используемого инструмента в питон-сообществе. Благо и пользоваться им максимально просто: # pip install wna где wna - это некий пакет (для примера я возьму код своего блога). Так же преимуществом pip безусловно является более полезный вывод информации о процессе установки и репортинг ошибок во всяких непредвиденных ситуациях. Помимо уже собранных source-пакетов pip может брать исходники пакетов из систем контроля версий. Поддерживаются subversion, mercurial, git, bazaar. Делая checkout и устанавливая через python setup.py с ключом devel, дает возможность иметь в папке /src/packet_name/ исходный код и при необходимости редактировать его. # pip install -e hg+http://bitbucket.org/daevaorn/turbion/#egg=turbion Где egg=turbion говорит pip чтобы он сделал checkout в /src/turbion/. Очень полезная возможность, … -
sphinx autodoc and django app
Today I have been getting my foot wet with autodoc extension from sphinx. Here it is what the documentation of sphinx say about it :"""Sphinx is a tool that makes it easy to create intelligent and beautiful documentation, written by Georg Brandl and licensed under the BSD license."""I have to say that before today my experience with sphinx as been excellent. It is relatively straightforward to get started once you pass the first little annoyances that come with the fact that you are learning a new tool.The module I have been using to conduct this experiment is django-geotagging this reusable app enables you to geotag any object in the database. If you want to know more about this you can read the sphinx based documentation. This is the goal of the documentation, isn't it ? :-)If adding a manually written documentation is very easy and well documented. The modification required to move from a very primitive documentation written using some rst file to sphinx is shown here. Most of it is automatically generated by : sphinx-quickstart.Taking it a step further have been more difficult than anticipated and this for several reasons : lack of example, and a bugToday I wanted … -
How Great is Django's Documentation?
One aspect of Django that never ceases to amaze me, is how well it is documented. I believe this aspect of the Django project got many of us to use it, me included. While doing some boring graduate donkey work, Django’s name popped out, and not surprisingly, as one of the highly documented code bases out there (only projects focusing on documentation came close!). So lets me take this opportunity to thank all those who might be reading this, who had a hand in making Django what it is (Thank you!) The Lines of documentation to SLOC ratio is plotted against SLOC for 1st of Jan, 2009. Django has one of the highest ratios compared to other open source projects of similar size (See the top part of the Graph). Of course I could have plotted doc lines to SLOC, but then I have to show the deviation of Django from the regression line. This graph just makes it more obvious and is easier to plot: Click to enlarge, and don’t forget to zoom in. I also have a few questions should any Django contributors pass by. Any of you guys think that you might have over done it? Is it difficult to … -
ModelAdmin readonly fields
Finalizing my web application, there was a few outstanding patches left to do. One of this I always felt strange why it was left out in the open. Django's admin interface form by default allows you to edit the primary key of the model. I always felt strange why it allowed this as it led to unexpected behavior. My users would edit the primary key expecting the changes to be done on the record which of course did not happen as django created another new object with the new edited id. In solving this bug I was hoping that django's admin model allowed for something like 'readonly = ( 'id_field')' or something like to that respect. Just thinking out aloud but shouldn't this be automatically done for all primary key fields in models.py ? Shouldn't the primary key be made non editable by default unless explicitly stated in the definition? Even then should the primary key be allowed to be edited? If a user were to be allowed to edit the primary key, would it really be editing or 'cloning' a new object with similar data but differing ids? I haven't really done a thorough search yet but I think … -
Django-Loupe for Design Collaboration
I've been using Basecamp for years and have a love/hate relationship with it simply because it costs me money for clients that don't want to use it. However, I can't get rid of it because there are a few clients I have that need collaboration for designs. For coding projects I use various ticketing systems from Trac to Sifter and I won't get into that in this post. During a current project Trac is being used for the backend parts but it falls apart on design collaboration. After a few late nights I'm thrilled with the progress of Django-Loupe for design collab. -
Django - migracje z south
South jest jedną z najlepszych aplikacji do prostego tworzenia migracji struktur baz danych w Django. Używam south'a od wersji 0.3. I muszę powiedzieć że jest to naprawdę dobre narzędzie. Ułatwia prace przy tworzeniu i rozwijaniu aplikacji w Django. Normalnie gdy tworzymy aplikacje w Django i korzystamy z syncdb, gdy chcemy zmienić strukturę bazy danych to musimy albo usunąć całą bazę i ponownie wykonać syncdb lub pisać "ręcznie" SQL który zmieni tą strukturę. Dodatkowym problemem jest jeżeli chcemy później te same zmiany struktury bazy danych wykonać na środowisku produkcyjnym. Przy większych projektach jest bardzo uciążliwe i zajmuje bardzo dużo czasu. Chciałbym opisać tutaj swoje doświadczenia z south 0.5 i pokazać jego możliwości. Instalacja Jeżeli nie mamy jeszcze zainstalowanego south'a to instalujemy: easy_install south Zaczynamy: Tworzymy projekt który posiada dwie aplikacje books oraz authors. django-admin.py startproject southtest manage.py startapp books manage.py startapp authors Dopisujemy south oraz aplikacje books i authors do INSTALLED_APPS i robimy syncdb. South stworzy sobie tabele w której będzie trzymać historie migracji. Dopisujemy modele do aplikacji books i authors Modele z aplikacji authors: from django.db import models class Author(models.Model): name = models.CharField(max_length=30) Modele z aplikacji books: from django.db import models from southtest.authors.models import Author class Book(models.Model): name = models.CharField(max_length=30) … -
Djangodose Logo
I finally got some time to work on my backlog of logos this week and they are starting to hit the streets. So if you're waiting on me to finish the commissioned logos, they are coming quickly! Sorry for delays, it's been hell-busy here. First out the door is the new djangodose logo for they great guys of TWiD fame Eric Florenzano, Brian Rosner and Kevin Fricovsky. I believe they have announced they are recording this Sunday for those (including myself) who are anxious for the new show. I'm still working on the site design which will be finished just in time for the show release. -
Adaptador do Django para DB2 lançado!
Adaptador do Django para DB2 lançado! -
Adaptador do Django para DB2 lançado!
Adaptador do Django para DB2 lançado! -
EuroDjangoCon 2009
EuroDjangoCon 2009 is still going strong, but I wanted to share the materials from my talk as quickly as possible. My slides are on Slide Share:Forms, Getting Your Money's WorthView more presentations from kingkilr.And the first examples code follows:from django.forms.util import ErrorListfrom django.utils.datastructures import SortedDictdef multiple_form_factory(form_classes, form_order=None): if form_order: form_classes = SortedDict([(prefix, form_classes[prefix]) for prefix in form_order]) else: form_classes = SortedDict(form_classes) return type('MultipleForm', (MultipleFormBase,), {'form_classes': form_classes})class MultipleFormBase(object): def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=':', empty_permitted=False): if prefix is None: prefix = '' self.forms = [form_class(data, files, auto_id, prefix + form_prefix, initial[i], error_class, label_suffix, empty_permitted) for i, (form_prefix, form_class) in enumerate(self.form_classes.iteritems())] def __unicode__(self): return self.as_table() def __iter__(self): for form in self.forms: for field in form: yield field def is_valid(self): return all(form.is_valid() for form in self.forms) def as_table(self): return '\n'.join(form.as_table() for form in self.forms) def as_ul(self): return '\n'.join(form.as_ul() for form in self.forms) def as_p(self): return '\n'.join(form.as_p() for form in self.forms) def is_multipart(self): return any(form.is_multipart() for form in self.forms) def save(self, commit=True): return tuple(form.save(commit) for form in self.forms) save.alters_data = TrueEuroDjangoCon has been a blast thus far and after the conference I'll do a blogpost that does it justice. -
Towards a Standard for Django Session Messages
Django needs a standard way in which session-specific messages can be created and retrieved for display to the user. For years we’ve been surviving using user.message_set to store messages that are really specific to the current session, not the user, or using the latest and greatest Django snippet, pluggable app, or custom crafted middleware to handle messages in a more appropriate way.