Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Using dev_appserver with Python 2.7 on App Engine
Starting with SDK 1.6.0 the App Engine fully supports Python 2.7. This article originally described a workaround for getting Python 2.7 running on SDK 1.5.5. Now it only describes how to port your app.yaml and request handlers to Python 2.7. The following instructions work with any WSGI-compliant web framework. I'll explain how to use Python 2.7 with djangoappengine/Django-nonrel at the end of this post. Yes, Django-nonrel works with Python 2.7 on App Engine. This blog (All Buttons Pressed) is already running on Python 2.7 with threadsafe: yes. Let's start with a simple app.yaml for Python 2.5: application: yourappid version: 1 runtime: python api_version: 1 handlers: - url: /.* script: handler.py The handler.py file looks like this: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # This can be any WSGI handler. Here we just use webapp. application = webapp.WSGIApplication(...) def main(): run_wsgi_app(application) if __name__ == '__main__': main() In order to use Python 2.7 you have to change your app.yaml like this: application: yourappid version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /.* script: handler.application Here we've changed the runtime to python27, added threadsafe: yes and modified the last line (script) to point to the WSGI handler directly … -
Generar arxius xls amb Python I
Una de les coses que volia que l'aplicació de gestió de comunitat de propietaris que fem és la de tenir algun tipus de via per a poder exportar la informació introduïda. D'aquesta manera el client no està captiu i les seves dades són realment seves, però a més també volia que aquesta informació es presentàs de manera que també pogués ser útil. El format csv està prou bé, però és massa simple a l'hora de presentar les dades. Necessitava quelcom del format del qual fora prou potent per poder aplicar estils i format bàsic, i al mateix temps que no implicàs una despesa addicional per al client. Cercant, cercant vaig arribar a la llibreria xlwt. Aquesta llibreria permet crear fitxers en format xls (Excel) d'una manera prou senzilla i ràpida com per a ser just el que necessitàvem. El format es pot llegir tant mitjançant aplicacions privatives, que de d'aquí no recomanaré, o des d'aplicacions lliures com l'OpenOffice o LibreOffice. Per a qui vulgui saber-ho tot podeu fer una ullada al codi font, però si us conformau amb un poquet menys, podeu llegir-vos el tutorial. Si voleu anar per feina podeu seguir llegint i us ne faré cinc cèntims de … -
Announcing the Yipit Django Blog: Sharing Everything We’re Learning
Yipit has been using Django since its inception nearly two years ago. If it wasn’t for a modern web framework like Django, we probably wouldn’t exist. Two years and hundreds of thousands of users later, we’ve gotten deep into the core of Django and many of the contributed packages. Our goal now is to truly master Django. While one can learn a lot by doing, we tend to believe that you can learn even more by teaching what you’ve learned. Accordingly, we’re going to be spending significant time sharing what we’ve learned and are learning about using and scaling Django. Topics We Will Cover Some of the topics we will be regularly discussing on our new Yipit Django blog include: System configurations: Using Chef and Fabric to deploy our Github-hosted code to Ubuntu servers on Amazon ec2. Running Gunicorn as the application server. Database Migrations: South handling model changes and generating appropriate migrations. Data Storage: A combination of MySQL, Memcache, and MongoDB for storing our data Queueing Tasks: Celery for queueing asynchronous processes. Amazon’s SQS to manage the underlying queue. Templating: Inheritance and custom inclusion tags. Testing: Automated testing tools including Nose, Splinter, and Lettuce We hope that by sharing … -
(Dutch) Python/Django vacature in Utrecht
-
I want to solve the uploads problem
Making file uploads is a frequent, but yet to be solved properly task. I believe we can, and should, do better. For some time now we've been working on a web service which handles file uploads for you, my fellow web developer. -
Postgres and Django
Frank Wiles gave a great talk [Secrets of PostgreSQL Performance][SoPP] ## Don't do dumb things * Dedicate a single server to your database * Only fetch what you need ## Do smart things * cache everything * limit number of queries ## Tuning * shared\_buffers : 25% of available RAM * effective\_cache\_size : OS disk cache size * work_mem : in-memory sort size ### Less important * wal\_buffers : set to 16MB * checkpoint\_segments : at least 10 * maintenance\_work\_mem : 50MB for every GB of RAM Can also transactionally turn on grouping of transactions. ## Hardware * As much RAM as you can afford - fit whole db if you can. * Faster disks. - Disk speed is important - RAID5 is bad - RAID-1+0 is good - WAL on own disk → 4x write performance * CPU speed - unlikely to be the limiting factor. ## Other * use pg_bouncer to pool connections * use tablespaces to move tables/indexes onto other disks + ie, indexes on fastest disk + stuff that might run in background and hit only specific tables that are not used by other bits [SoPP]: http://blip.tv/djangocon/secrets-of-postgresql-performance-5572403?utm\_medium=twitter&utm\_source=twitterfeed -
I got lots of "Solid Django" book feedback
-
Разъяснения Рассела
В недавнем посте с интервью с Джанго-разработчиками меня попросили уточнить, что имел в виду Рассел Кит-Маги, говоря про WSGI и валидацию моделей. У меня и у самого эти два пункты вызывали недопонимание, поэтому я попросил его их разъяснить. Вот перевод его ответа: Так, первый пункт: WSGI на самом деле хорошо заточен под классическую задачу "показать целиком веб-страницу". Он был спроектирован как самый простой рабочий "наименьший общий делитель" — фактически Питоний вариант CGI. То есть он очень хорошо спроектирован для веба 1995 года, но не настолько хорошо для веба 2011, с его long polling'ом и другими вкусными push-технологиями и серверными плюшками, которые теперь используются повсеместно. Многие уже написали гораздо подробней и об этой проблеме, и о WSGI вообще: http://lucumr.pocoo.org/2011/7/27/the-pluggable-pipedream/ http://www.b-list.org/weblog/2009/aug/10/wsgi/ На самом деле, это не обязательно является проблемой самой Джанго — она использует WSGI всего лишь как API для общения с сервером. Можно использовать любой другой интерфейс, если он кем-то специфицирован. Например, Джанго поддерживает fcgi и mod_python — последний хоть и устарел, но показывает, что метод, который используется для запуска Джанго не зависит от Джанго, как библиотеки по обслуживанию веб-запросов. Я также должен заметить, что на WSGI тоже возможно реализовать long poll и другие push-технологии, просто это спецификация не обязательно лучше … -
Utilizar javascript o CSS en el admin de Django
Es realmente sencillo utilizar javascript o CSS propio en el sitio de administración de nuestro proyecto Django. Para ello podemos añadir en nuestros ModelAdmin los archivos JS o CSS que necesitemos utilizando la clase Media en los modelos de administración... -
Kiwi PyCon, DjangoCon US, and PyCodeConf Recap
I just got back from a long conference circuit, attending and speaking at PyCon Australia, Kiwi PyCon, DjangoCon US, and PyCodeConf. It was a ton of work, but it was a blast. I got to blog about PyCon Australia already, but then the time in between the other conferences was just a bit too hectic to blog. Kiwi PyCon 2011 I gave the opening keynote speech at Kiwi PyCon in Wellington, New Zealand. The talk was meant to be mildly provocative but in an inspiring, "go out and code" kind of way. Kiwi PyCon 2011 - Audrey Roy Keynote Speech View more presentations from Audrey Roy The Pythonistas of New Zealand are amazing. I met more Twisted devs than I've ever met in my life, attended tons of hardcore Python talks by women, and ones by men too, and learned all sorts of new things. I was also blown away by the hospitality of the conference organizers, particularly Tim McNamara and Richard Shea. After the conference, I spent a couple of days going around the countryside and southern island coastal towns with Danny. It was spectacular. DjangoCon US 2011 I co-presented the Django Package Thunderdome with Daniel Greenfeld. Here … -
any2any - flexible serialization / deserialization for Python and Django
Why on earth ? When doing web programming, we all the time have to pass data from one format to another, from one object to another, we serialize, we deserialize … For much of those problems, many cook their own stuff … a piece of code that does its thing, and which is usually not so flexible and therefore not re-usable. It ends-up being not very DRY ! Recently I was working on a project implying Django, ldap and a json API ; trying to stick libraries together and endlessly transforming the same data from/to different formats. I grew tired of writing similar-looking code for doing that. So I started gathering, factorizing, generalizing this code, and came up with any2any. NB: if at this point you think “Why on earth would I ever use that ?”, maybe you should first download this example, and play with it. It is a very simple Django project demonstrating, how you can customize the output format of your API with any2any. A primer for Cast any2any’s most important class is Cast. Basically, that’s the base class for building all your transformation operations. Defining a new cast is very simple : class MyCast(Cast): setting1 = … -
Taller de Introducción a Django el 17 octubre en Madrid
El próximo lunes día 17 de Ocubre realizaremos en Madrid un Taller de Introducción a Django de la mano de Betabeers. Está orientado a gente que quiere tener un primer contacto con el framework y que todavía no lo conoce mucho (o nada). Tenéis la información en la sección de formación y en el blog de de Betabeers... -
Ordenar una query por la longitud de un campo
A veces tenemos que hacer queries un poco especiales y necesitamos ayuda de SQL cuando el ORM de Django se nos queda pequeño. Aquí tenemos un ejemplo de cómo ordenar una query a la base de datos por la longitud de un campo... -
Django admin magic screenshots
-
Caktus 2012 Summer Internship Program
I'm excited to announce that Caktus is looking for candidates for our summer internship program. It is a 12 week paid position in our Carrboro, NC office. We're driving distance from UNC Chapel Hill, NC State Univeristy in Raleigh, and Duke in Durham, so students from all parts of the NC Research Triangle are welcome ... -
Caktus 2012 Summer Internship Program
I'm excited to announce that Caktus is looking for candidates for our summer internship program. It is a 12 week paid position in our Carrboro, NC office. We're driving distance from UNC Chapel Hill, NC State Univeristy in Raleigh, and Duke in Durham, so students from all parts of the NC Research Triangle are welcome to apply. -
Caktus 2012 Summer Internship Program
I'm excited to announce that Caktus is looking for candidates for our summer internship program. It is a 12 week paid position in our Carrboro, NC office. We're driving distance from UNC Chapel Hill, NC State Univeristy in Raleigh, and Duke in Durham, so students from all parts of the NC Research Triangle are welcome ... -
Caktus 2012 Summer Internship Program
I'm excited to announce that Caktus is looking for candidates for our summer internship program. It is a 12 week paid position in our Carrboro, NC office. We're driving distance from UNC Chapel Hill, NC State Univeristy in Raleigh, and Duke in Durham, so students from all parts of the NC Research Triangle are welcome ... -
Load Testing with JMeter: Part 2 - Headless Testing and Jenkins Integration
If you read part 1 of my JMeter series, you now know how to create a JMeter performance test with as much complexity as you need to hit every part of your application and push it to its limits. As mentioned at the end of the post, though, when running your test plan from your local machine you are often limited by bandwidth. The test plan may not be able to fully stress your application because it can’t transfer data fast enough for all of your concurrent connections. To really push your application hard, you need to run your load test from the same local network that your application runs within. -
Cómo importar un archivo CSV (ó TSV) en un modelo de django
Mitch Fournier explica en su blog cómo importar datos en formato CSV a un modelo de Django, tal cómo lo ha utilizado en su proyecto Wantbox.com. Primero creamos un modelo que contenga los mismos campos que el archivo CSV que queramos importar, utilizando el tipo de campo más adecuado para cada uno de ellos dependiendo de si sus valores van a ser cadenas de texto, números, fechas... -
I'm writing a Django book
-
How To Import a CSV (or TSV) file into a Django Model
Recently I downloaded a US zip code data file in comma separated (CSV) format. Below are the steps and python script that I used to import that data into a django model for my site Wantbox.com. The Steps to Import CSV Data into Django: Create your django model (mine is called “ZipCode”, see below). Create [...] -
First steps with Compass
A lightning talk by Thijs Jonkman at the Dutch Plone User Day once again brought Compass to my attention. I’ve read about it on other occasions, but I never actually tried it. But Thijs really made me want to try it for myself. First of all a bit of explanation about Compass. According to the website it is an “open source CSS authoring framework which uses the Sass stylesheet language."1 Let’s process this backwards… Sass, which stands for “Syntactically Awesome Stylesheets”, is an extension of CSS3 and it adds a lot of useful features (e.g. variables, and mixins). These features make CSS development a lot easier. (And, speaking as a Python developer, more fun.) Compass is a framework that makes working with Sass even better. Its core contains all kinds of useful mixins for e.g. CSS resets, CSS3 borders, a footer that sticks to the bottom of the page and code to help you with sprites, to name just a few. And if you need more than Compass delivers out of the box, there are many more plugins available. Getting started To get an impression of Compass, I decided to retrofit the CSS for this website with Compass. Luckily Brandon … -
Django pro tip: if you only use the admin
If you have a project that only exposes the admin you should just use the 500/404 templates from the admin. Put this in your project’s urls.py: from django.utils.functional import curry from django.views.defaults import server_error, page_not_found handler500 = curry(server_error, template_name='admin/500.html') handler404 = curry(page_not_found, template_name='admin/404.html') I wonder why django doesn’t mention those templates in the docs … If you have other drop-in apps that need authentication (like rosetta or sentry) bare in mind that the admin doesn’t have a reusable login view so you must hook one. You should just reuse django admin’s login template. Put this in the urlpatterns (don’t forget to match it to LOGIN_URL in the settings): url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}), You might note that this is not very DRY but actually the LOGIN_URL might differ than the one in the urlpatterns (eg: you mount the django wsgi handler on a non-root path). Tagged: django, python -
Django pro tip: if you only use the admin
If you have a project that only exposes the admin you should just use the 500/404 templates from the admin. Put this in your project's urls.py: from django.utils.functional import curry from django.views.defaults import server_error, page_not_found handler500 = curry(server_error, template_name='admin/500.html') handler404 = curry(page_not_found, template_name='admin/404.html') I wonder why django doesn't mention those templates in the docs ... If you have other drop-in apps that need authentication (like rosetta or sentry) bare in mind that the admin doesn't have a reusable login view so you must hook one. You should just reuse django admin's login template. Put this in the urlpatterns (don't forget to match it to LOGIN_URL in the settings): url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}), You might note that this is not very DRY but actually the LOGIN_URL might differ than the one in the urlpatterns (eg: you mount the django wsgi handler on a non-root path).