Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
How To Import a CSV (or TSV) file into a Django Model
Recently I downloaded a US zip code data file in comma separated (CSV) format. Below are the steps and python script that I used to import that data into a django model for my site Wantbox.com. The Steps to Import CSV Data into Django: Create your django model (mine is called “ZipCode”, see below). Create [...] -
First steps with Compass
A lightning talk by Thijs Jonkman at the Dutch Plone User Day once again brought Compass to my attention. I’ve read about it on other occasions, but I never actually tried it. But Thijs really made me want to try it for myself. First of all a bit of explanation about Compass. According to the website it is an “open source CSS authoring framework which uses the Sass stylesheet language."1 Let’s process this backwards… Sass, which stands for “Syntactically Awesome Stylesheets”, is an extension of CSS3 and it adds a lot of useful features (e.g. variables, and mixins). These features make CSS development a lot easier. (And, speaking as a Python developer, more fun.) Compass is a framework that makes working with Sass even better. Its core contains all kinds of useful mixins for e.g. CSS resets, CSS3 borders, a footer that sticks to the bottom of the page and code to help you with sprites, to name just a few. And if you need more than Compass delivers out of the box, there are many more plugins available. Getting started To get an impression of Compass, I decided to retrofit the CSS for this website with Compass. Luckily Brandon … -
Django pro tip: if you only use the admin
If you have a project that only exposes the admin you should just use the 500/404 templates from the admin. Put this in your project’s urls.py: from django.utils.functional import curry from django.views.defaults import server_error, page_not_found handler500 = curry(server_error, template_name='admin/500.html') handler404 = curry(page_not_found, template_name='admin/404.html') I wonder why django doesn’t mention those templates in the docs … If you have other drop-in apps that need authentication (like rosetta or sentry) bare in mind that the admin doesn’t have a reusable login view so you must hook one. You should just reuse django admin’s login template. Put this in the urlpatterns (don’t forget to match it to LOGIN_URL in the settings): url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}), You might note that this is not very DRY but actually the LOGIN_URL might differ than the one in the urlpatterns (eg: you mount the django wsgi handler on a non-root path). Tagged: django, python -
Django pro tip: if you only use the admin
If you have a project that only exposes the admin you should just use the 500/404 templates from the admin. Put this in your project's urls.py: from django.utils.functional import curry from django.views.defaults import server_error, page_not_found handler500 = curry(server_error, template_name='admin/500.html') handler404 = curry(page_not_found, template_name='admin/404.html') I wonder why django doesn't mention those templates in the docs ... If you have other drop-in apps that need authentication (like rosetta or sentry) bare in mind that the admin doesn't have a reusable login view so you must hook one. You should just reuse django admin's login template. Put this in the urlpatterns (don't forget to match it to LOGIN_URL in the settings): url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}), You might note that this is not very DRY but actually the LOGIN_URL might differ than the one in the urlpatterns (eg: you mount the django wsgi handler on a non-root path). -
Django pro tip: if you only use the admin
If you have a project that only exposes the admin you should just use the 500/404 templates from the admin. Put this in your project's urls.py: from django.utils.functional import curry from django.views.defaults import server_error, page_not_found handler500 = curry(server_error, template_name='admin/500.html') handler404 = curry(page_not_found, template_name='admin/404.html') I wonder why django doesn't mention those templates in the docs ... If you have other drop-in apps that need authentication (like rosetta or sentry) bare in mind that the admin doesn't have a reusable login view so you must hook one. You should just reuse django admin's login template. Put this in the urlpatterns (don't forget to match it to LOGIN_URL in the settings): url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}), You might note that this is not very DRY but actually the LOGIN_URL might differ than the one in the urlpatterns (eg: you mount the django wsgi handler on a non-root path). -
Caktus Hosts 3rd Django Sprint in North Carolina
Here at Caktus, we love Django and use it to make all of our web applications. To help support the Django community, we are hosting a development sprint on November 12th and 13th at our office in Carrboro, NC in preparation for the 1.4 release. The sprint is a great is an excuse for people to ... -
Caktus Hosts 3rd Django Sprint in North Carolina
Here at Caktus, we love Django and use it to make all of our web applications. To help support the Django community, we are hosting a development sprint on November 12th and 13th at our office in Carrboro, NC in preparation for the 1.4 release. The sprint is a great is an excuse for people to ... -
Caktus Hosts 3rd Django Sprint in North Carolina
Here at Caktus, we love Django and use it to make all of our web applications. To help support the Django community, we are hosting a development sprint on November 12th and 13th at our office in Carrboro, NC in preparation for the 1.4 release. The sprint is a great is an excuse for people to ... -
Making Django's signals asynchronous with Celery
Update: A comment on the ticket I opened by Alex Gaynor brought up a point that I hadn't fully considered. It's worth noticing before going further in this post and also worth pointing out my monkey patch doesn't answer this question. After speaking with Carl, I'm marking this as wontfix because it is non-obvious as to whether pickling a Signal should include the registered receivers, and how that interacts with the weak referencing, since there's no obvious semantic it seems better not to guess. I really enjoy working with both Django's signal framework and Celery tasks. Today it occured to me that it would be useful to combine the two and have “asynchronous signals”. Here is the solution that I came up with, read on below if you want to see how I arrived at this and why we need to monkey patch. from celery.task import task from django.db.models.signals import post_save from myproject.models import MyModel # Warning. Monkey patch. from django.dispatch.dispatcher import Signal def reducer(self): return (Signal, (self.providing_args,)) Signal.__reduce__ = reducer # With the patch done, we can now connect to celery tasks. @task(ignore_result=True) def async_post_save(sender, instance, **kwargs): # do something with the instance. pass post_save.connect(async_post_save.delay, sender=MyModel) The first solution … -
From server hater to server lover
From server hater to server lover -
Improve Django SQL Queries Using Debug Toolbar
Django’s database querying is there to make life easier but it’s also easy to forget about the SQL that is still generated under the hood. When using Django’s query objects it’s extremely difficult to know how often the database is being hit and with what SQL queries. We often write queries in our views, check [...] -
Django CMS Plugins with selectable template …
A simple explanation how to create Django CMS plugins that allow the administrator to select different templates. This is extremely useful if you need to use the same plugin in several sections with different designs. -
django and jQuery templates
KnockoutJS is a great way to create relationships between data objects, and interface elements. You can, for instance, bind a date value to an html ``input[type=date]`` element, and have it converted into a proper date object. You could then display data based on this, or do anything else you wanted. KnockoutJS 1.2 (the currently stable version) defaults to using jQuery templates (jQuery-tmpl), which happen to use conflicting syntax to django templates. For instance, if you were to have the following in your django template file: {% highlight html+django %} {{ "{{if foo > bar"}} }} Stuff Here {{ "{{/if"}} }} {% endhighlight %} Then django would attempt to process that, as it uses bits that look like django's template engine's value placeholder. A workaround to this is to look at doing something like wrapping any jQuery templates in something that prevents django from interpreting it. But I don't like that solution. For starters, almost every text editor will try to syntax highlight data between `` -
Why CustomUser subclasses are not such a good idea
### Background The system I work on has People who may or may not be Users, and very infrequently Users who may not be a Person. In fact, an extension to the system has meant that there will be more of these: a User who needs to be able to generate reports (say, a Franchisor who needs to only be able to access aggregate data from franchises, that might belong to multiple companies) who is never rostered on for shifts, which is what the Person class is all about. Anyway, the long and the short of this was that I thought it might be a good idea to look at sub-classing User for ManagementUser. I guess I should have listened to those smarter than me who shouted that sub-classing User is not cool. Although they never gave any concrete reasons, but now I have one. You cannot easily convert a superclass object to a specialised sub-class. Once a user is a User, it's hard to make them into a ManagementUser. It can be done: the following code will take a User (or any parent class) object, a User (or whatever) subclass, and any other keyword arguments that should be passed … -
Improve Django SQL Queries Using Debug Toolbar
Django’s database querying is there to make life easier but it’s also easy to forget about the SQL that is still generated under the hood. When using Django’s query objects it’s extremely difficult to know how often the database is being hit and with what SQL queries. We often write queries in our views, check that they return what we want, then forget them. Lots of the time that is okay but often we’ll run into performance problems later down the road due to too many database queries. Even if you only have one query in your view, the template might generate more queries without you knowing about them. Luckily we have the django debug toolbar to show us how many queries are being sent to our database for a single page request. So I’m going to go through an example of using the debug toolbar to make a performance improvement for a django view. I’m not going into how to install the debug tool bar because it’s all on their download page here. I created a simple test site to demonstrate how to find and improve database hits. It has one page which just lists a load of comments … -
Conference Talks I want to see
I'm writing this the day after Github's pycodeconf ended. That was an amazing conference, and I'll be blogging it soon (I'll also be writing about PyCon Australia, PyCon New Zealand, and DjangoCon US). With all this conference experience very current in my head, things I've seen and done at them, and the deadline for PyCon US submissions coming up, here are some talks I really want to see happen in the next six months. If not at PyCon US, then please consider these for other forthcoming events!Note: Couldn't do my preferred 'linkify' as well as I liked thanks to bad hotel internet. I'll clean it up later.Advanced SQL Alchemy UsageI think the uber-powerful SQL Alchemy ORM needs the same sort of treatment me and Miguel Araujo gave on Advanced Django Forms Usage. Not a 30 tutorial or overview or 'State of', but tricks and patterns by someone who has used it frequently on more than one project. Multiple projects is important because the speaker should have had the chance to try multiple approaches. Start with something simple like a TimeStampModel all model classes might inherit from, then go into deeper and and more complex technical detail. Finish the talk with something … -
Propietariosonline, la visió tècnica
Aquesta setmana és obligat parlar del llançament de propietariosonline.com, una aplicació web per a la gestió de comunitats de propietaris que hem llançat des d'APSL. Junt amb la web de trobacasa forma el gruix dels projectes propis. Actualment estam en fase beta, és a dir, mirant de netejar tots els possibles errors que puguin haver passat els nostres testeigs inicials i sobre tot, copsant les opinions dels beta-testers, per tal d'anar incorporant els suggeriments de millora que ens facin. Personalment una de les coses que més em motiven a l'hora de fer un programa és que aquest sigui útil, i per això res millor que fer-lo en col·laboració amb els usuaris potencials del programa. Com que supòs que no llegiu això per a que us parli de la gestió de les comunitats de propietaris, aniré entrant en matèria. L'aplicació està desenvolupada amb Django en la seva versió 1.3. És la primera aplicació grossa en la que feim un ús intensiu de les generic class views. Com molts sabreu abans de la versió 1.3 la manera de passar del la petició (el request) cap a la sortida html era mitjançant una funció que es posava a l'arxiu views.py. Amb la versió … -
Why I don't like class-based generic views
… because I have to replace this: def category(request, slug, language): translation.activate(language or 'ru') category = get_object_or_404(models.Category, slug=slug) return object_list(request, template_name = 'marcus/category.html', queryset = models.Article.public.language(language).filter(categories=category), paginate_by = settings.MARCUS_PAGINATE_BY, extra_context = { 'category': models.Translation(category, language), 'language': language, }, ) with this: class Category(generic.ListView): template_name = 'marcus/category.html' paginate_by = settings.MARCUS_PAGINATE_BY def get_queryset(self): self.category = get_object_or_404(models.Category, slug=self.args[0]) return models.Article.public.language(self.args[1]).filter(categories=self.category) def get_context_data(self, **kwargs): translation.activate(self.args[1] or 'ru') context = super(Category, self).get_context_data(**kwargs) context.update({ 'category': models.Translation(self.category, self.args[1]), 'language': self.args[1], }) return context Now, these snippets might not look strikingly different from the first sight so let me break them down for you and explain my point: When your code is a function it is this function that actually works and calls other functions. When your code lives in overridden methods, something else works elsewhere and calls your code. This is called "inversion of control" and it makes code harder to read because you no longer see why and in which order things happen. This is not necessarily a bad thing (the whole framework works by inverting control, after all) but in this particular case it did make me think harder. In the original code I call translation.activate before anything else to make sure that any code … -
Dutch Django meeting in Amsterdam summaries
-
The home office
The home office -
Some Pull Requests
I have had a number of pull requests backing up on my personal projects that I wanted to get to but time always gets squeezed out of the day before I have a chance to look into them. Well, this afternoon, I just made the time. I pulled in changes, commented on commits and requests, and published new releases to PyPI. Here is a summary of changes across four different projects: postman This was a sample utility that I wrote for an article that I was commissioned to write for the Python AWS portal. Turns out I guess it has been useful to some folks, even to the point where I got some pull requests. I really don't use this utility much anymore but was thankful for the pull requests nonetheless. Graham Poulter, from Cape Town, added some excellent improvements in Pull Request #5. I especially liked the use of the print function and string formatters, as well as showing more structured output that is sure to be more useful to the end user. The only thing that I'd like to see changed is the commits he made to the setup.py. I did not go ahead and pull all the … -
Dutch Django meeting in Amsterdam, Wednesday 5 Oktober
-
Ведущие разработчики о будущем Джанго
Во время последнего DjangoCon я пересёкся с несколькими из ведущих разработчиков и попросил их поделиться своими взглядами на будущее Джанго. Идея едва ли свежая — любого лидера чего бы то ни было постоянно достают вопросами о БУДУЩЕМ. Но у меня был и свой резон. По прошествии некоторого времени вдали от Джанго-разработки, мне было интересно, куда она движется, а также хотелось найти в себе мотивацию снова включиться в процесс. Стоит заметить, что все интервью были независимы друг от друга, и мои собеседники не знали о них заранее. Записывал разговоры я старым и совершенно нетехнологичным способом — делая заметки на бумажке, поэтому всё, что написано дальше, это именно заметки, а не точные слова. Джейкоб Каплан-Мосс Джейкоб — один из первоначальных разработчиков Джанго. Его диктаторская воля часто является последней в разрешении споров раз и навсегда. Что ждёт Джанго дальше? Я не знаю! Нет никакого генерального плана. Джанго следует за сообществом, мы слушаем, чего хотят люди. Что бы лично вам хотелось видеть в Джанго? Это ни в коем случае не "официальная" позиция, но вот несколько вещей: замена auth на что-нибудь получше, более гибкое Джанго не очень хорошо подходит для real-time веб-сервисов, было бы хорошо иметь такую поддержку … и хотя это не личная хотелка, … -
Ведущие разработчики о будущем Джанго
Во время последнего DjangoCon я пересёкся с несколькими из ведущих разработчиков и попросил их поделиться своими взглядами на будущее Джанго. Идея едва ли свежая — любого лидера чего бы то ни было постоянно достают вопросами о БУДУЩЕМ. Но у меня был и свой резон. По прошествии некоторого времени вдали от Джанго-разработки, мне было интересно, куда она движется, а также хотелось найти в себе мотивацию снова включиться в процесс. Стоит заметить, что все интервью были независимы друг от друга, и мои собеседники не знали о них заранее. Записывал разговоры я старым и совершенно нетехнологичным способом — делая заметки на бумажке, поэтому всё, что написано дальше, это именно заметки, а не точные слова. Джейкоб Каплан-Мосс Джейкоб — один из первоначальных разработчиков Джанго. Его диктаторская воля часто является последней в разрешении споров раз и навсегда. Что ждёт Джанго дальше? Я не знаю! Нет никакого генерального плана. Джанго следует за сообществом, мы слушаем, чего хотят люди. Что бы лично вам хотелось видеть в Джанго? Это ни в коем случае не "официальная" позиция, но вот несколько вещей: замена auth на что-нибудь получше, более гибкое Джанго не очень хорошо подходит для real-time веб-сервисов, было бы хорошо иметь такую поддержку … и хотя это не личная хотелка, … -
Neil Gaiman’s Anansi Boys…
A story about a journey in Greece, a bartender, an unexpected gift and the best dedication I have ever read.