Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Moving Data from One Database to Another with Django
So I have a django database I'm working on and I decided I wanted to do the development in sqlite3 instead of mysql. I decided to do this because it makes it easier, for example, to have someone else work on HTML/CSS if I can just give them a directory, tell them to run a bash script and go to http://localhost:8000, rather than them having to do all that AND setup a mysql server. Sure, that can also be done with a script, but with sqlite things are just a hell of a lot easier in some ways. I decided I wanted to take the data out of my mysql database and load it into a sqlite db. Not so simple, you can't just take an SQL dump from mysql and import it into sqlite3. I started Googling around for "mysql to sqlite" and didn't really get anywhere. I then realized that Django can already talk to sqlite and mysql transparently without me having to know any SQL. So I thought about writing my own python modules to do this, but it turns out someone has already done it. The django-extensions project has a manage.py command called "dumpscript" that "Generates … -
Dynamic ModelForms in Django
For an ongoing project I am implementing basic advertising functionality, where I define a number of positions in the page and advertisers can self-serve to create an advertisement to fit those positions. Each 'Position' can have different attributes turned on or off. For example, a 'sidebar' ad may permit an image and link text, however a 'footer' ad may only contain link text. When the user creates their own ad, I wanted a single form that morphed itself based on the Position being used so that fields were enabled or disabled, and made mandatory as required. To get started, here are excerpts from the two models I'll use to demonstrate how I achieved this: # models.py from django.db import models class Position(models.Model): title = models.CharField(max_length=100) description = models.TextField() has_title = models.BooleanField(blank=True, null=True) has_summary = models.BooleanField(blank=True, null=True) has_link = models.BooleanField(blank=True, null=True) has_image = models.BooleanField(blank=True, null=True) class Advertisement(models.Model): position = models.ForeignKey(Position) internal_name = models.CharField(max_length=150) image = models.ImageField(upload_to=ad_image_path, blank=True, null=True) link_url = models.URLField(blank=True, null=True) link_text = models.CharField(max_length=100, blank=True, null=True) ad_text = models.CharField(max_length=100, blank=True, null=True) The trick here is to ensure that when creating an Advertisement, the image, link_url, link_text and ad_text fields are turned on and off based on the related Position. First … -
Dynamic ModelForms in Django
For an ongoing project I am implementing basic advertising functionality, where I define a number of positions in the page and advertisers can self-serve to create an advertisement to fit those positions. Each 'Position' can have different attributes turned on or off. For example, a 'sidebar' ad may permit an … -
Clarification for Confusion: Creating New Django Fields. Part 1
Let's say you've just published your first Django-based project. You've learned a lot, you know how to create a new app, views, forms, middleware, and template tags. That's cool, but there is still much space for making your code cleaner and better-organized. One of such improvements could be joining multiple fields into a single field.To be clear, there are several types of fields in Django web development and all of them are related to each other. First of all, there are the fields of database tables in the lowest level. Then there are model fields representing the database fields in python. Form fields go on top in the abstraction level. Then there are bound fields which bound the form fields with data from the database (or somewhere else). And finally there are HTML fields which represent the rendered bound fields and which can be spiced up with Javascript for creating new widgets.Now imagine, that you have a Contact model which includes two phone numbers where each of them has three parts. They are the country code, area code, and the serial number. In the simplest case you would have something like this:COUNTRY_CODE_CHOICES = getattr(settings, "COUNTRY_CODE_CHOICES", ( ("+44", "United Kingdom (+44)"), … -
Django Site of the Week
Since I started DjangoSites over a year ago, the response has been fantastic. I used to approve a handful of websites a week, recently it's more like a half-dozen a day. I've decided that a bunch of those websites are just awesome, and I wanted to have a chat with the owners of those sites and share their stories with the Django Community. Most larger or more unique stories have a story behind them, and the experiences of the team building them are vary from project to project. Upon approaching the owners of a number of cool websites powered by Django, I received great feedback and enthusiastic responses. So far there are a few weeks of interviews ready to be published, with more on the way. The first website we've featured is Disqus, a hosted comment engine that can be used on any blog or website for free. It's an interesting website, and Daniel Ha (one of the founders) was very helpful in answering my questions and helping to share his experiences with Django. Each weekend, another interview will be published. You can subscribe to the RSS feed to be automatically alerted to new websites, however I suggest you visit … -
Django Site of the Week
Since I started DjangoSites over a year ago, the response has been fantastic. I used to approve a handful of websites a week, recently it's more like a half-dozen a day. I've decided that a bunch of those websites are just awesome, and I wanted to have a chat with … -
Diário 0.2 out! The Alexandros Grigoropoulos's Diary Release
Today was released the Diário version 0.2, blog application for Django projects, packaged from revision 181 in Subversion. New in version 0.2: Django 1.0.X compatible; Support to ping weblog directories (issue #11); Changed license to LGPLv3 (issue #36); Some code refactoring; Removed deprecated features; Many bug fixes; Other enhancements. Diário 0.2 too will be packaged to Debian by Lincoln Sousa and be available in main Debian repository. Help us to improve Diário! See the Roadmap for version 0.3. Thanks to everyone who made this release possible! This version is a tribute to Alexandros Grigoropoulos, 15-year-old boy, libertarian, murdered by greek police in last week (2008-12-06). -
Enhancing Django comments admin with django-batchadmin
So, I'm making headway against comment spam, but still accumulating a bunch of comments that are suspicious enough to mark for review, but not bad enough to reject out of hand. The find, delete, confirm delete cycle in the admin interface is tiresome. Enter django-batchadmin. -
Django fulltext search -- part 1
I have been recently working on adding full text search to a django based web application since this is not yet particularly well documented. Here it is my little stone to the amazing pyramid already in place waiting for you to use it. In order to add this "must have" feature to your great web application you will need 3 components :djangosearchpysolrsolrStarting by the latest the first challenge is to get it installed, I haven't had luck with the usual "apt-get install solr". It must be me but after an installation I was only getting a blank page instead of solr admin interface. On #solr channel someone advise me to just grab the latest release tar ball and to run with it. Then I have performed the tutorial this help me a lot to get started with solr. Believe it or not when you are there you have done the hardest part of it.Now you need to go inside the django project you want to work on and follow the following recipe :download and put into your PYHTONPATH djangosearch and pysolrAdd djangosearch inside the INSTALLED_APPS tuppleadd the following settings :SEARCH_ENGINE = "solr" # solr, lucene, xapian, estraierSEARCH_RESULTS_PER_PAGE = 10SOLR_URL= "http://localhost:8983/solr"At … -
Testy
Anyone attempting to dip into my modest archive this morning would have seen an error message instead. (And yes, the error page itself isn't getting styled properly. One thing at a time, people!) I discovered a bug in how my archive_month view was working and I fixed it. And in the process I opened a much worse bug. This is one of the classic narratives, along with "boy meets girl", "stranger comes to town" and the rest. Here's the way the view looked this morning: def archive_month(request, year, month, category_slug=None): queryset = BlogPost.objects.public_posts() if category_slug: category = get_object_or_404(Category, slug=category_slug) queryset = queryset.filter(category=category) return date_based.archive_month( request, year=year, month=month, month_format="%B", date_field='pub_date', queryset=queryset, template_object_name='blogpost', extra_context={'category': category, 'preview': True} ) So close... Now, here it is, with the fix: def archive_month(request, year, month, category_slug=None): queryset = BlogPost.objects.public_posts() if category_slug: category = get_object_or_404(Category, slug=category_slug) queryset = queryset.filter(category=category) else: category = None return date_based.archive_month( request, year=year, month=month, month_format="%B", date_field='pub_date', queryset=queryset, template_object_name='blogpost', extra_context={'category': category, 'preview': True} ) Now category is always set, whether it's to a Category object or to None. No more "UnboundLocalError: local variable 'category' referenced before assignment". But when I realized I was going to post my fix, I also realized I would have … -
SmartyPants in Django Templates
John Gruber’s SmartyPants script is a great tool for converting a body of text into a more typographically correct and visually appealing version. Chad Miller’s Python port makes it really easy to implement this functionality as a template tag, but I wanted to take it a step further and use SmartyPants as a Markdown pre-processor, just as I did with Pygments. The solution is actually very simple, but the actual RegEx required to do the job took me a bit of time to put together. The problem was to properly ignore code blocks and apply the SmartyPants filter on all areas outside the code examples. Here is the final Markdown pre-processor that I came up with: class SmartyPantsPreprocessor(TextPreprocessor): """ A Markdown preprocessor that implements SmartyPants for converting plain ASCII punctuation characters into typographically correct versions """ pattern = re.compile(r'(.+?)(@@.+?@@end|$)', re.S) def run(self, lines): def repl(m): return smartyPants(m.group(1)) + m.group(2) return self.pattern.sub(repl, lines) The pattern looks for every piece of text that comes before a text block or before the end of the content, then filters the first part through SmartyPants, and passes the code blocks as they are. Finally, I make sure to register this processor before my Pygments pre-processor: … -
django-registration
This will be about (bad?) documentation.Im in process of making small database inferface in django with few additional functions. I need to register people. This is the place where django-registration kicks in, I choose it to cut development time and to not reinvent the wheel.Basic setup of django-registration is a breeze, but when it gets to template creation it gets worse. Information about context variables passed to the templates is hid among the rest of documentation. I found easier to dig it out from the code rather than from documentation. It could be so beautiful if it was included in overview.txt (in "Templates used by django-registration" section specifically). I know that it is not much but it could be easy 5 minutes of setting up django-registration instead of 15 minutes poking with code and other documentation.Fortunately I wont moan more but do something productive instead and produce better documentation ;) I know that in a week I will not remember which template takes which parameter and first place I'll be looking in is documentation. So here we go:The views included in django-registration make use of five templates:* ``registration/registration_form.html`` displays the registration form for users to sign up. Gets ``form`` in … -
Clearing Django Form Fields One By One
I just spent an hour looking all over the web for something everyone assumes everyone else already knows. If you’re new to Django and you’re trying to clear a form field on validation then the solution is not intuitive. Take a common scenario, you have a CAPTACHA image and the user enters it incorrectly, next [...] -
Simple spam defense for Django comments
A simple way to block comment spam with the Django 1.0 contrib comments application. -
Emacs mode for dpaste.com
Since Paul Bissex announced the api for Django-powered dpaste.com last week I've had it's been on my todo list to make a emacs mode for posting pasties. -
How Django Works
This is my attempt to explain the inner working of Django. I've broken it down to multiple steps as an HTTP Request travels from your Browser to how your response is generated and back to your browser. I'll outline the steps here again:1. Standard Http Request Initiated http://mysite.com/hello/2. Your HTTP Server will load multiple copies of your django app ready to process requests.3. Django creates a Request Object representing your request and will filter them through multiple middlewares (python functions). These functions may modify the Request object or respond the request right there. Writing custom middlewares are simple.4. Django checks your defined URLs (Regular Expressions) to decide which function it must hand over the Request object to.5. This function takes the request object, much like your middlewares, except it Must return an Http Response Object. All your logic will go here. Django gives you a ton of other tools to access db, render your HTML files, etc to help you do all you need to do. You do not have to use them.6. The Response Object will once again go through all Middlewares in the reverse order, giving each middleware the option to modify the response if appropriate. -
Some great functions in django templates
In my quest to capitalize the title for my application, I found some great functionality in django's templates. To 'humanize' data there is contrib package called 'humanize'. For the docs you can find it here.For some built in functions look here. I really like some of the humanize functions after spending so much time to implement some of the functions found here. While django's template language might not be as powerful as others they sure have some pretty useful functionality here! -
Get User from session key in Django
Error emails contain session key When you get an error email from your Django app telling you someone got a server error, it’s not always easy to tell which user had a problem. It might help your debugging to know or you might want to contact the user to tell them you have fixed the problem. Assuming the user is logged in when they get the error, the email will contain the session key for that user’s session. The relevant part of the email looks like: <WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{ 'sessionid': '8cae76c505f15432b48c8292a7dd0e54'}, ... Finding the user from the session If the session still exists we can find it, unpickle the data it contains and get the user id. Here’s a short script to do just that: from django.contrib.sessions.models import Session from django.contrib.auth.models import User session_key = '8cae76c505f15432b48c8292a7dd0e54' session = Session.objects.get(session_key=session_key) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) print user.username, user.get_full_name(), user.email There it is. Pass in the session key (sessionid cookie) and get back the user’s name and email address. Plug: Get your own job board at Fuselagejobs -
Python 3.0 wydany!
Dziś w nocy została wydana trzecia wersja języka Python. Gratulujemy wszystkim programistom, którzy przyczynili się do tego wydarzenia. Informację o nowej wersji znajdziecie na http://www.python.org.pl/ Jak myślicie, kiedy Django przejdzie na nową wersję pythona? Czy będzie to najpierw... -
Generic inlines and Django history
The other day at work I stumbled across my first opportunity to use a relatively-new feature in the Django admin, one which turned what had looked like it would be a fairly nasty task into, basically, a five-minute job (plus staging, testing and deployment, of course, but that happens no matter how long it takes to develop the code). I’ll get to the specifics in a minute, but first I want to give a little ... Read full entry -
Generic inlines and Django history
The other day at work I stumbled across my first opportunity to use a relatively-new feature in the Django admin, one which turned what had looked like it would be a fairly nasty task into, basically, a five-minute job (plus staging, testing and deployment, of course, but that happens no matter how long it takes to develop the code). I’ll get to the specifics in a minute, but first I want to give a ... Read full entry and comments -
fez.djangoskel: Django projects and apps as eggs
I've made an initial release of fez.djangoskel, which provides simple paster templates for egg-based Django projects and applications. -
fez.djangoskel: Django projects and apps as eggs
This is just a brief note to say that I've release fez.djangoskel, a package which provides paster templates for creating egg-based Django projects and reusable applications. This is all part of my crusade to get the Django community to package software as eggs. As well as source and binary egg releases on PyPI, the code is available on GitHub (representing my first foray into git). The easiest way to get this is, as usual, with easy_install. (See my previous posts on how to set this up): easy_install fez.djangoskel Once that and its dependencies have installed, you should fine that paster can now create Django projects and apps: $ paster create --list-templatesAvailable templates: basic_package: A basic setuptools-enabled package django_app: Template for a basic Django reusable application django_project: Template for a Django project paste_deploy: A web application deployed through paste.deploy It's standard paste from here on in: to create a project, use: paster create -t django_project To create an app, use: paster create -t django_app Paster will then ask you a bunch of questions (the most crucial one being the name of your app/project!) and generate the file layout for you. I plan to do another release later this week which includes … -
fez.djangoskel: Django projects and apps as eggs
This is just a brief note to say that I've release fez.djangoskel, a package which provides paster templates for creating egg-based Django projects and reusable applications. This is all part of my crusade to get the Django community to package software as eggs. As well as source and binary egg releases on PyPI, the code is available on GitHub (representing my first foray into git). The easiest way to get this is, as usual, with easy_install. (See my previous posts on how to set this up): easy_install fez.djangoskel Once that and its dependencies have installed, you should fine that paster can now create Django projects and apps: $ paster create --list-templatesAvailable templates: basic_package: A basic setuptools-enabled package django_app: Template for a basic Django reusable application django_project: Template for a Django project paste_deploy: A web application deployed through paste.deploy It's standard paste from here on in: to create a project, use: paster create -t django_project To create an app, use: paster create -t django_app Paster will then ask you a bunch of questions (the most crucial one being the name of your app/project!) and generate the file layout for you. I plan to do another release later this week which includes … -
fez.djangoskel: Django projects and apps as eggs
This is just a brief note to say that I've release fez.djangoskel, a package which provides paster templates for creating egg-based Django projects and reusable applications. This is all part of my crusade to get the Django community to package software as eggs. As well as source and binary egg releases on PyPI, the code is available on GitHub (representing my first foray into git). The easiest way to get this is, as usual, with easy_install. (See my previous posts on how to set this up): easy_install fez.djangoskel Once that and its dependencies have installed, you should fine that paster can now create Django projects and apps: $ paster create --list-templatesAvailable templates: basic_package: A basic setuptools-enabled package django_app: Template for a basic Django reusable application django_project: Template for a Django project paste_deploy: A web application deployed through paste.deploy It's standard paste from here on in: to create a project, use: paster create -t django_project To create an app, use: paster create -t django_app Paster will then ask you a bunch of questions (the most crucial one being the name of your app/project!) and generate the file layout for you. I plan to do another release later this week which includes …