Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django almost spaceless template tag
Django has a {{ spaceless }} tag that's a little too greedy for my taste. Removing all whitespace between HTML tags can actually change what the browser renders, so here's a less greedy variant. However, it removes all whitespace, not just between tags, so if you use the pre tag for example you don't want this. class AlmostSpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): return self.remove_whitespace(self.nodelist.render(context).strip()) def remove_whitespace(self, value): value = re.sub(r'\n', ' ', value) value = re.sub(r'\s+', ' ', value) return value @register.tag(name='almostspaceless') def spaceless(parser, token): """ Remove all whitespace except for one space from content """ nodelist = parser.parse(('endalmostspaceless',)) parser.delete_first_token() return AlmostSpacelessNode(nodelist) -
Django almost spaceless template tag
Django has a {{ spaceless }} tag that's a little too greedy for my taste. Removing all whitespace between HTML tags can actually change what the browser renders, so here's a less greedy variant. However, it removes all whitespace, not just between tags, so if you use the pre tag for example you don't want this. Raw class AlmostSpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): return self.remove_whitespace(self.nodelist.render(context).strip()) def remove_whitespace(self, value): value = re.sub(r'\n', ' ', value) value = re.sub(r'\s+', ' ', value) return value @register.tag(name='almostspaceless') def spaceless(parser, token): """ Remove all whitespace except for one space from content """ nodelist = parser.parse(('endalmostspaceless',)) parser.delete_first_token() return AlmostSpacelessNode(nodelist) -
Django almost spaceless template tag
Django has a {{ spaceless }} tag that's a little too greedy for my taste. Removing all whitespace between HTML tags can actually change what the browser renders, so here's a less greedy variant. However, it removes all whitespace, not just between tags, so if you use the pre tag for example you don't want this. Raw class AlmostSpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): return self.remove_whitespace(self.nodelist.render(context).strip()) def remove_whitespace(self, value): value = re.sub(r'\n', ' ', value) value = re.sub(r'\s+', ' ', value) return value @register.tag(name='almostspaceless') def spaceless(parser, token): """ Remove all whitespace except for one space from content """ nodelist = parser.parse(('endalmostspaceless',)) parser.delete_first_token() return AlmostSpacelessNode(nodelist) -
Django Commit Number Two
Team Django is on fire. Commit number two: https://github.com/django/django/commit/5ce6a7cea25ac8e616fa6bd132ee341a240aad6fSecond Team Django commitAnother documentation fix, this time concerning the first introductory tutorial which needed to be updated to be inline with the new default project template. Weirdly enough the request was committed by the same developer who committed my first pull request. Even weirder it appears this time it was he who forgot to wrap the text after he changed my note on the BASE_DIR variable. Well that is two contributions down, many more to go. I think I will turn to the list the team has compiled and attempt to help the team proceed with resolving those tickets. Though I probably should go back through the rest of the tutorials and determine if there are any other areas I could spruce up. -
Administer WordPress using Django's Admin
Administer WordPress using Django's Admin -
First commit!
https://github.com/django/django/commit/af2bb174708e662c59f43f3f8df79e4de7411451Follow the link above to Team Django's first commit! Yes, it was a merge and edit of my pull request, but that doesn't matter. Team Django is officially on the board! Well, it does matter somewhat. I swore I wrapped the text at 80 characters, but obviously I did not. Thankfully a fellow contributor was kind enough fix this overlook, and commit the request for me. Team Django's first accepted contributionAfterwards I went to check on my initial request and see if I forgot to wrap the text there. Sadly, yes I did. So I went back in and edited the file, committed the edit, then pushed the commit. Since this is a pull request, and the Django community does not need to nor wants to read every single commit I make, I had to go in and edit the commit message history. First you type in 'git rebase -i HEAD~#' where # is the number of commit messages you wish to change. Then an editor opens and you select to either pick, edit, or squash a commit.Then save and exit the editor, and you will see another screen listing the commits. Save and exit this screen too. Now time to … -
First Contribution Update
* Update 1: Including the mailing list discussion.* Update 2: Added section on new pull requestWell that ended quickly. It seems there is a discrepancy between the TIME_ZONE default in the project and in django.conf.global_settings. After a short discussion with a fellow contributor, I removed my change to the settings reference document, and have posted a question to the mailing list about the discrepancy. I did eventually send out another pull request, and closed the initial, after some strange commits appeared in my initial request. I probably just messed up while attempting to rebase the branch so I could squash a few of my previous commits. You can find the new request at https://github.com/django/django/pull/711. The mailing list actually led to a resolution of a sorts to the question. The post can be found here. It appears the TIME_ZONE was set to 'America/Chicago' during the initial developments of Django. I guess this is due to the framework being developed in the American Midwest. However the developers have decided the best practice is to set TIME_ZONE to 'UTC' to handle time. Keeping 'America/Chicago' as the global default allows older applications to remain compatible when upgrading to newer versions of Django, while new apps will … -
First contribution to Django
Squashed? Earlier this morning I began the process of trying to address the ticket #19536, which a staff user without has_add_permissions is unable to see any object-tools buttons, when in reality only the add button should be hidden. The proposed patch involves a simple switching of two lines of the Django template language within change_list.hml. While the patch does fix the hiding of all object-tools buttons, it also adds in an empty <ul> element where the add button would be. So says a core developer on the ticket's post. However I was having issues recreating the bug, which I will address shortly, so I am unable to verify this assessment.Being currently unable to replicate the issue, I can only speculate that the bug could also be in changelist.css, but I was having severe issues loading the admin css files in my hastily built Django application. As I had previously written about, I went through the Django tutorial and created a basic polls application. After that I fiddled around with the application a bit more, and at some point injected an error somewhere in the code. When I visit the admin site none of the styling shows, only plain old misaligned … -
Bug Exercises
This bugs meFor today's post I am following going through Chapter 6 of the Teaching Open Source textbook, and attempting to complete the included exercises.In the Django community the oldest bug currently open is ticket #25. This ticket was opened eight years ago by Adrian Holovarty (one of the creators of Django). The ticket began life as a feature request/bug to allow "use_filter_interface on non-multiple select boxes" which was eventually changed to adding a filtering interface on ForeignKey <select> boxes. Adrian supplied the following summary of the ticket:Select boxes are a pain, and slow, to deal with when there are a lot of values to select from. (Example: datelines on news stories). There should be a generator option, use_filter_interface, available on select boxes. It would add an <input type="text"> next to the select box and allow users to filter the select box that way.This would make data entry quicker, because folks could just paste in the dateline they want, and it'd be selected for them (assuming it's been entered as a dateline in the system).The ticket initially was to be completed for Django version 1.1, but steadily slipped as the need for the work was questioned, until ultimately a design decision … -
Restricting django to one user concurrent session only
Here's the tiny code that helps you avoid multiple users logged using the same account. # -*- coding: utf-8 -* from django.conf import settings from django.core.cache import cache, get_cache from django.utils.importlib import import_module class UserRestrictMiddleware(object): def process_request(self, request): """ Checks if different session exists for user and deletes -
Committers Needed For Tastypie & Haystack
Committers Needed For Tastypie & Haystack -
Hardening Your Web Server’s SSL Ciphers
There are many wordy articles on configuring your web server’s TLS ciphers. This is not one of them. Instead I will share a configuration which is both compatible enough for today’s needs and scores a straight “A” on Qualys’s SSL Server Test. Disclaimer: I’m updating this post continually in order to represent what I consider the best practice in the moment – there are way too many dangerously outdated articles about TLS-deployment out there already. Therefore it may be a good idea to check back from time to time because the crypto landscape is changing pretty quickly at the moment. You can follow me on Twitter to get notified about noteworthy changes. If you find any factual problems, please reach out to me immediately and I will fix it ASAP. Rationale If you configure a web server’s TLS configuration, you have primarily to take care of three things: disable SSL 2.0, and – if you can afford it – SSL 3.0 (Internet Explorer 6 is the last remaining reason to keep it around; you can’t have elliptic curve crypto with SSL 3.0 and downgrade attacks exist), disable TLS 1.0 compression (CRIME), disable weak ciphers (DES, RC4), prefer modern ciphers (AES), … -
Team Django update
Bug JuiceTomorrow Team Django is responsible for presenting a set of contributions we plan on making towards the open source project, Django. With the help of Django's ticket tracker the team was able to break down the possible contributions into four general types: documentation creation or fixing, unit test creation, bug fixing, or feature request. After perusing the ticket tracker over the course of the past few weeks, we have narrowed down the list of potential contributions to the set of planned contributions found here. In order to arrive at the final list, each team member was required to select at least one outstanding ticket, and detail how they planned to resolve the ticket's issue. If things go smoothly we plan to address more tickets, but initially we thought it was wise to keep the list small and manageable.I have chosen to tackle ticket #9532 which is a new feature request. Currently Django users can specify the maximum number of forms of a particular type to be displayed. However the user can not designate the minimum number of forms to be displayed. The user requesting the feature offered the following use case: "I want an address formset that displays all addresses that have … -
Testejar app Django
Una de les coses que me fan més peresa quan he de crear una nova aplicació Django és tenir que configurar una aplicació per poder-ne fer els tests quan sols estàs fent un mòdul que serà reutilitzable per a altres aplicacions. Una vegada s'ha fet l'aplicació el que voldria és poder-ho testejar sense tenir que configurar tot un projecte i no acabava de trobar-ho del tot fins que vaig veure la manera en que ho feia Brutasse a django-password-reset. L'aproximació de Brutasse és tenir una projecte Django dins la mateixa applicació que s'està creant, de manera que aquesta es pot testejar sense tenir que crear el projecte sencer i controlant a la mateixa vegada els settings que estam fent servir. És a dir, just el que estava cercant. Aquests darrers dies he estat treballant un poc en una branca de django-mailer2 i l'he refactoritzat per seguir la seva idea a l'hora de fer els unit tests. Una vegada creat el [paquet python] (http://guide.python-distribute.org/index.html) el que es fa es crear un arxiu que serà l'executable que iniciarà els tests. runtests.py per no ser massa originals Creant l'executable Aquí el que fem és configurar l'aplicació com se fos una execució desatesa de … -
Attending FOSDEM 2013
For the 6th consecutive year, I am attending FOSDEM! That’s right, this time I am boarding from Lisbon and I will arrive in Brussels in time for the traditional and epic beer event. I am not giving any talks this year so I will have plenty of time to enjoy the event and all the nice things the city has to offer. Of course, I love a good chat about Free Software over a beer so if you want to know more about some of my projects, let me know. See in Brussels! -
Redis PubSub wrapper for Python
Recently I've found that there's no reasonable simple and useful Redis pub sub examples around. So, here is my dead simple wrapper how to implement it without any unnecessary overhead. -
Taking up the gauntlet: defense of Django
I'm taking up the gauntlet. A gauntlet that has been thrown down with considerable force and eloquence by my colleague Gijs on his new weblog in a post called Django is just an API. The title comes from a similar article about Rails being just an API. Transitioning to modern times We have a big stack of Django apps (called Lizard, 50+ apps) and some 40 sites. I have a quite good description of how it all fits together in a previous post where I told about a pyramid experiment. Summary: we use all of Django (models, templates, views, staticfiles, etc). Reusable apps. Two big core apps that everything inherits from for basic user interface and basic map handling. To quote Gijs: ... we are currently transitioning to API-based de-coupling of back-end and front-end. In other words: a client-side user interface which talks to an API for data. This web app should just be one of the api-consuming clients, not privileged in any way compared to an iPhone or Android native client. So: Django is relegated to the dustbin of history and is mercifully allowed to serve up an API (probably until it is replaced in due course with some … -
Churning behind the scenes
At the moment there are several Evennia projects churning along behind the scenes, none of which I've yet gotten to the point of pushing into a finished state. Apart from bug fixes and other minor things happening, these are the main updates in the pipeline at the moment.Multiple Characters per Player/SessionEvennia has for a long time enforced a clean separation between the Player and the Character. It's a much appreciated feature among our users. The Player is "you", the human playing the game. It knows your password, eventual user profile etc. The Character is your avatar in-game. This setup makes it easy for a Player to have many characters, and to "puppet" characters - all you need to do is "disconnect" the Player object from the Character object, then connect to another Character object (assuming you are allowed to puppet that object, obviously). So far so good. What Evennia currently doesn't support is being logged in with different client sessions to the same Player/account while puppeting multiple characters at the same time. Currently multiple client sessions may log into the same Player account, but they will then all just act as separate views of the same action (all will see the same output, you can … -
Virtualenvwrapper for your production server
Virtualenvwrapper is a popular tool for the Django developer who works on several different projects at the same time. I have not seen much on the web about how this tool can also simplify your production setup, in particular Fabric and crontab. So here's a quick writeup... -
Taking up the gauntlet: defense of Django
I'm taking up the gauntlet. A gauntlet that has been thrown down with considerable force and eloquence by my colleague Gijs on his new weblog in a post called Django is just an API. The title comes from a similar article about Rails being just an API. Transitioning to modern times We have a big stack of Django apps (called Lizard, 50+ apps) and some 40 sites. I have a quite good description of how it all fits together in a previous post where I told about a pyramid experiment. Summary: we use all of Django (models, templates, views, staticfiles, etc). Reusable apps. Two big core apps that everything inherits from for basic user interface and basic map handling. To quote Gijs: ... we are currently transitioning to API-based de-coupling of back-end and front-end. In other words: a client-side user interface which talks to an API for data. This web app should just be one of the api-consuming clients, not privileged in any way compared to an iPhone or Android native client. So: Django is relegated to the dustbin of history and is mercifully allowed to serve up an API (probably until it is replaced in due course with some … -
Virtualenvwrapper for your production server
Virtualenvwrapper is a popular tool for the Django developer who works on several different projects at the same time. I have not seen much on the web about how this tool can also simplify your production setup, in particular Fabric and crontab. So here's a quick writeup... -
Version Control and the Django Tutorial
Subversion Under ControlSimilar to last semester teams are required to use version control, Subversion (SVN) in particular, to manage their project's source code. Last semester's project was my first experience with SVN, which was quite a learning process.Shortly into the creation of the repository the need for standard protocols was realized. In particular the team needed to write succinct commit messages which convey why the commit was made. The message must include what problem was fixed, or if a new feature was added a use case for said feature. Messages which could be found on whatthecommit.com or other similar sites should be avoided at all costs. Eventually the contributing members of the group adopted a standard messaging format which helped greatly with project development. In spite of various issues, gaining firsthand knowledge at how SVN handles conflicts and merges was very educational. After a few frustrating experiences I promptly learned to check for and pull down new versions before starting work on a new task.Despite my previous experiences with SVN I decided to follow along with the exercises in Chapter 4 of The Teaching Open Source (TOS) textbook (link on the sidebar). Unfortunately, I was unable to checkout the tutorial repo as it … -
Hurray for tests: preparing a buildout pull request
Last week, I prepared a pull request for zc.buildout 2.0 to include buildout-versions' functionality in buildout itself. I had looked at the inner workings of buildout before and even prepared a pull request before, but that was a small one. buildout-versions monkeypatches internals of buildout so that it can print a list of picked versions at the end of your buildout run. Quite essential if you want to make your buildouts repeatable. You don't want too many surprises by new versions. So: I integrated a buildout extension that did some buildout-monkeypatching into buildout itself. More specifically into a historically quite involved piece of buildout. Picking the right versions is at the core of buildout, so making a mistake there is a big no-no :-) Where did I get the confidence for making such a pull request? From the tests. There are a lot of tests in buildout's code. They're mostly doctests. Doctests have their drawbacks (and advantages). But they're tests anyhow. And I could find a couple of good spots to add my documentation and tests to test the functionality I was copying over from buildout-versions. And I could be certain that if I broke something, the existing tests would … -
Testing and Django settings
Django uses a from django.conf import settings configuration mechanism, which makes it hard to test. The settings object is global. You have to do set a setting and revert the change at the end of a test; quite messy. You can do a bit better, in such a situation, by using the excellent mock library. But even mock is defeated sometimes by Django's settings. I tried a couple of variants like the following and failed to change the settings: import mock class XYZTest(TestCase) @mock.patch('django.conf.settings.DEBUG', False) def test_xyz(self): # ... # Well, I'm importing settings in my views module... @mock.patch('my_app.views.settings.DEBUG', False) def test_xyz2(self): # ... After some googling I discovered something I totally missed. Django 1.4 has something real useful. The @override_settings decorator. Does exactly what I want it to do: from django.test.utils import override_settings ... class XYZTest(TestCase) @override_settings(DEBUG=False) def test_xyz(self): # ... Hurray! -
Django Extensions 1.0.3
A new version of Django-Extensions just hit PyPi :) We call it: 1.0.3 ChangeLog: FEATURE: notes command now shows BUG tags FEATURE: support SSL in runserver_plus DOCS: Better documentation for runserver plus DOCS: Better documentation for runscript command FIX: truncation on admin widgets FIX: allow AutoSlugField to work with inherited models. FIX: show_templatetags command FIX: RSA public key check for keyzcar encrypted fields FIX: graph_models command for Django 1.5