Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Retiring as BDFLs
Adrian broke the news: today, he and I are retiring as BDFLs, transitioning to a truly community-run project. Adrian wrote a bit about the history of the BDFL term and our roles wearing that hat. Go check out his writing for that, and for some of his personal thoughts. Here, I’ll just add a few things of my own: For me, this has been a long time coming – I’ve been thinking about this for at least a year. -
Managing Events with Explicit Time Zones
Recently we wanted a way to let users create real-life events which could occur in any time zone that the user desired. By default, Django interprets any date/time that the user enters as being in the user’s time zone, but it never displays that time zone, and it converts the time zone to UTC before storing it, so there is no record of what time zone the user initially chose. This is fine for most purposes, but if you want to specifically give the user the ability to choose different time zones for different events, this won’t work. One idea I had was to create a custom model field type. It would store both the date/time (in UTC) and the preferred time zone in the database, and provide a form field and some kind of compound widget to let the user set and see the date/time with its proper time zone. We ended up with a simpler solution. It hinged on considering the time zone separately from a time. In our case, we would set a time zone for an event. Any date/time fields in that event form would then be interpreted to be in that time zone. Now, displaying … -
Managing Events with Explicit Time Zones
Managing Events with Explicit Time Zones Recently we wanted a way to let users create real-life events which could occur in any time zone that the user desired. By default, Django interprets any date/time that the user enters as being in the user’s time zone, but it never displays that time zone, and it converts the time zone to UTC before storing it, so there is no record of what time zone the user initially chose. This is fine for most purposes, but if you want to specifically give the user the ability to choose different time zones for different events, this won’t work. -
A Pattern for Handling Multiple HTTP Verbs in Django
Recently I met @odonnell004, a very knowledgeable Django developer at the CodeMash conference in Sandusky, Ohio, and over a beer he showed me a technique he cooked up for dealing with multiple HTTP verbs in a single Django function-based-view that I immediately fell in love with. The most commonly seen way to handle either a GET or POST (or PUT or whatever) request is to test the value of request.method in an if/else block, with the logic for what to do for each case contained in the block itself. Forms are the classic example (code below taken directly from the Django docs): def contact(request): if request.method == 'POST': # If the form has been submitted... form = ContactForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = ContactForm() # An unbound form return render(request, 'contact.html', { 'form': form, }) I have been doing it this way pretty much since I started with Django three years or so ago, and while it probably bothered me a bit at first I've long since gotten used to this pattern and … -
Django Extensions 1.3.0
We are proud to release: Django-Extensions Version 1.3.0 This brings official Django 1.6 support and the usual tons of fixes and improvements Get it now: https://pypi.python.org/pypi/django-extensions/1.3.0 Changelog: Feature: SQLDiff much better notnull detection Feature: reset_db add option to explicit set the PostGreSQL owner of the newly created DB Feature: shell_plus added support for MongoEngine Feature: sync_s3 enable syncing to other cloud providers compatible with s3 Improvement: ForeignKeyAutocompleteAdmin add option to limit queryset Bugfix: graph_models fix issue with models without primary key Bugfix: graph_models fix UnicodeDecodeError using --verbose-names Bugfix: dumpscript fix problems with date/datetimes by saving them now as ISO8601 Docs: many improvements Docs: Chinese translation !!! Python3: various improvements Tests: add Django 1.6 -
Permissions & Authentication - django-rest-framework part 2
Learn how to use basic authentication with your new API, and setup custom permissions to get fine grained precision of what can be done with data.Watch Now... -
Django Blog Tutorial - the Next Generation - Part 3
Hello again! In this instalment, we’re going to do the following: Add support for flat pages Add support for multiple authors Add a third-party comment system Flat pages Django ships with a number of useful apps - we’ve already used the admin interface. The flat pages app is another very handy app that comes with Django, and we’ll use it to allow the blog author to create a handful of flat pages. First of all, you’ll need to install the flatpages app. Edit the INSTALLED_APPS setting as follows: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'south', 'blogengine', 'django.contrib.sites', 'django.contrib.flatpages', ) Note that we needed to enable the sites framework as well. You’ll also need to set the SITE_ID setting: SITE_ID = 1 With that done, run python manage.py syncdb to create the required database tables. Now, let’s use the sqlall command to take a look at the database structure generated for the flat pages: BEGIN; CREATE TABLE "django_flatpage_sites" ( "id" integer NOT NULL PRIMARY KEY, "flatpage_id" integer NOT NULL, "site_id" integer NOT NULL REFERENCES "django_site" ("id"), UNIQUE ("flatpage_id", "site_id") ) ; CREATE TABLE "django_flatpage" ( "id" integer NOT NULL PRIMARY KEY, "url" varchar(100) NOT NULL, "title" varchar(200) NOT … -
Django blog tutorial - the next generation - part 2
Welcome back! In this lesson, we’ll use Twitter Bootstrap to make our blog look nicer, and we’ll implement individual pages for each post. Now, before we get started, don’t forget to switch into your virtualenv. From within the directory for the project, run the following command: $ source venv/bin/activate If you haven’t used Bootstrap before, you’re in for a treat. With Bootstrap, it’s easy to make a good-looking website quickly that’s responsive and mobile-friendly. We’ll also use HTML5 Boilerplate to get a basic HTML template in place. Now, to install these easily, we’ll use Bower, which requires Node.js. Install Node.js first. On most Linux distros, you’ll also need to set NODE_PATH, which can be done by pasting the following into your .bashrc: NODE_PATH="/usr/local/lib/node_modules" With that done, run the following command to install Bower: $ sudo npm install -g bower Next we need to create a Bower config. First, create the folder blogengine/static. Then create a new file called .bowerrc and paste in the following content: { "directory": "blogengine/static/bower_components" } This tells Bower where it should put downloaded libraries. Next, run the following command to gener Bower: $ bower init Answer all the questions it asks you - for those with … -
New Year's Resolutions for 2014
Making News Year's Resolutions is something I do every year. It's important to me. I like to set goals and see how well I do. Resolutions Write and publish fiction. This is a childhood dream that I would like to do. Write and publish as least one new technical book, preferably on Python. Release the second edition of Two Scoops of Django. Learn Haskell or some other interesting programming language. Figure out a way I can make money working in open source efforts. As a consultant, this explains why I don't do it more. Visit the three continents I've yet to see. That means South America, Africa, and Antarctica. Visit at least one new nation. It's hard to come up with preferences since the whole world is so exciting. Take road trips around the USA. See the Grand Canyon. Visit more family. Do 1000 push-ups or similar exercises in a single day. I'm at 300 now. Pull off an Aú sem Mão (no-handed cartwheel). Blog once a week. That is at least 52 blog entries! Take a fun class with Audrey. Upload all my outstanding pictures to Flickr! Learn how to surf or snowboard. See all my friends. All of … -
New Year's Resolutions for 2014
Making New Year's Resolutions is something I do every year. It's important to me. I like to set goals and see how well I do. Resolutions Write and publish fiction. This is a childhood dream that I would like to do. Write and publish as least one new technical book, preferably on Python. Learn Haskell or some other interesting programming language. Figure out a way I can make money working in open source efforts. As a consultant, this explains why I don't do it more. Visit the two continents I've yet to see. That means Africa and Antarctica. See the Grand Canyon. Visit more family. Do 1000 push-ups or similar exercises in a single day. I'm at 300 now. Pull off an Aú sem Mão (no-handed cartwheel). Blog once a week. That is at least 52 blog entries! Take a fun class with Audrey. Upload all my outstanding pictures to Flickr! Learn how to surf or snowboard. See all my friends. All of them. Work less and enjoy life with Audrey more. Accomplished Release the second edition of Two Scoops of Django. Visited South Africa (Argentina and Brazil!) Visited two new nations, Argentina and Brazil. Went back to the East … -
New Year's Meme 2013
Inspired by Alex Clark's meme, here is my own entry into this end-of-year fun. What’s the Coolest Thing You Discovered This Year? Alex had his own focused on Python applications, frameworks, and libraries. Me, I'm going for a more general approach. This year I discovered: LaTeX That book I co-wrote with Audrey Roy? Written in LaTeX. It wasn't easy to get started, even with Audrey as my instructor, but now that I grok it, I feel extremely empowered. That's because I can do all kinds of awesome, insane hacks when Sphinx generates PDFs. I hope I get the chance to show off some of my new madness to the world in 2014. How to Tie A Bow Tie If you are going to be formal, the bow tie adds an enormous amount of class. However, clip-ons are considered tacky, especially as it's considered stylish to loosen the bow tie later in the evening to demonstrate you aren't wearing that clip. Of all the stuff I watched on the subject of bow tying, this video was the longest and the best of them all. Update 1/4/2014: I learned this awesome skill because I wanted to be classy on my wedding day. … -
New Year's Meme 2013
Inspired by Alex Clark's meme, here is my own entry into this end-of-year fun. What’s the Coolest Thing You Discovered This Year? Alex had his own focused on Python applications, frameworks, and libraries. Me, I'm going for a more general approach. This year I discovered: LaTeX That book I co-wrote with Audrey Roy? Written in LaTeX. It wasn't easy to get started, even with Audrey as my instructor, but now that I grok it, I feel extremely empowered. That's because I can do all kinds of awesome, insane hacks when Sphinx generates PDFs. I hope I get the chance to show off some of my new madness to the world in 2014. How to Tie A Bow Tie If you are going to be formal, the bow tie adds an enormous amount of class. However, clip-ons are considered tacky, especially as it's considered stylish to loosen the bow tie later in the evening to demonstrate you aren't wearing that clip. Of all the stuff I watched on the subject of bow tying, this video was the longest and the best of them all. Awesome Foods Around the World Here's the short-list: Oscypek is a Polish smoked, salted cheese that should … -
JavaScript based charts in Django made easy with Chartkick application
Chartkick is an application, a library for making JavaScript based charts. There is JavaScript library, Ruby wrapper and Python wrapper for Django and Flask. Let see what Chartkick can offer us in Django applications. -
Django blog tutorial - the next generation - part 1
My series of Django tutorials for building a blogging engine are by far the most popular posts I’ve ever written on here. I’ve had a lot of people contact me with questions or just to express their thanks, for which I’m very grateful! However, these tutorials haven’t really aged well. I’ve since had the opportunity to use Django in a professional capacity, which has significantly improved my understanding of the framework and the whole Python ecosystem, and there’s a lot of best practices that I didn’t follow and now wish I had. There’s also been a few gotchas that have hindered a few people in the past that I’d like to have the opportunity to correct. So, I’m therefore creating a brand new series of tutorials to remedy this situation. This series will cover exactly the same basic idea of using Django to build a blogging engine, but will expand on what the original series did in many ways. We will cover such additional topics as: Using Twitter Bootstrap to make your blog look good without too much hassle Using Virtualenv to sandbox your blog application Using South to effectively manage changes to your database structure Writing some simple unit … -
Euler Totient Function
In this post I will explain yet another simple number theoretic function, called the Euler Totient Function. This is a simple function which is used indirectly in many problems in programming contests. The function is denoted as phi(n). phi(n) basically gives the number of integers greater than 1 and lesser than n which are co-prime to the integer n. In other words, it is the cardinality of the set S = { a: 1<a<n , gcd(a,n) = 1 }. To calculate this function, we will use a straight forward brute force approach. With a simple analysis, we can show that the running time of this algorithm is O(sqrt(n)). - Start with an estimate of the totient function as n - Iterate for i from 2 to sqrt(n) - If i | n , we know that all factors of i less than equal to n will have gcd with n as atleast i. Hence, they can never be in the set S. Hence remove them from the result. - While i|n, divide n by i. - After the iteration of i from 2 to sqrt(n), if n is a number greater than 1, remove all its multiples less than n … -
How to Export Your Data as CSV, XLS, or XLSX
There are times, when you need to export the data from your database to different formats. For example, you want to create some diagrams in Office program for a presentation. In this post I will show you how to create admin actions which export selected items as files for a spreadsheet application (like MS Excel, OpenOffice Calc, LibreOffice Calc, Gnumeric, or Numbers). I will cover the mostly used formats: Comma Separated Values (CSV), Binary Excel (XLS), and Office Open XML (XLSX). First of all, have a look at the model we will be dealing with. It's a simple model with title, description, and - of course - the id. # models.pyfrom django.db import modelsclass MyModel(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) In the admininstration options, we'll define three admin actions: export_csv, export_xls, and export_xlsx. # admin.pyfrom django.contrib import adminfrom models import MyModel# ... export functions will go here ...class MyModelAdmin(admin.Admin): actions = [export_csv, export_xls, export_xlsx]admin.site.register(MyModel, MyModelAdmin) Now let's create functions for each of those actions! Comma-Separated Values Format CSV is the most common import and export format for spreadsheets and databases. It's a textual format which one could easily create or parse himself, but there is also a python built-in … -
Imaginary Realities is back
The Imaginariy Realities webzine was the place to go to for MUD game design articles in the late 90's. Last released in 2001, its articles are still worth the read for any game designers today. But guess what - this venerable ezine has now returned! You can find the new issue here.I think this is a good community initiative worthy of support. I contibuted two articles myself (one of which is about Evennia) and would like to thank the staff/editors who took their work very seriously and did sterling work on getting everything in shape.Thanks also to the other authors who penned some very interesting articles. Great job guys!My impressions: KaVir elaborates in A modern interface for a modern MUD on the advantages of not sticking with an outdated UI just for the sake of it. Adding a more accessible presentation is not that hard and won't ruin your game but rather help it. Whereas I have read his argument about this before, this is a good summary to take to heart. Evennia's javascript web client is currently mainly a telnet clone; there's a lot of things we could offer to make it easier for users to offer a more graphical … -
Start Your API - django-rest-framework part 1
In this video we start creating our API by learning what it takes to put data in our database, and retrieve it back doing all of our CRUD operations. django-rest-framework makes it very simple to accomplish with a minimal amount of effort.Watch Now... -
A note on Django 1.5.2 rotating CSRF token and frontend javascript applications
Django 1.5.2 introduced a change named The CSRF token now rotates when a user logs in. This isn't anything problematic for typical web applications where user submits a form and the page reloads. For applications that are based on JavaScript frameworks like ember (or angular) this becomes a problem, as the user is logged in the background with an AJAX request (for example with Facebook JS SDK) and the page in general never reloads. When he logs in the token changes and API (POST) requests (to django-rest-framework for example) will get forbidden as answers from the server. A solution would be to return a new token with server response to the login request and insert it in the place of the old one, which was inserter when Django template was rendered: xhr.setRequestHeader("X-CSRFToken", "{{csrf_token}}"); I wonder if there are any solutions for this already?.hll { background-color: #ffffcc } .c { color: #408080; font-style: italic } /* Comment */ .err { border: 1px solid #FF0000 } /* Error */ .k { color: #008000; font-weight: bold } /* Keyword */ .o { color: #666666 } /* Operator */ .cm { color: #408080; font-style: italic } /* Comment.Multiline */ .cp { color: #BC7A00 } … -
Working Together
Workflows, teams committing conflicting VCS branches, foreign keys being annoying and more feature in this week's Django Diaries. Time for your semi-regular update on how Django's migrations are going! I've implemented two major things since the last blog post: workflow improvements, and ForeignKey change detection. Workflow One of the problems that only started emerging with South some years after it was released was the issue of working with distributed VCS systems - like Git and Mercurial - and how their tendency towards branching impacted migration writing. When South was initially released, the world was mostly a Subversion place, and so the chance of two developers committing conflicting migrations was small. These days, the chance that someone is going to go off in a branch to add new model features while the master branch also gets a model bugfix is quite high. South didn't really deal with the resultant merge very well; it implicitly ordered migrations by filename, and so whoever had the migration which appeared first alphabetically "won"; the other developer would have to apply migrations out-of-order or back out theirs and then apply both. In short, it was a mess. My fix to this problem inside django.db.migrations is simple … -
Adding stacktraces to log messages
I always had this issue with libraries that logs useful stuff but make figuring out how you called said library very hard. For example, Django logs SQL queries but it's hard to figure out what code made the ORM query. This is a huge pain for Ajax requests - django-debug-toolbar can't help you much with those ... well, not yet. Turns out Python's logging module allows custom formatters. How about we write one ? The filter is just a class with a filter(record) method. It appears that filter can be called multiple times so we need to make sure we don't patch the record more than 1 time: class WithStacktrace(object): def filter(self, record): if not hasattr(record, 'stack_patched'): record.msg += " -- Stack: \n" + ''.join(format_stack(f=sys._getframe(1))) record.stack_patched = True return True You probably notice now the stacktrace can get rather long, and it includes useless frames from the logging module. We can fix that by blacklisting frames from logging or whatever we chose to ignore (like the django.db package): import sys from traceback import format_stack class WithStacktrace(object): def __init__(self, skip=(), limit=5): self.skip = [__name__, 'logging'] self.skip.extend(skip) self.limit = limit def filter(self, record): if not hasattr(record, 'stack_patched'): frame = sys._getframe(1) if self.skip: … -
Adding stacktraces to log messages
I always had this issue with libraries that logs useful stuff but make figuring out how you called said library very hard. For example, Django logs SQL queries but it's hard to figure out what code made the ORM query. This is a huge pain for Ajax requests - django-debug-toolbar can't help you much with those ... well, not yet. Turns out Python's logging module allows custom formatters. How about we write one? The filter is just a class with a filter(record) method. It appears that filter can be called multiple times so we need to make sure we don't patch the record more than 1 time: class WithStacktrace(object): def filter(self, record): if not hasattr(record, 'stack_patched'): record.msg += " -- Stack: \n" + ''.join(format_stack(f=sys._getframe(1))) record.stack_patched = True return True You probably notice now the stacktrace can get rather long, and it includes useless frames from the logging module. We can fix that by blacklisting frames from logging or whatever we chose to ignore (like the django.db package): import sys from traceback import format_stack class WithStacktrace(object): def __init__(self, skip=(), limit=5): self.skip = [__name__, 'logging'] self.skip.extend(skip) self.limit = limit def filter(self, record): if not hasattr(record, 'stack_patched'): frame = sys._getframe(1) if self.skip: while … -
How to Store Your Media Files in Amazon S3 Bucket
In this article, I will show you how to use Amazon Simple Storage Service (S3) to store your media files in the cloud. S3 is known and widely used for its scalability, reliability, and relatively cheap price. It is free to join and you only pay the hosting and bandwidth costs as you use it. The service is provided by Amazon.com. S3 tends to be attractive for start-up companies looking to minimize costs.S3 uses a concept of buckets which is like a storage database. Each bucket has its own url. Inside the buckets you have folders and under that you have files. In fact, directories don't actually exist within S3 buckets. The entire file structure is actually just one flat single-level container of files. The illusion of directories is actually created based on having the file names like dirA/dirB/file.If you want to browse the files in a folder-like structure, you can use Transmit FTP client on Mac OS X. It supports S3 services. Amazon browser-based console also has interface for browsing or uploading files.OK. Now let's have a look how to set up a Django project which will use S3 for media files. 1. Create a bucketAt first you will … -
Getting Started Contributing to Django
Recently I had the opportunity to attend the DjangoCon Sprint here in Chicago (see related post). One of my big take-aways from the event was that contributing to Django isn’t as daunting as I previously thought. The process is mostly straightforward and the Django team has gone a long ... -
Django Facebook 5.3
The 5.3 release makes it a lot easier to get started with Django Facebook. Documentation has had a major overhaul, many small bugs have been fixed and setting validation will complain if you make mistakes during the install. Have a look at the new docs. Especially the bit documenting how to use OpenFacebook will be interesting to many people: Getting an OpenFacebook object Making calls The full docs are linked on github. Share and Enjoy: