Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Setting up Apache server for Django with mod_wsgi
Django is a very cool web development framework which comes with its own lightweight development server which is best for testing the application. But when it comes to deploying the application for the outer world, more efficient and secure web … Continue reading → -
The Installation
Please join me this month as we dive head first into building things with Python (and Django) emphasizing location information. I hope at the end of this you’re up to speed on building basic location-aware web apps and no longer … Continue reading → -
Django-ratelimit-backend ne réglera pas vos problèmes de foie, mais de rate oui…
Deuxième édition de la django app du mois précédent, encore une fois sur le fil, alors que les citrouilles continuent à ricaner dans leurs coins. Ce mois-ci c’est django-ratelimit-backend, une des multiples apps de monsieur Brutasse (qui ne doit jamais dormir pour publier autant de truc…) 1- Où on le trouve, comment on l’installe, tout ça quoi (et la doc) ? Deux possibilités pour le trouver, sur sa page github (on regrettera le choix de github et non bitbucket mais bon:) ) ou sur sa page pypi. Ce qui du coup vous permettra de l’installer de deux façon : un petit git clone bien de chez nous un simple : pip install django-ratelimit-backend La doc est dispo sur la page readthedocs du projet. Et elle est bien fournie. Une aide à l’install, un quickstart et une section pour expliquer comment modifier le critère de limitation et une référence complète du code. 2- Mais au fait, à quoi ça sert ? A empêcher les vilains méchants pas beau de crier ‘des logins ou un sort’ devant vos jolis sites webs Django. En clair, à ‘bannir’ pendant 5 minutes des IP qui auraient tentées de se logguer sur votre appli à de … -
Django Explorer - What's up?
Django Explorer - What's up? -
DIY supplies
Since moving to the country a year ago my weekends and evenings have turned into project time. I’m a cheapskate, so I’ve been buying and repairing lots of used tools and making a lot of my own parts. This means I’m constantly looking for some random specific bolt, or a piece of plastic some particular size, or something similarly specific and esoteric. So I starting maintaining a list of the places I go to when I need supplies. -
Blog Intro / November Attempt
Welcome (a little early) to November, a month where many technical authors around the internet will be attempting to write one blog post per day. I intend to join them – on something very interesting to me and useful for … Continue reading → -
Generar arxius xls amb Python III
En aquesta tercera entrega veurem com podem fer que des de la nostra aplicació Django es puguin generar i servir els arxius que hem generat amb la llibreria xlwt. La mecànica és la mateixa que la que hi ha als tutorials de Django que mostren com servir un arxiu csv o un pdf, així que per a que serveixi d'alguna cosa més us mostraré como ho feim utilitzant les generic class views incorporades a Django 1.3. El que volem fer és poder mostrar els resultats per pantalla i després poder afegir un link que ens retorni les dades que tenim en pantalla en forma d'arixu descarregable. ListView Per el nostre propòsit farem servir la classe ListView que es troba a django.views.generic La utilització més típica d'aquesta classes implica sobreescriure el mètode get_query_set de tal manera que ens retorni les dades que mostrarem a la plantilla, i, com no, indicar-li el nom de la plantilla a la qual s'han de mostrar els resultats. El codi seria quelcom semblant a això per la part de views.py class TestView(ListView): """Classe de proves per l'article""" template_name='tests/user_list.html' def get_queryset(self): """Listam tots els usuaris que no són superusuaris""" return User.objects.filter(is_superuser=False) a l'arxiu urls.py crearem la url … -
I'm available for consulting
I’m not really a freelancer for life, but I enjoy rare occasions of small “outside” gigs. I need some money boost right now, for both UploadCare (which is doing really, really fine!) and some personal problems1. So if you’re looking for someone to work with you for a couple of hours, weeks or months, I’d be happy to come forward. I’m pretty good with some programming stuff. Please write me to: v.golev@gmail.com. What I can do I’ve got my share of experience with Django. I know most of its dark corners and stumbled upon some of its crankeries. I’m writing a lot about it in my blog. I have successfully contributed a couple of lines of code into its ORM. I have teached my co-workers to use it and I have some experience debugging weird problems with South. I’ve secured the third place at DjangoDash. I’m good with Python, too. I understand metaclasses, really. And other stuff. I’ve used some spooky libraries for it, like eventlet and nltk. I’m okay with JavaScript, though not really an expert. Hey, for some reason I’ve read a lot about ECMAScript standard and know some useless weird trivia about it. I know how to … -
In a month!?
In a month!? -
Django Without the Web
One of the things I like best about Django is how easy its ORM makes it to work with databases. Too bad Django is only for web applications. Sure, you could deploy a Django app and then make use of it from a non-web application using a REST API, but that would be too awkward.But ... -
Django Without the Web
One of the things I like best about Django is how easy its ORM makes it to work with databases. Too bad Django is only for web applications. Sure, you could deploy a Django app and then make use of it from a non-web application using a REST API, but that would be too awkward.But ... -
Django Without the Web
One of the things I like best about Django is how easy its ORM makes it to work with databases. Too bad Django is only for web applications. Sure, you could deploy a Django app and then make use of it from a non-web application using a REST API, but that would be too awkward.But ... -
Drop-in celery AbortableTask replacement
If you need to report progress updates from the tasks (or you call update_state in the task) you cannot use the bundled AbortableTask from celery.contrib.abortable because it relies on status updates too. That means you’ll get race conditions if you do that. You can use revokes for aborting tasks but they don’t give you enough control and it’s not guaranteed that your tasks will stop gracefully (or stop at all). Revokes can raise SoftTimeLimitExceeded if enabled (via TERM signal) however it might be tricky to perform cleanup – if you call C extension the exception will get delayed till the call returns. See the signal module docs for what happens when you raise an exception from a signal handler (that’s what celery does). Given this, an alternative is to use redis to store the aborted task ids in a redis set. If you use the redis broker you can use this drop-in replacement: from contextlib import contextmanager import celery from celery.task.base import Task from celery.result import AsyncResult from django.conf import settings assert settings.BROKER_TRANSPORT == 'redis', "AbortableTask can only work with a 'redis' BROKER_TRANSPORT" REDIS_KEY = getattr(settings, 'ABORTABLE_REDIS_KEY', 'task-aborts') @contextmanager def client_from_pool(): connection = celery.current_app.pool.acquire() try: yield connection.default_channel.client finally: connection.release() class … -
Drop-in celery AbortableTask replacement
If you need to report progress updates from the tasks (or you call update_state in the task) you cannot use the bundled AbortableTask from celery.contrib.abortable because it relies on status updates too. That means you'll get race conditions if you do that. You can use revokes for aborting tasks but they don't give you enough control and it's not guaranteed that your tasks will stop gracefully (or stop at all). Revokes can raise SoftTimeLimitExceeded if enabled (via TERM signal) however it might be tricky to perform cleanup - if you call C extension the exception will get delayed till the call returns. See the signal module docs for what happens when you raise an exception from a signal handler (that's what celery does). Given this, an alternative is to use redis to store the aborted task ids in a redis set. If you use the redis broker you can use this drop-in replacement: from contextlib import contextmanager import celery from celery.task.base import Task from celery.result import AsyncResult from django.conf import settings assert settings.BROKER_TRANSPORT == 'redis', "AbortableTask can only work with a 'redis' BROKER_TRANSPORT" REDIS_KEY = getattr(settings, 'ABORTABLE_REDIS_KEY', 'task-aborts') @contextmanager def client_from_pool(): connection = celery.current_app.pool.acquire() try: yield connection.default_channel.client finally: connection.release() class … -
Drop-in celery AbortableTask replacement
If you need to report progress updates from the tasks (or you call update_state in the task) you cannot use the bundled AbortableTask from celery.contrib.abortable because it relies on status updates too. That means you'll get race conditions if you do that. You can use revokes for aborting tasks but they don't give you enough control and it's not guaranteed that your tasks will stop gracefully (or stop at all). Revokes can raise SoftTimeLimitExceeded if enabled (via TERM signal) however it might be tricky to perform cleanup - if you call C extension the exception will get delayed till the call returns. See the signal module docs for what happens when you raise an exception from a signal handler (that's what celery does). Given this, an alternative is to use redis to store the aborted task ids in a redis set. If you use the redis broker you can use this drop-in replacement: from contextlib import contextmanager import celery from celery.task.base import Task from celery.result import AsyncResult from django.conf import settings assert settings.BROKER_TRANSPORT == 'redis', "AbortableTask can only work with a 'redis' BROKER_TRANSPORT" REDIS_KEY = getattr(settings, 'ABORTABLE_REDIS_KEY', 'task-aborts') @contextmanager def client_from_pool(): connection = celery.current_app.pool.acquire() try: yield connection.default_channel.client finally: connection.release() class … -
Разъяснения Рассела
В недавнем посте с интервью с Джанго-разработчиками меня попросили уточнить, что имел в виду Рассел Кит-Маги, говоря про 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-технологии, просто это спецификация не обязательно лучше … -
Django Facebook 3.2 – Simple image upload and wall posts
Most of the Facebook examples are written in PHP and unfortunately for us they always seem so damn simple. I think the Python libraries should allow you to write more elegant code and the new version of Django Facebook let’s you do just that. Much of the new found simplicity comes from the facebook_required decorator. This decorator is similar to login_required, but instead checks the Facebook permissions given to you. Writing the input of a form to someone’s wall is now as simple as this: @facebook_required(scope='publish_stream') def wall_post(request): fb = get_persistent_graph(request) message = request.POST.get('message') fb.set('me/feed', message=message) messages.info(request, 'Posted the message to your wall') return next_redirect(request) Another example would be uploading some photos to a user’s timeline: @facebook_required(scope='publish_stream,user_photos') def image_upload(request): fb = get_persistent_graph(request) pictures = request.POST.getlist('pictures') for picture in pictures: fb.set('me/photos', url=picture, message='the writing is one The ' 'wall image %s' % picture) messages.info(request, 'The images have been added to your profile!') return next_redirect(request) As you can see the syntax is very straightforward. You no longer have any technical excuse against integrating Facebook. More examples and installation instructions can be found on Django Facebook’s github. Share and Enjoy: -
Using Haml in Django Projects
-
Beating Google With CouchDB, Celery and Whoosh (Part 8)
In the previous seven posts I’ve gone through all the stages in building a search engine. If you want to try and run it for yourself and tweak it to make it even better then you can. I’ve put the code up on GitHub. All I ask is that if you beat Google, you give me a credit somewhere. When you’ve downloaded the code it should prove to be quite simple to get running. First you’ll need to edit settings.py. It should work out of the box, but you should change the USER_AGENT setting to something unique. You may also want to adjust some of the other settings, such as the database connection or CouchDB urls. To set up the CouchDB views type python manage.py update_couchdb. Next, to run the celery daemon you’ll need to type the following two commands: python manage.py celeryd -Q retrieve python manage.py celeryd -Q process This sets up the daemons to monitor the two queues and process the tasks. As mentioned in a previous post two queues are needed to prevent one set of tasks from swamping the other. Next you’ll need to run the full text indexer, which can be done with python manage.py … -
Open sourcing your Django site
This is the first in series of posts, focusing on issues around open sourcing your Django site and data privacy in Django. A lot of people focus on open sourcing their Django libraries, but at Mozilla we open source the entire site. Releasing your entire source code can lead to a few problems, firstly let’s [...] -
Open sourcing your Django site
This is the first in series of posts, focusing on issues around open sourcing your Django site and data privacy in Django. A lot of people focus on open sourcing their Django libraries, but at Mozilla we open source the entire site. Releasing your entire source code can lead to a few problems, firstly let’s look at your Django settings file. Separating your settings All Django sites come with a settings.py file. This file contains some key settings that you should not be releasing to the general public, such as database configuration and the secret key. The simple way to do this is have another file that contains the secret settings and then import it from settings.py. For example include this at the bottom of your settings.py: All your sensitive settings can now kept in that local file on your server and should not be published as part of your site code. This file will override the base settings file. There are plenty of other examples on different ways to do this. You can do it in manage.py, or turn your settings.py into a folder that Python can import. Make sure that you ignore your settings_local.py file in your source … -
PEP712 - Proposal to make unittest2 more accurate
PEP712 - Proposal to make unittest2 more accurate -
Generar arxius xls amb Python II
A l'article anterior havíem fet un petit "hello world" en format xls, ara toca fer alguna cosa més de profit, així que veurem com podem generar un full de càlcul a partir de dades. En altres temps, quan donava formació ofimàtica, un dels exercicis que feia fer als alumnes quan tocava el tema de les fulles de càlcul era el de fer una taula de multiplicar, serveix per perdre la por a la cosa aquesta dels nombres i mostra els conceptes fonamentals, ara podem fer el mateix. Per no fer-ho molt complicat anem per la taula del dos #!/usr/bin/env python #-*- coding: UTF-8 -*- import xlwt fmt = xlwt.easyxf h1 = fmt('font: name Arial, height 200, bold on;') wbk = xlwt.Workbook() full = wbk.add_sheet('Taula del 2') full.write(0, 0, "Taula del 2", h1) for x in range(1, 11): full.write(x, 0, 2) full.write(x, 1, "x") full.write(x, 2, x) full.write(x, 3, "=") full.write(x, 4, xlwt.Formula('A%s*C%s' % (x+1, x+1))) wbk.save('taula.xls') Podem veure com hem creat fàcilment una fórmula per a fer la multiplicació. També podem veure com per posar les fórmules hem de tenir en compte que s'ha de fer en la notació de files i columnes pròpia de les fulles de càlcul, és … -
Fabric - A Deployment Tool for Rubyists and Pythonists Alike
If you're coming from the Ruby/Rails world, the industry standard tool for deployment is clearly Capistrano. In some cases, though, using Fabric might make more sense. If you've got a simple web app and want to try something different for deployment, have a look at Fabric. It's a terse, lightweight Python deployment tool and a good alternative to Capistrano. Most importantly, it's SUPER EASY to learn and you don't need ANY Python experience.I like how Fabric's tutorial shows a version-control-agnostic deployment pattern. The fabfile is part of the project we want to deploy, and whatever is in our project directory will be deployed. With this pattern, Fabric doesn't need any information about our version control system or repository.For example, I use git for most of my projects. If I'm running the master branch on my development machine and want to deploy master, I just run$ fab deployWhat if I want to deploy my release branch instead of the master branch? I just do the following:$ git checkout my-release-branch$ fab deploySuper easy. We can manage the code we're deploying with the tools already built in to our version control system; we don't have to implement those controls again with our deployment … -
Custom Date Formats in the Django Admin
For better or for worse, subclassing Django components to add custom functionality is a common technique. The workflow usually goes something like this:Subclass a django componentOverride a specific methodSet some custom configuration options in the methodCall super() For our Django 1.1 app, we needed to customize the behavior of a DateField so it would accept dates entered in the standard US format, MM-DD-YYYY, instead of the default behavior, YYYY-MM-DD. We'll create a new field called USADateField.First, let's add a new module to our app, fields.py:In fields.py, subclass the Datefield form, adding the MM-DD-YYY format to the tuple of default formats:class USADateFormField(forms.DateField): def __init__(self, *args, **kwargs): kwargs.update({'input_formats': ("%m-%d-%Y",)+DEFAULT_DATE_INPUT_FORMATS}) super(USADateFormField, self).__init__(*args, **kwargs)Then, subclass the django model DateField to use the new USADateFieldForm:class USADateField(models.DateField): def formfield(self, **kwargs): kwargs.update({'form_class': USADateFormField}) return super(USADateField, self).formfield(**kwargs)When you're done, your new module will look like this:Finally, import fields in your models.py module and use it! Your model might look something like this:class Appointment(models.Model): scheduled_date = USADateField(blank=True)I like approaches like this, which push logic back into the models. The functionality would be tougher to test and maintain if we wrote custom front-end code for the field.