Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Logical Delete Support in Django
I have had a small set of functionality that I have copied to several projects and thought it was time to abstract it out as its own pluggable Django app. Thus, a new django app has been released onto the public -- django-logicaldelete. Check it out and let me know what you think! Here is the README.md copied for your reading pleasure: Django Logical Delete This is a small and simple app that I threw together to get some reuse out of something I do in nearly every project and every model I create. It's too easy for good data to get deleted and it be unrecoverable. It's also too easy to fix this by overriding the model's delete() method and just flagging records as deleted and then leveraging Django's Managers to override default behavior so that logically deleted items are not returned in querysets. There are two exceptions however, that I have found useful to this rule. In the admin I like to see everything with an indicator of whether or not it has been deleted, with the ability to filter down to just active records, (or deleted for that matter). I still think it is a valid request … -
My art cataloging app
A few months ago, I wrote an app to catalog all of my artwork. I've lost track of quite a bit of my sold art over time, which makes me teary-eyed. My cataloging app is a Django app consisting of forms that I fill out with details about each art piece, e.g. dimensions, materials, where it's located, who owns it, any stories behind it, etc. After filling out the details, I upload a variable number of photos of each piece via the app's uploader, which generates thumbnails and sticks them into Amazon S3. I didn't bother much with the front-end back then because I already had what I needed. I hated js, css, html, ajax, etc., and the app was just for myself anyway. I used it to catalog a bunch of my art, and then I forgot about it. But last month I suddenly ramped up my front-end skills. So it was a delight to pick up the app yesterday afternoon and see it in a new light. I was up until 3am coding unnecessary things like transparent gradients overlaid on text, which I never had the motivation to do before. It's still not publicly accessible, but chances are … -
Django aggregation and most popular tags
Use Django to calculate most popular tags, or any query that makes use of an aggregation function. -
First impressions on Google Wave
I was really looking forward to get a chance to play with Google Wave. If you have not heard about this, Google is experimenting with a new means of communication and collaboration (to destroy any remains of your unused time!). Watch the video of the demo from Google IO conference to get a feel for [...] -
Django's Inlineformset_factory and You
Yesterday, while trying to set up a public-facing form for a recipes app, I ran into the issue of combining Django's ModelForm (for the Recipe model) with an inline for the foreign key Ingredients. One of my astute coworkers (there are many of them) poi -
Django-filter 0.5 released!
I've just tagged and uploaded Django-filter 0.5 to PyPi. The biggest change this release brings is that the package name has been changed from `filter` to `django_filters` in order to avoid conflicts with the Python builtin `filter`. Other changes included the addition of an `initial` argument on Filters, as well as the addition of an `AllValuesFilter` which is a `ChoiceFilter` who's choices are any values currently in the DB for that field. Despite the change in package name I will not be changing the name of the project due to the overhead in moving the repository (Github doesn't set up redirects when you change a project's name) and the PyPi package. I hope everyone enjoys this new release, as a lot of it's improvements have come out of my usage on Django-filter in piano-man.As for what the future holds several people have indicated their interest in the inclusion of django-filter in Django itself as a contrib package, and for usage in the Admin as a new implementation of the `list_filter` option that is more flexible. Because of this my next work is probably going to be on implementing a custom `ModelAdmin` class that uses `FilterSets` for filtering.You can find the … -
Adventures in Django and Python – Part III
Read my previous two posts on Django and Python - Part I and Part II I've been working on a project management tool suite in Django. It's been a great side project to really experiment with Django in real-world scenarios. Forms At times I feel like I fight with newforms. In particular, it lacks the [...] Related posts:Django URL Parameter Passing and Python Strings Django and Python First Impressions – Part II Getting Started with Django and Python – First Impressions -
Requiring at least one inline FormSet
Last month I posted an article about my Improved Django FormWizard, well this month I've release a simple subclass of Django's BaseInlineFormSet that demonstrates how you can require a user to enter at least one entry in an inline formset.After updating to wadofstuff.django.forms 1.1.0 you can use the RequireOneFormSet class as the formset argument to inlineformset_factory().When the formset is -
Contributor analysis
Some of you might find it interesting to know that over 900 unique contributors have participated in Django’s development since Jan 1st, 2007, as attributed by the svn log messages. I would say the community is very healthy especially if you compare it to other well known projects: Django: 906 Pylons: 80 PyPy: 240 Linux Kernel: 4043 PostgreSQL: 150 Appache HTTP server: 118 SQLAlchemy: 36 (Contributors identified from trac tickets mentioned in svn log) Python: 428 Note that I consider anonymous or guest contributors as a single contributor, so these number can be considered conservative if the project allows anonymous contributions. -
Inlines support for Django generic views
Django's excellent Generic Views provide developers with most of what they need to get a site up and running (if they aren't using the Admin of course). The flexibility of these views is such that for most sites you don't need much else. Extending these views is also well documented and probably covers off 95% of the situations where the plain generic views fall short.In a recent project I found -
Let's talk about WSGI
Recently Armin Ronacher (whose blog you should be reading if you do anything at all involving Python and the web) has published a couple of good articles poking at the current state of WSGI, the standard interface for Python web applications. Some of his comments dovetail nicely into concerns I’ve been trying to put into words for a while now, so I’m glad he’s posting on the subject and providing some context. In short, I’ve come ... Read full entry -
Let's talk about WSGI
Recently Armin Ronacher (whose blog you should be reading if you do anything at all involving Python and the web) has published a couple of good articles poking at the current state of WSGI, the standard interface for Python web applications. Some of his comments dovetail nicely into concerns I’ve been trying to put into words for a while now, so I’m glad he’s posting on the subject and providing some context ... Read full entry -
Atualizações de segurança
Atualizações de segurança -
Atualizações de segurança
Atualizações de segurança -
Reminder: Django Training
A quick reminder: if you’re thinking of coming to me week-long Django course in Kansas City next month, today’s the last day to sign up at early-bird pricing. The price goes up by $500 tomorrow. It’s shaping up to be a blast – why not join us? -
Adding django-shorturls
Time to time I sync my blog software to the Django trunk and introduce small enhancements. Some of them visible to my readers, some of them are just for me. This time after reading Simon Willison's post on rev=canonical I decided to add short URLs to my blog as well. This is a convention to provide custom short URLs managing the mapping on your own web site. In my opinion the idea is very cool. To be completely honest: while I like the idea I am not completely sold on its implementation. For example Mark Nottingham advocates a different way to provide the same information: rel=shorturl (via Simon's post), and it sounds more logical to me. Oh, well. The first approach is easy to try: Simon coded it for Django, and Jacob Kaplan-Moss even created a full-fledged Django application out of it available both on github and on pypi — with this kind of availability I had no excuse not to try it. And rev=canonical can be used together with rel=shorturl, if I want to add it later, using the same universal django-shorturls application. So after buying lzt.me domain I armed myself with Simon's article and Jacob's git repository, and … -
Adding django-shorturls
Time to time I sync my blog software to the Django trunk and introduce small enhancements. Some of them visible to my readers, some of them are just for me. This time after reading Simon Willison’s post on rev=canonical I decided to add short URLs to my blog as well. This is a convention to provide custom short URLs managing the mapping on your own web site. In my opinion the idea is very cool. To be completely honest: while I like the idea I am not completely sold on its implementation. For example Mark Nottingham advocates a different way to provide the same information: rel=shorturl (via Simon’s post), and it sounds more logical to me. Oh, well. The first approach is easy to try: Simon coded it for Django, and Jacob Kaplan-Moss even created a full-fledged Django application out of it available both on github and on pypi — with this kind of availability I had no excuse not to try it. And rev=canonical can be used together with rel=shorturl, if I want to add it later, using the same universal django-shorturls application. So after buying lzt.me domain I armed myself with Simon’s article and Jacob’s git repository, and … -
Twitter Change
After two years or more I have finally been able to get my real name on twitter (gregnewman) and will be switching over to using that as my main twitter account. I will keep 20seven around as a pointer to gregnewman but please re-follow me there and I'll be working on re-following all my friends under that account. -
Пространства имен
Недавний релиз Джанги 1.1 принес с собой новую фичу - пространства имен урлов. Цель они призваны достичь благую, но увы их механизм пока не очень прозрачен и понятен при первом приближении. Давайте разбираться. Всё это родилось из идеи иметь несколько админок в одном проекте. И после рефакторинга админки под новые формы это стало возможным. Так же нужно было решить как разделять их урлы и главное как их реверсить по имени. Понятно, что в общем случае имена паттернов урлов разных админок будут пересекаться и однозначно преобразовать имя в урл невозможно. Тогда придумали каждому объекту SiteAdmin давать имя и это имя становилось частью названия паттерна урлов соответствующей админки. Ещё особенностью являлось то, что админка это объект и её урлы скрыты в атрибуте urls, что немного ломало классический способ инклюда урлов Джанги. Что же сделали? Добавили разделение имен урлов. Причем разделенние на 2 уровня - уровень приложения и уровень инстанса приложения. Так что за приложения и что за инстансы? Допустим у вас есть приложение foo, в котором присутствует какое-то количество урлов. Раньше хорошей практикой считалось урлы называть с префиксом имени приложения, например foo_index (или ещё каким-то уникальным идентификатором, что делала раньше админка (именем)). Теперь же. использую пространства имен, можно ограничится только index и … -
Links Desktop Teaser Screencast
In past blogs I've hinted on the fact that I'm working on a Javascript application in my spare time. It's not quite done yet, and wont be live for a few more weeks, but I do have something that I can show off. This project is best explained in the form of a screencast. This is the first screencast I have ever made and I'm not sure if I have done it right, or if my humble server will cope with serving FLV files. If the server doesn't manage to keep up, I'll probably Youtube it. -
Links Desktop Teaser Screencast
In past blogs I've hinted on the fact that I'm working on a Javascript application in my spare time. It's not quite done yet, and wont be live for a few more weeks, but I do have something that I can show off. This project is best explained in the form of a screencast. This is the first screencast I have ever made and I'm not sure if I have done it right, or if my humble server will cope with serving FLV files. If the server doesn't manage to keep up, I'll probably Youtube it. flowplayer("player_linksdesktop", "http://www.willmcgugan.com/media/flowplayer/flowplayer-3.1.2.swf"); Update: If for any reason the above player doesn't work, you can view the screencast on Youtube. The front-end uses nothing more than HTML and Javascript. This project actually represents more Javascript than I have written in all my previous career. I've written so much JS lately that I have stopped hating it – but that may just be Stockholm Syndrome. The back-end is a Django application that serves the content and the API that is used by the front-end JS. I've put together a nice simple mechanism for exposing an AJAX API in Django, that removes virtually all the boiler plate; … -
Links Desktop Teaser Screencast
In past blogs I've hinted on the fact that I'm working on a Javascript application in my spare time. It's not quite done yet, and wont be live for a few more weeks, but I do have something that I can show off. This project is best explained in the form of a screencast. This is the first screencast I have ever made and I'm not sure if I have done it right, or if my humble server will cope with serving FLV files. If the server doesn't manage to keep up, I'll probably Youtube it. Update: If for any reason the above player doesn't work, you can view the screencast on Youtube. The front-end uses nothing more than HTML and Javascript. This project actually represents more Javascript than I have written in all my previous career. I've written so much JS lately that I have stopped hating it – but that may just be Stockholm Syndrome. The back-end is a Django application that serves the content and the API that is used by the front-end JS. I've put together a nice simple mechanism for exposing an AJAX API in Django, that removes virtually all the boiler plate; the API … -
Django development workflow
Speak to 10 different Django developers and you will find 10 different ways of working. Speak to them the following year and you will no doubt find another 10 evolutions. This is just one of them, pickled in the moment. I have a longish history with python but my Django experience is much more recent, but nonetheless I think this distills a some sound practices that I've learned from others, and -
Django: Testing With File System Side Effects
Django uses unittest for testing. django.test.TestCase is a special base class for tests that adds various features1. Django testing framework takes care of creating a test database, resetting it to its initial state after each test and finally destroying it. So you don’t have to worry tests overwriting anything in your main database. But if [...] -
Собственные фильтры полей в админке Django
Пока Правильное Решение проблемы страдает в джанговском Trac'е уже два с половиной года от смены майнтейнеров и архитектурной астронавтики, мне как раз потребовалось это сегодня для Афиши. Оказывается, никого ждать не надо , и это вполне решаемо уже сейчас, хоть и с небольшим хаком процесса регистрации. Задача У нас есть моделька City, в которой страна задана целым числом -- ID региона из яндексовой геобазы. Название в модели не хранится, а при необходимости вычисляется из ID запросом в геобазу: class City(models.Model): country_region_id = models.IntegerField() def country(self): return get_name_from_geobase(self.country_region_id) Если в админке сделать фильтр по полю country_region_id, получится некрасиво: Хочется заставить админку выводить не цифры, а то, что получается из country(). FilterSpec В админке за выдачу данных фильтров овечает несколько классов, определённых в django.contrib.admin.filterspecs. Каждый класс отвечает за то, чтобы из модели и типа поля вытащить данные для фильтра и определяет правила составления запроса. Стандартные FilterSpec'и умеют строить фильтры для полей разного типа: Для ForeignKey выбираются все данные из модели, на которую он ссылается. Для полей с choice'ами фильтрами являются сами choice'ы. Для BooleanField'ов предопределённый набор из двух значений: True и False. Для всех остальных полей делается distinct-выборка всех значений, которые есть в модели. Для того, чтобы выдавать названия стран, я и …