Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Untitled
hej -
Untitled
hej -
Applying Patches in Guerrilla Way
How many times did you submit patches that have never been approved? How many times did you need to patch Django for some third-party application to work? How many times did you bumped into the wall working on real-world projects just because of some bugfixes waiting for tests or nicer solution? In all those cases, you should not panic nor run into circles, because you can still apply the existing patches in guerrilla way (or so called monkey patching).Guerrilla patches overwrite existing code not on a disk, but in memory at execution time. Everything is an object in Python. Numbers, strings, functions, methods, classes, instances, modules, etc. are objects. Each object might be conceived as an attribute of a module where it is defined. In addition, properties and methods of classes can be conceived as attributes of the class. The principle of guerrilla patching is loading a module or class which attributes need to be changed, and assigning new values to those attributes before the module or class is used. All that has to happen somewhere in the beginning of execution. Usually, I put or import guerrilla patches in models.py of some app, because all models are loaded in one … -
Design Pattern for Reusable Apps: Getting into Details
This article is an attempt to explain a technique for creating reusable and overridable apps that were partly mentioned in my last post.First of all, let's remember the presentation by James Bennett about reusable apps from DjangoCon 2008:Also the upgraded version Real World Django by Jacob Kaplan-Moss presented at PyCon 2009 should be checked.Imagine, that you have a bunch of predefined apps somewhere under your python path. Some of them have models with relations to models from other apps. You will surely want to reuse those apps for different projects. You'll want to be able to activate the necessary set of apps. Probably sometimes you'll want to use an extended version of an existing app. As shown in the presentations given above, reusable apps should allow you easy overrides. Although all apps should be either under python path directly or under a package, nothing should be set in stone. The method get_model() should be used to import models from installed apps. But apps consist of more components than just models. There are urls, views, forms, template tags, context processors, middlewares, etc.Let's have a look at a simple example. Two reusable apps could be events and venues where events would contain … -
Djapian: версия 2.2.1 - хотфиксы
Тут неожиданно для меня вскрылось, что в одном из последних релизов Djapian существенно просела производительность индексирования. Для проверки я решил найти или на худой конец намайнить какой-то большой массив данных и его проиндексировать. Подумав, решил что что-то типа википедии будет в самый раз. Быстро нашел xml дамп русской википедии и попробовал его залить в базу, а потом проиндекcировать. Для оперативности ограничился числом в 150К статей. При тестировании действительно выяснилось, что с включенными транзакциями индекс обновляется очень медленно - примерно 0.5 док/сек. Причем виноваты не сами транзакции, а то что при каждом комите происходил flush базы. Отключив flush, производительность индексирования выросла в разы - до 15-20 док/сек, что уже очень не плохой показатель. В итоге в хотфикс релизе я добавил возможность управлять транзакциями (по умолчанию они выключены) и сбросом кеша в базу через опции команды index - --transaction и --flush: --transaction - включает использование транзакций --flush - включает сброс файлового кеша при обновлении каждого документа Ещё изменил политику работы с большим числом объектов в очереди индексирования. Теперь они обрабатываются постранично и не сжирают кучу виртуальной памяти из-за нерадивых client-side курсоров БД. Это тоже могло приводить к активному свопингу и ухудшению производительности. Djapian стал ещё производительнее и лучше:-) -
Caching and signals
Adding in cached objects on signals -
Django - edytowalne komentarze
Domyślnie w django 1.0.2 w wbudowanych komentarzach nie ma możliwości edytowania komentarzy, brakowało mi tej funkcjonalności, więc postanowiłem rozszerzyć istniejące komentarze o edycje komentarzy. Zauważyłem także że nowe komentarze dodane w django 1.0 nie posiadają funkcji uzupełniania danych użytkownika(jeżeli jest zalogowany), podczas dodawania komentarza mimo iż model Comment jest powiązany teraz z modelem User z aplikacji auth. Rozszerzyłem więc komentarze o tą funkcjonalność. Po dyskusji na ten temat na kanale #django-pl został utworzony ticket na stronie projektu Django z tym związany. Zależało mi aby używać tego samego mechanizmu zarówno do edycji komentarzy przez zalogowanych użytkowników jak i przy dodawaniu nowych komentarzy. Aby to zrealizować wystarczy stworzyć własnego tag'a który będzie używać klasy po dziedziczonej po klasie RenderCommentFormNode, tag'a ten będzie używany do generowania formularza dodawania lub edycji komentarza, zamiast domyślnego tag'a. from django.contrib.comments.templatetags.comments import RenderCommentFormNode class EditRenderCommentFormNode(RenderCommentFormNode): """Render the comment form directly""" def get_form(self, context): ctype, object_pk = self.get_target_ctype_pk(context) if object_pk: comment = context.get('comment', None) if comment: initial = dict(name=comment.user_name, email=comment.user_email, url=comment.user_url, comment=comment.comment ) else: request = context['request'] initial = dict(name=request.user.get_full_name() or request.user.username, email=request.user.email, ) return EditCommentForm(target_object=ctype.get_object_for_this_type(pk=object_pk), initial=initial) else: return None @register.tag def render_edit_comment_form(parser, token): """ Render the comment form (as returned by ``{% render_edit_comment_form %}``) through the ``comments/form.html`` template. … -
Easily Code Templates for iPhone in Django
Sometimes, you want to create a custom page for an iPhone or other small phone browser but don't want a custom URL or view for it. This can easily be handled by using the mini_render_to_response function. This works equally well for any browser that has very little real-estate. It's based on the mini-detector middleware which can be downloaded here here. mini_render_to_response is a drop in replacement to render_to_response. When using mini_render_to_response it will try to load a version of your template with mini at the end. For example "home_mini.html" instead of "home.html". If it doesn't find the _mini version it falls back to the regular "home.html" version of your template. The middleware automatically detects if it's a small browser and the function uses this information to attempt to load the mini version of the page. Using this method you can use the same URL and same view to serve the iPhone page. This is not ideal for every type of site. For example, if the mini template only uses a very small portion of what the view does, you might as well code a different view or at least put a bunch of if conditions to optimize the view. -
Djapian: версия 2.2
Очередной релиз Djapian подоспел. Коротко расскажу о нововведениях: Добавлена работа с транзакциями Xapian при обновлении индекса. Теперь, если в процессе индексирования какого-то объекта, произойдет ошибка, то он не оставить никаких следов в индексе. Чуть-чуть просела производительность индексирования. Добавлена возможность использовать X объекты для фильтрации результатов. X объект - это аналог django.db.models.Q объектов, которые позволяют писать комплексные фильтры. Поддерживаются операторы И (&), ИЛИ (|) и отрицания(~). Пример: from djapian import X result_set = Article.indexer.search('foobar')\ .filter(X(type='news') | (X(type='article') & X(tag='featured'))) У каждого результата поиска появился атрибут tags с полями данного документа, которые хранятся непосредственно в индексе. В некоторых случаях позволяет не вытягивать из базы данных сам объект, используя в отрисовке выдачи элементы из tags. Исправлен баг с индексированием значений чисел с плавающей точкой. В следующем релизе, я надеюсь, появится выдача снипетов с искомыми термами и дженериковая инфраструктура для простой интеграции поиска в приложении - формы, вьюхи шаблонные теги. -
TrenchMice gets snuffed
We pulled the plug on TrenchMice yesterday. It had plateaued in traffic, and wasn’t able to break through to the next level of readership. New features or different marketing efforts resulted in only temporary traffic spikes, followed by a return to the plateau. The cost for the servers wouldn’t be a large financial drain in and [...] -
Top 5 Django IDEs
I’ve seen a lot of people out there looking for a good IDE for doing Django work. Personally I’m a pydev guy. I have been using Eclipse for so long for everything else it’s very natural to keep on that path. However there are definitely other alternatives out there. Here is a list of other [...] -
Untitled
hej -
Convenciones de aplicaciones reusables en Django
Este post es una traducción al español de Django reusable apps conventions, escrito por Eric Holscher. Trata de servir como punto de referencia sobre las mejores prácticas y convenciones en Django. -
Django, Malnutrition, SMS and Kenya
How I ended up doing one of most interesting and important projects I've been involved with. -
Dynamic Django queries (or why kwargs is your friend)
A very easy way to dynamically build queries in Django is to use Python kwargs (keyword arguments). Let’s say we have a model that looks something like this: class Entry( models.Model ): user = models.ForeignKey( User, related_name = 'entries' ) category = models.ForeignKey( Category, related_name = 'entries' ) title = models.CharField( max_length = 64 ) […] -
Arquivos do Mini curso de Django disponibilizados
No dia 24 de abril de 2009, no SENAC em Natal/RN, ocorreu o FLISOL. Neste evento, eu ministrei um mini curso de django. Então estou disponibilizando tanto os arquivos_mini_curso desenvolvido durante o curso, como os slides. Mini curso introdutório ao DjangoView more presentations from vbmendes. -
Presenting: django-simple-wiki
It was bothering me that all the wikis I tried, all had either errors, feature lacks, too many dependencies or were simply unmaintained. So I decided to create yet another one. Curiously, the third hit when googling ‘django wiki’ is Create a wiki in 20 minutes. Luckily that’s not really true, so all the PHP guys and MediaWiki can continue breathing. This took me several days. Google Code project page Demo website Hierarchy and relations First of all, as in the Trac wiki system, I chose to create a system for hierarchy, meaning that it’s possible to create an article and then create sub-articles. The hierarchy does not support multiple inheritance, because it needs to be basis for the permission system. That’s where the relation system comes in place: All articles can contain symmetrical relations to any other articles in the hierarchy. Parsing Python and Django supports Markdown pretty much out of the box, so it’s an obvious choice to use this for parsing. The HTML features of normal Markdown have been removed, so all HTML is escaped in django-simple-wiki. And parsing is static, so every time a revision is created, the contents are passed and stored. This means that … -
Database independent Django queries: COALESCE vs. NVL, IFNULL, ISNULL
Most of the time, it is not necessary to write raw SQL from Django. However, there are cases where it can’t be avoided. One common pattern in SQL that always comes up is to check two fields and get the value of the first non-NULL field. In Oracle I’ve used NVL and in MySQL I’ve […] -
Django powered AJAX Chat – Part 1
In the neverending adventure of developing our game website we have stumbled upon the “live chat” rock. I’ve seen some interesting things here using a pure django implementation for chat and there using django and comet for chat. I browsed the first one and I didn’t like it too much, and the comet implementation is clearly out of the picture for now. We have to finish this project in 4 to 6 weeks and we cannot take the risk of messing around with yet another technology (although I will keep this django+comet link bookmarked for future use). So I decided to make one quick and dirty chat app myself. I had a very clear idea of how I wanted to implement the chat, it is really simple after all: Client loads HTML + Javascript Client queries the Server every X seconds for new messages Server responds messages serialized in JSON format Client attaches new messages to the message box This does fail regarding performance, so I did a little bit of reading regarding the matter of creating html based chat applications. It turns out there’s this Comet model to allow persistent or long lived HTTP requests. The idea behind that … -
New Django Rpx
Rpx is a great sig in center. With RPX users can login using their facebook, openid, google, myspace, aol, yahoo, blogger, flickr and some other types of accounts. Some days ago I looked at django-rpx wich is pretty good but doesn´t cover som interesting rpx like mapping. Mapping allows a user to have multiple openids [...] -
robots.txt via Django, in one line
A significant difference between developing Django sites versus static-HTML-based approaches (among which I count PHP and the like) is that static files, aka "media", live in a dedicated spot. Sometimes you need a piece of static content to be available at a specific URL outside your media root. robots.txt for example. This can be done in pure Django (i.e. without even touching your Apache configuration), and is especially nice if your robots.txt content is short. The example below serves a basic "keep out" configuration. At the top of your root URLconf, add this import: from django.http import HttpResponse and below, among your list of URL patterns, add: (r'^robots\.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /*", mimetype="text/plain")) The lambda r bit is a concise way of creating a function object which accepts (and discards) the HttpRequest object that Django provides to all views. The "mimetype" setting (aka "content_type" in Django 1.0) is important too, because robots don't like text/html. So there you have it -- a classic one-line (plus an import) robots.txt solution. -
Festival Latino-americano de Instalação de Software Livre
Venho através deste convidá-los ao FLISOL/RN 2009. O Festival Latino-americano de Instalação de Software Livre do RN irá acontecer no dia 25 de abril de 2009 no SENAC em Natal. No evento eu irei ministrar um mini-curso introdutório ao framework Django das 14:00 as 17:00 horas, cujo objetivo é formar pessoas com conhecimentos básicos acerca [...] -
GSoC: Implementation of additional i18n features on Django
Here you have my proposal for Google Summer of Code 2009. It was approved previous week, and I'll be working on it during this summer. The problemWhile Django provides an amazing system to translate texts, and displays localized dates in some parts of the admin; it has many data that could be internationalized, not it's not yet. The information that developers should be able to localize/translate is mainly: All dates and related information (times, calendars...) All numbers (mainly decimal ones) Texts (and any data in general) saved on the database More information on these issues can be found in the following blog post and this ticket: http://vaig.be/2008/07/django-i18n-status.html http://code.djangoproject.com/ticket/7980 Proposal The proposed solution for improving Django i18n includes several different tasks. Those tasks are: Import locale data from CLDR Apply i18n to Django dates and times Apply i18n to Django numbers Allow translating content on the database Fix already reported bug about i18n Next are the details for every task. Note that all those specifications are subject to change, according to discussions with the mentor of the project, Django core developers team, and the main Django community. Importing locale data The main repository of locale data is the Common Locale Data … -
Django Local Server Slow?
Downgrading to a Vista machine, each HTTP request on my local django (development) webserver was taking more over a second to respond, which forced me to look for solutions. Here is a quick compilation of answers I found and what worked for me:My DB was on a remote machine, so first I copied the DB to my desktop. Result: Bad idea, it wasn't the bottleneck. "Change localhost to 127.0.0.1". Result: Didn't help me, but perhaps it would resolve a possible DNS conflict / misconfiguration. "Disable your virus scanner". It makes perfect sense as virus scanners present further processing for every HTTP request. It apprently has helped many, but did nothing for me. "Remove '::1 localhost' from your hosts file'. On windows its located "C:\windows\system32\drivers\etc\hosts". Result: Success! Everything was fast again.Other solutions I didn't try include:Stop using VistaUpgrade your Vista to the latest service packOn Firefox "switch off ipv6". -
Run Django Tests from TextMate
It would be cool to be able to run my Django tests from within TextMate. Update: this version will run just the tests from the active file, if there are any. Otherwise, it runs all of the tests in the whole project. Here is a Command to do just that: {% highlight ruby linenos %} #! /usr/bin/env ruby command = [ENV["TM_PYTHON"] || "python", "-u", "#{ENV['TM_PROJECT_DIRECTORY']}/manage.py", "test", "--noinput"] File.open(ENV['TM_FILEPATH']) do |f| f.readlines.each do |line| if line =~ /class (.*)\(.*TestCase\):/ test_case = $1 app_name = ENV['TM_FILEPATH'].split(ENV['TM_PROJECT_DIRECTORY'])[1].split('/')[1] test_name = "#{app_name}.#{test_case}" command << test_name end end end require ENV["TM_SUPPORT_PATH"] + "/lib/tm/executor" ENV["PYTHONPATH"] = ENV["TM_BUNDLE_SUPPORT"] + (ENV.has_key?("PYTHONPATH") ? ":" + ENV["PYTHONPATH"] : "") TextMate::Executor.run(command) do |str, type| if type == :err if str =~ /\A[\.EF]*\Z/ str.gsub!(/(\.)/, "\1") str.gsub!(/(E|F)/, "\1") str + "\n" elsif str =~ /\A(FAILED.*)\Z/ "#{htmlize $1}\n" elsif str =~ /\A(OK.*)\Z/ "#{htmlize $1}\n" elsif str =~ /^(\s+)File "(.+)", line (\d+), in (.*)/ indent = $1 file = $2 line = $3 method = $4 indent += " " if file.sub!(/^\"(.*)\"/,"\1") url = "&url=file://" + e_url(file) display_name = file.split('/').last "#{htmlize(indent)}" + (method ? "method #{method}" : "at top level") + " in #{display_name} at line #{line}\n" end end end {% endhighlight %}