Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
BarDiver.com Launches
Back in September I said that I was working on a surprise project. Well today I am happy to announce that BarDiver.com has officially launched. BarDiver.com is a community driven search site to help you find local bars that have the features and atmosphere you like. For this first release I am keeping BarDiver.com focused on Colorado only. If that is a success and I get interest to open BarDiver.com for another city/state I will absolutely do that. So please, check out the site and if you think your area could use BarDiver.com, let me know. BarDiver.com is built using the Django web framework. Django was instrumental in getting the site up fast. I cannot get over how great Django is to work with. I was able to use many of the goodies built into Django instead of writing them (again) myself. Some of these things are the authentication, comments, sites, flatpages and of course the admin user interface. I am really looking forward to the many cool new things that are being worked on in the seperate Django branches, such as Multiple Database Support, and Generic Authorization. I hope you enjoy BarDiver.com Dive In. -
Django in June
This is going to be one busy weekend. Friday after work I am going to Coors Field to watch the Rockies vs. the Devil Rays. I am driving straight from the game to DIA to catch the red eye into Logan where I will pick up my rental car and go directly to the Django in June un-conference. I am really looking forward to this. It will be great to meet some of the great people in the Django community. I also hope to meet some people in Boston that might be interested in helping me populate boston.bardiver.com with some more great bars. To ensure that this happens I will also be bringing with me some BarDiver.com Schwag to give out. ;) Once the conference is done with I will be driving up to New Hampshire to play golf with my Dad on Fathers Day. This should be a lot of fun. This will be the 3rd time I have played this year. After that and a quick visit with my Grandmother, I will be driving back into Boston to catch my flight back to Denver. Sunday night I might actually get 8 hours of sleep before I have to … -
Intense Debate Import Hack
Recently I wanted to try out the Intense Debate commenting system on this blog. I didn't want to lose all the comments that I had already and Intense Debate only supports importing comments from Blogger, etc but not custom blog software. Since I wrote this blog using the Django framework using django.contrib.comments I needed to come up with my own solution. It only took one Tamper Data request to see how an anonymous comment was posted into the Intense Debate system. A few minutes later I had a script to import my old comments into Intense Debate. intenseDebate.py import intenseDebate intenseDebate.postComment(blogpostid="", acctid="", anonName="", anonEmail="", \ anonURL="", comment="") blogpostid is the unique Intense Debate postId. You can find this easily on any Intense Debate powered page using the firebug dom tab. The key to look for is "IDCommentScript". acctid is your Intense Debate accountId. This can also be found using the firebug dom tab. The key to look for is "IDWUserWidget.acctid" anonName is the name of the commenter anonEmail is the commenters email address anonURL is the commenters web address comment is the text of the comment This method of importing comments does have it's problems. Manual process to get the … -
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 …