Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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 [...] -
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 …