Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Portuguese Python User Group
I've created a Python User Group in Portugal. The idea is to join people who enjoy programming in Python. No membership is required to participate, experienced programmers and absolute beginners are both welcome! You can visit the site or follow us on Twitter. -
Review of Django 1.0 Template Development
Initially when Packt Publishing sent this ebook Django 1.0 Template Development by Scott Newman to review, I did what any self respecting Django entreprenuer with 3 project down his pants would do. I skimmed through the book to the code sections and read through the code and read about 10 lines after that. The blink that I obtained reading the book this way was not too good and I felt some of the explanation in certain sections lacking. BAD mistake! This book SHOULD NOT and I repeat SHOULD NOT be read that way. After I hunkered down and read the book cover to cover, it was then I really began to like it. So now, Django projects later, I wish that I read the book the right way the first time, because it has given me so many ideas to improve my Django code. So my advice, get this book, read it cover to cover and then revisit, bookmark or underline sections that you will revisit later. This way I found out was the way to get the maximum benefit out of this great Django reference. I really like reading technical books that know how to put forth advanced concepts … -
Django 1.1 Talk Text
This is the text from the Django 1.1 talk I gave on Friday May 15 at Algonquin College for FOSSLC's Geocamp/Summercamp 2009. I have tried to format this in a way that is well suited to skimming and easier to access from the web than reading the original slides. If you find this useful, please let me know. -
Seattle Django Users’ group
A Seattle Django Users’ group is forming. Here’s the official announcement: —— Forwarded Message From: Brian Gershon Reply-To: A group of Python users in Seattle Date: Mon, 4 May 2009 13:57:35 -0700 To: seattle-python, plone_seattle Subject: New Seattle Django User Group meeting June 2 (Save the Date) This is an invite for the newly forming [...] -
Виджет на морде
Как же сложно писать о том, что заняло у тебя столько сил и эмоций. Очень многое хочется рассказать, но почему-то трудно сформулировать и четко выразить мысль. Наверно это эмоции и неравнодушие так проявляются. Но я всё равно попробую. Обновленная Яндекс.Афиша работает на Джанге. Вот уже третий месяц как. Запустили мы её прямо в канун пятницы тринадцатого в марте! Проект получился большой, со своими особенностями. Расскажу вам про процесс разработки с допустимой детальностью. Глобальная цель была - обновить движок Яндекс.Афиши, переписав его на Django. Что да как Распил кода КВИ Ни для кого не секрет, что сервис "Куда все идут" один из сервисов Яндекса написанных на Джанге. Долгое время он был дополнением к Афише и добавлял социальный фан для пользователей. Ему и было суждено дать начало новой Афише. Мы резонно решили, что, переписывая Афишу на Джанге, нужно опираться уже на имеющийся code base КВИ. Но при разработке КВИ никто и не думал, что в последствие этот код может быть использован в другом проекте, поэтому процесс отделения и обобщения имеющихся наработок занял много времени и сил. Тогда мы впервые начали использовать наследование моделей в Джанге, т.к. многие наши сущности можно было строго разделить на общие части и какие-то сервисо-зависимые надстройки. Это кстати … -
Bericht vom dritten Django-UserGroup Treffen in Hamburg
Am Dienstag, den 12.05.2009, hat sich die Django-UserGroup Hamburg zum dritten Mal getroffen. Dank der CoreMedia AG hatten wir diesmal einen Raum mit Beamer und W-Lan zur Verfügung, so dass wir eine Reihe kurzer Vorträge halten bzw. hören konnten. Wenn wir uns nicht verzählt haben waren 17 Djangonauten anwesend. Die Vorträge orientierten sich am Format Lightning Talks, so dass jeder der wollte 5 bis 10 Minuten Zeit bekam zu einem Thema seiner Wahl etwas zu erzählen. Folgende Vorträge gab es: Django + PyAMF von @mohlendo RESTful Django am Beispiel routeconverter.com von @cpesch Django-Caching in der Praxis von @_arne [Slides] Deployment mit Fabric von @bracki [Fabric] Vorstellung von kogakure.de von @kogakure Spam-Deathmatch von @toadle [Blog-Eintrag] Des Weiteren haben wir auf dem Treffen entschieden ein Repository auf GitHub anzulegen, in dem wir Slides und Code allen zugänglich machen können. Das Master-Respository ist hier zu finden: http://github.com/mohlendo/dughh/ und zusätzlich gibt es die Domain dughh.de, welche zur Zeit einfach auf das Repository umgeleitet wird. Ausblick Das nächste Treffen wird in ca. 2 Monaten stattfinden, ankündigen werden wir das Treffen rechtzeitig hier im Blog, unter dughh.de in der Django-Gruppe auf Xing, in den News auf django-de.org und auf der django-de GoogleGroup. Jeder der schon vorab … -
¿Cómo agregar editores HTML al django admin?
Django trae una feature que es simplemente genial: interfaz administrativa generada automáticamente como parte del framework. Esta interfaz ahorra mucho tiempo de desarrollo el cual podés usar para dejar mas bonita tu aplicación Django. Esta interfaz se puede customizar hasta … Continue reading → -
¿Cómo agregar editores HTML al django admin?
Django trae una feature que es simplemente genial: interfaz administrativa generada automáticamente como parte del framework. Esta interfaz ahorra mucho tiempo de desarrollo el cual podés usar para dejar mas bonita tu aplicación Django. Esta interfaz se puede customizar hasta cierto punto pero desgraciadamente no trae un editor de HTML WYSIWYGbonito de esos que se usan para poner un post en un blog o foro que permiten que alguien sin conocimientos de HTML pueda dar estilo a lo que escribe de manera sencilla y parecido a una suite ofimática. Para esto tenemos disponibles una gran cantidad de editores hechos en javascriptlibres y gratuitos disponibles en la red. En este caso usaremos mi preferido TinyMCE el cual es muy popular y es el editor por defecto de Wordpress. Este editor funciona con los campos definidos como TextField Paso 1: Bajar TinyMCE Paso 2. En un proyecto de Django agregar la carpeta de TinyMCE a la locación donde guarden su javascript Paso 3. Agregar el siguiente archivo para configurar el aspecto dentro de una carpeta llamada editores (o como quieran ponerle) en la misma ubicación del paso 2. Paso 4. En el admin.py de la aplicación en la cual desean tener el … -
jj: dojo.beer(3) wrap up
jj: dojo.beer(3) wrap up -
Autoryzacja przez clickpass kontra rpx
RPX jest podobną usługą do clickpass - upraszcza logowanie z systemów gdzie użytkownicy już mają konta. Zasada działania jest bardzo podobna. System ten również opiera się o OpenID. Istnieje także implementacja rpx dla django - http://code.google.com/p/django-newrpx/ rpx wydaje się lepsze od clickpass, z tego względu że użytkownik dużo łatwiej się może zalogować, praktycznie po autoryzacji w systemie zewnętrznym jest już zalogowany, przy clickpass po autoryzacji pokazuje się formularz rejestracyjny z wypełnionymi danymi( typu: email, opcjonalnie imię, nazwisko) i trzeba ręcznie wpisać nazwę użytkownika jaki będzie utworzony. W rpx się tego nie robi, wszystko się dzieje z automatu, nazwa użytkownika jest z automatu przekazywana(z systemu w którym wcześniej odbyła się autoryzacja) do backend’u autoryzacji który sam tworzy nowego użytkownika i go loguje. Przy następnym logowaniu backend sprawdza czy login użytkownika(przekazany np. z google accounts) istnieje już i go loguje. W jednym i drugim przypadku logowanie to tak naprawdę 2-3 kliknięcia myszą. Teraz na temat samej implementacji rpx w django Pakiet django-newrpx był dosyć z bugowany – parę drobnych bugów w kodzie, udało mi się wszystko popoprawiać i wysłać pacha do autora. W django-newrpx w przeciwieństwie do django-clickpass nie ma zaimplementowanego tzn "account merge"(samo rpx obsługuje tą opcje- Mapping API) jest to … -
Simple Django Commenting System with Ajax
I have begun incorporating ajax techniques using the script.aculo.us and prototype libraries and thought I'd share a basic example that combines ajax with django. The snippets shown here have been taken and simplified for the purpose of this article. Making good use of ajax can significantly improve the usability of a website as it introduces a more user friendly experience. Granted sites can go overboard especially with all the effects. In this article I thought I would demonstrate a simple commenting system that uses the Prototype library to create asynchronous calls necessary for submitting a form while remaining integrated with the django framework. Model Lets start with the model describing the commenting class. It contains the basics for user submitted comments, name, email, website, content, reference, etc. The key represents an attribute for retrieving a set of comments. For example, combining the comments with articles the key could store the article's title or slug. When an article is loaded the comments can easily be retrieved based on their title. The name, email and website contain information on the user submitting a comment. The email and website fields are optional in this case. The text refers to the comment being submitted … -
Job board added
As promised the site now has a job board -
Customized comment notifications from Django
I recently had to implement a way to send notifications (using the excellent django-notification app developed by James Tauber) to users whose content is commented on in my Django web app. However, I wanted the owner/creator of the original content to get a more customized notification message. For example, if the model instance being commented [...] -
Switching from PHP to Django: The Result
-
Selling clients on Django
So right up front let me just say that I love Django. This should come as no surprise to anyone who has been to my site. I think its a great framework and I really enjoy working with it. That being said all too often my clients look like a deer in headlights when I [...] -
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 [...]