Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
A simple Django life stream
After reading Ryan Bergs' "The basics of creating a tumblelog with Django" (part1) and (part2), I realized that I wanted a similar tumblog/life stream but I didn't want to have to go through all the work of saving those objects to the database. After all, isn't all that data already stored in their respective systems. And since I am using FriendFeed, which is again duplicating all that data, I don't want to be duplicating it yet another time. That's when the light bulb went off. Using the FriendFeed API and a bit of caching I can pull in my lifestream from FriendFeed using only a custom tag. So I came up with what I call lifefeed Just add "lifefeed" to your installed apps and you can now do this from any template {% load lifefeed %}{% load cache %} {% cache 900 friendfeed %} {% lifefeed "YOUR FRIEND FEED USERNAME" %} {% endcache %} You can use the default friendfeed.html template that comes with lifefeed or use your own. You will most definitely want to use your own CSS to style the items since I am no CSS guru. lifefeed is very simple right now but I would like to … -
Pinax Developer Quickstart
At PyCon I helped a group of people get a Pinax development environment set up. Many People were not yet familiar with the whole virtualenv and pip workflow, so I thought I would put up the steps I use to get Pinax up. -
Satchmo product images
Templatetag for Satchmo creates unordered list for product images. CSS can be applied to customize output. from django import template from satchmo.product.models import Product from satchmo.thumbnail.templatetags.satchmo_thumbnail import thumbnail try: from xml.etree.ElementTree import Element, SubElement, tostring except ImportError: from elementtree.ElementTree import Element, SubElement, tostring register = template.Library() default_opts = { 'thumbnail': 'width=280', 'start': 0 } class ProductGalleryNode(template.Node): def __init__(self, product, **opts): self.product = template.Variable(product) self.opts = default_opts self.opts.update(opts) def render(self, context): actual_product = self.product.resolve(context) images = actual_product.productimage_set.all() start = int(self.opts['start']) if len(images) <= start: return ("") root = Element("ul", {'class': self.opts.get('class', '')}) for (i, pic) in enumerate(images[start:]): li_attr = {'class': 'first'} if not i else {} li = SubElement(root, 'li', li_attr) link = SubElement(li, 'a', {'href' : pic.picture.url}) caption = pic.translated_caption() src = thumbnail(pic.picture.url, self.opts.get('thumbnail')) img = SubElement(link, 'img', {'src': src, 'alt': caption, 'title': caption}) return tostring(root, 'utf-8') @register.tag def product_gallery(parser, token): """ Returns an unordered list of image thumbnails for product. Usage: {% product_gallery product %} {% product_gallery product thumbnail="width=280"%} {% product_gallery product start=1%} {% product_gallery product class=galeria%} """ kwargs = {} bits = token.split_contents()[1:] product = bits[0] for bit in bits[1:]: arg, val = bit.split("=", 1) kwargs[str(arg)] = val.strip('"') return (ProductGalleryNode(product, **kwargs)) -
Switch between django trunk and stable versions
This is snippet that I use to switch development with Django between 1.0 and trunk versions: #!/bin/sh rm /Library/Python/2.5/site-packages/django if [ "$1" = "" ]; then echo "Django 1.0" ln -s LOCATION_OF_SOURCE_CODE/django-1.0/django /Library/Python/2.5/site-packages/django else echo "Django trunk" ln -s LOCATION_OF_SOURCE_CODE/django-trunk/django /Library/Python/2.5/site-packages/django fi $ ~/djchange.sh Django 1.0 $ django-admin.py --version 1.0-final-SVN-8977 $ ~/djchange.sh trunk Django trunk $ django-admin.py --version 1.1 alpha 1 SVN-10065 Also check that django-admin.py is symbolic link to /Library/Python/2.5/site-packages/django/bin/django-admin.py -
Django testshell
It is usable if you want to play with test database. See also testserver docs from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list help = 'Runs a Python interactive interpreter with test database and data from the given fixture(s).' args = '[fixture ...]' requires_model_validation = False def handle(self, *fixture_labels, **options): from django.core.management import call_command from django.db import connection verbosity = int(options.get('verbosity', 1)) # Create a test database. db_name = connection.creation.create_test_db(verbosity=verbosity) # Import the fixture data into the test database. call_command('loaddata', *fixture_labels, **{'verbosity': verbosity}) call_command('shell') -
Use unicode in doctests
Use hex representation, double quote slashes in expectation. Do not use print in doctests . """ >>> s = u"šđčćž" >>> s u'\\xc5\\xa1\\xc4\\x91\\xc4\\x8d\\xc4\\x87\\xc5\\xbe' """ -
Django set language for admin
If you want to explicitly set language for django admin section use this middleware: from django.conf import settings from django.utils import translation class AdminLocaleURLMiddleware: def process_request(self, request): if request.path.startswith('/admin'): request.LANG = getattr(settings, 'ADMIN_LANGUAGE_CODE', settings.LANGUAGE_CODE) translation.activate(request.LANG) request.LANGUAGE_CODE = request.LANG Then put somewhere in settings.py: ADMIN_LANGUAGE_CODE=’it’ and add middleware: MIDDLEWARE_CLASSES = ( ... 'utils.multilang.middleware.AdminLocaleURLMiddleware', .... -
Django-simpleadmindoc
I started this project as I needed to deliver help and documentation for django-admin on client website and admindocs seems more oriented to developers than to users. http://github.com/bmihelac/django-simpleadmindoc -
Django time widget with custom time shortcuts
This small javascript snippet replaces standard django clock shortcuts Midnight, Noon, Now & 6am with various time increments . $(window).load(function() { $('.timelist').each(function(num, el) { time_format = get_format('TIME_INPUT_FORMATS')[0]; $(el).html(''); for (i=8; i<20; i++) { var time = new Date(1970,1,1,i,0,0); lnk = "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '" + time.strftime(time_format) + "');" $(el).append('<li><a href="'lnk'">' + time.strftime('%H:%M') + '</a></li>'); } }); }); This snippet use JQuery which is available with Django 1.2. (dev at time of writing)Also, javascript should be loaded after DateTimeShortcuts.js but unfortunately I didn’t find a better way to achive this but to add in modified base admin site templates/admin/base_site.html. If you have any suggestion for improvement, let me know in comments. -
Do not use appname as templatetags module
This is the second time I created same error writing templatetags, so it is about time to document it. This is the bad layout for poll app. polls/ __init__.py models.py templatetags/ __init__.py polls.py views.py Instead of polls.py it should be polls_tags.py or something other different from appname. Whats going on? polls.py would define polls module and it would not be possible to import other modules from original polls application. For example the code bellow would throw ImportError: No module named models #polls.py from django import template from polls.models import Question register = template.Library() -
Handling i18n in Django projects
Given the following premises: Some 3rd party apps do have translations for language that we need and some do not. Translations for some apps maybe poor or just inadequate We don't always have write access for some apps catalogs Our goal is to offer website editor access for easily managing all important translations. Example project setup As a example project let say we want to build small website with FAQ section in Slovenian and Deutsch language. To manage questions and answers we want to use django-faq app. We would include Django Admin and Rosetta applications to allow administrator to easily manage content and translations on the website. Our directory structure looks like this: example.com/ website/ custom/ settings.py urls.py requirements.txt Note that we won't copy django-faq (or any other external apps) into our project directory, as it would made it harder to receive updates and bugfixes. Beside that we don't want it to clutter our source version control system with other projects. We would rather made it available on python-path by using pip, easy_install or symlinking it to site-packages directory. Ideal workflow Looking at the faq app we notice that it already have translations for Deutsch language but not for Slovenian … -
Speed up Django testing with sqlite
Using MySql default ISAM storage type for testing in Django can be slow. To use sqlite in memory database with transactions support add this code to the end of settings.py: if 'test' in sys.argv: DATABASES = { 'default': {'ENGINE': 'django.db.backends.sqlite3'} } -
Rättigheter hos FS-Data
hej -
Rättigheter hos FS-Data
hej -
Джанго в роли микрофреймворка
Известно мнение, что Джанго не подходит для написания "наколеночных" проектиков, которым не нужно ничего особенно, кроме вывода HTML'а. Создание скелета проекта на Джанго считается работой, достаточно существенной для того, чтобы не заниматься ею ради пары функций. Мне всегда было "очевидно", что это не так, но недавно по оброненной коллегой фразе я понял, что это не значит, что это очевидно всем. Многие просто не задумываются об этом. Ну, вы знаете, как это бывает… Поэтому я хочу продемонстрировать создание Джанго-проекта минимальными усилиями. Упрощение Нужно отказаться от команды startproject. Она создаёт хороший скелет проекта с аннотированным файлом настроек, но если вы Джанго-проект видите не впервые, этим можно пренебречь. Файл manage.py — тоже не нужен, это просто локальный хелпер для django-admin.py Не нужно думать о проекте, как о контейнере для приложений, а следовательно не нужно оформлять свой код, как подключаемое приложение. Приложения — одна из самых сильных архитектурных черт Джанго, но для мелких задач эта гибкость никогда не понадобится. В итоге мы имеем что-то такое: settings.py: DEBUG = True ROOT_URLCONF = 'urls' TEMPLATE_DIRS = ['.'] urls.py: from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^test/(\d+)/$', views.test), ) views.py: from django.shortcuts import render def index(request): return render(request, 'index.html', {}) def test(request, id): … -
nashvegas 0.4.1 released
A week or so ago I packaged up nashvegas 0.4.1 and thanks to Brian Rosner and Jannis Leidel there have been a good number of features added since my last blog post about nashvegas. Change Log Running ./manage.py syncdb now prompts for confirmation to prevent accidental executions. When migrations are managed by nashvegas, running syncdb can make it easy to forget to create migrations. --seed option takes an end point instead of the entire unexecuted list in the migrations folder SQL is no longer piped into your database backend client, but executed via the in process database connection object managed by Django. All migrations, including interleaved Python based migrations run in one atomic migration (backend database must support transactions obviously) Added admin interface for nashvegas's Migration model Updated --create to not output BEGIN/COMMIT statements as transaction is now managed by nashvegas not the script(s) being executed. Fixed some minor bugs Updated execution of Python migrations to use execfile instead of __import__ to avoid pyc confusion. Updated output of --execute to provide better user feedback of what is being executed. -
nashvegas 0.4.1 released
A week or so ago I packaged up nashvegas 0.4.1 and thanks to Brian Rosner and Jannis Leidel there have been a good number of features added since my last blog post about nashvegas. Change Log Running ./manage.py syncdb now prompts for confirmation to prevent accidental executions. When migrations are managed by nashvegas, running syncdb can make it easy to forget to create migrations. --seed option takes an end point instead of the entire unexecuted list in the migrations folder SQL is no longer piped into your database backend client, but executed via the in process database connection object managed by Django. All migrations, including interleaved Python based migrations run in one atomic migration (backend database must support transactions obviously) Added admin interface for nashvegas's Migration model Updated --create to not output BEGIN/COMMIT statements as transaction is now managed by nashvegas not the script(s) being executed. Fixed some minor bugs Updated execution of Python migrations to use execfile instead of __import__ to avoid pyc confusion. Updated output of --execute to provide better user feedback of what is being executed. -
django-helpdesk
A while ago I released a helpdesk tool that I use to manage support requests, under the name of Jutda Helpdesk (named after my small consulting company). The project has received a slow but steady stream of patches and bug fixes, however it's always been a little tricky to manage with a single committer over at Google Code. To make life easier for everybody involved, I've renamed the project to django-helpdesk and shifted the source code and issue management to GitHub. -
django-helpdesk
A while ago I released a helpdesk tool that I use to manage support requests, under the name of Jutda Helpdesk (named after my small consulting company). The project has received a slow but steady stream of patches and bug fixes, however it's always been a little tricky to manage with a single committer over at Google Code. To make life easier for everybody involved, I've renamed the project to django-helpdesk and shifted the source code and issue management to GitHub. I thought I'd spend a few words talking about these two changes. Firstly, the change in name. Because django-helpdesk was originally built for my own use internally at Jutda and WhisperGifts I released it under the name of "Jutda Helpdesk" when I opened the source up a few years back. There was a bit of a thought that I could release more products with a similar naming scheme, such as "Jutda Basket Weaver" and "Jutda Donut Maker". Those products never eventuated, leaving the only open-source product as "Jutda Helpdesk". This seems to have caused a bit of confusion, with people referring to the product simply as "Jutda" which does no good for either the helpdesk product or my business. … -
django-helpdesk
A while ago I released a helpdesk tool that I use to manage support requests, under the name of Jutda Helpdesk (named after my small consulting company). The project has received a slow but steady stream of patches and bug fixes, however it's always been a little tricky to manage … -
Django session key changes on every request?
Django version is 1.2.4.views.pyfrom django.http import HttpResponsefrom random import choicedef index(request): x = choice([0, 1, 2]) if x == 0: request.session['a'] = 1 elif x == 1: request.session.flush() return HttpResponse(request.session.session_key + ' ' + str(request.session.keys()) + ' ' + str(x), content_type='text/plain')session.clear() method doesn't change session key.The session key was changed when call the session.flush() method. (eg. logout())If session isn't used in request, session key was changed on every request.ref:Django | How to use sessions | Django documentation -
Los Angeles Open Source Hackathon
I want to announce the launch of our new company which we've named Cartwheel! Besides Python and Django consulting, our plan is to support local Los Angeles small business, teach classes, and host events. And our first event is a Los Angeles Open Source Hackathon on February 5th! Space is limited so RSVP before tickets run out!Open Source Hackathon at CartwheelA hackathon (or sprint if we want to be Pythonic) is where a bunch of developers get together to push various projects forward.Bring your laptop and work on any open source project that you'd like, as long as it's open source. It can be an existing open source project (e.g. Django, Python) or a new one of your own. Leave the work stuff at work! Got an existing project? Hackathons are a great place to share ideas and perhaps find additional contributors. Let me know and I'll put it in an additional blog post.New to open source? A beginning developer? We'll help you get started with open source software development and do our best match you to a project that fits what you want to do.Some projects that may be worked on:Nudge: Evite's API tool is being open sourced!django-packages: Integration with brabeion … -
First entry
Syntax highlightingfrom django.http import HttpResponsedef index(request): return HttpResponse('OK') -
4 Lessons learned about multivariate testing
Recently we did our first major multivariate test on a page using Google Website Optimizer (GWO). Our goal was to increase reader involvement by having them go to any other page on our web site. There ended up being 32 combinations of content. We wrote and open-sourced a Django application to do much of the work called django-gwo. Here are a few lessons from the first test: You can test the layout of dynamic pages Typically A/B and multivariate testing is about a static testing URL and a static goal URL. We needed to test every story URL and our goal was any other URL on our site. The tricks: Use JavaScript to tell GWO that the test is starting Use the “onclick” method on links to tell GWO that the test succeeded. Don’t include any dynamic content within the experiment sections Use <div> tags around dynamic content with an alternate <div style=”display: None”> to make it disappear. If you want to test if a dynamic content block is better in position A or position B, put it in both. Use surrounding <div> tags to make the content appear and disappear. You can manually remove combinations where the content would appear twice. Test multiple things GWO will show you the … -
Error Tracing in Sentry