Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
CSS Hacking to make my code samples legible
I've been very happy with Pelican as a blog engine so far, and haven't even moved off the sample theme. There's just been one problem: Myself and others have had a lot of trouble reading the code snippets. I didn't have time to cook up a full Pelican theme, so instead I just hacked the local CSS files. The problem with this hack is that every time I regenerate the blog I have to copy the right CSS files into place. So next week when I have time I'll do a proper Pelican theme. In the meantime, enjoy! from random import shuffle class Meal(object): def __init__(self): self.food_type = ['Beef', 'Fish', 'Vegetarian', 'Chicken'] shuffle(self.food_type) -
CSS Hacking to make my code samples legible
I've been very happy with Pelican as a blog engine so far, and haven't even moved off the sample theme. There's just been one problem: Myself and others have had a lot of trouble reading the code snippets. I didn't have time to cook up a full Pelican theme, so instead I just hacked the local CSS files. The problem with this hack is that every time I regenerate the blog I have to copy the right CSS files into place. So next week when I have time I'll do a proper Pelican theme. In the meantime, enjoy! from random import shuffle class Meal(object): def __init__(self): self.food_type = ['Beef', 'Fish', 'Vegetarian', 'Chicken'] shuffle(self.food_type) -
AOP in Python API design - Douwe van der Meij
-
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 … -
Choosing an API framework for Django
First off, out of the box, Django lets you construct API responses with a little work. All you need to do is something like this: # Copied from https://docs.djangoproject.com/en/1.4/topics/class-based-views/#more-than-just-html from django import http from django.utils import simplejson as json class JSONResponseMixin(object): def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. return json.dumps(context) Once you get that mixin, use it in your views like so: # modified from djangoproject.com sample code from django.utils import simplejson as json class JSONDetailView(JSONResponseMixin, MyCustomUserView): def convert_context_to_json(self, context): context['objects'] = User.objects.values('first_name','last_name','is_active') return json.dumps(context) This works pretty well in a number of simple cases, but doing things like pagination, posting of data, metadata, API discovery, and other important things ends up being a bit more work. This is where the resource oriented API frameworks come in. What makes a decent API Framework? … -
Choosing an API framework for Django
First off, out of the box, Django lets you construct API responses with a little work. All you need to do is something like this: # Copied from https://docs.djangoproject.com/en/1.4/topics/class-based-views/#more-than-just-html from django import http from django.utils import simplejson as json class JSONResponseMixin(object): def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. return json.dumps(context) Once you get that mixin, use it in your views like so: # modified from djangoproject.com sample code from django.utils import simplejson as json class JSONDetailView(JSONResponseMixin, MyCustomUserView): def convert_context_to_json(self, context): context['objects'] = User.objects.values('first_name','last_name','is_active') return json.dumps(context) This works pretty well in a number of simple cases, but doing things like pagination, posting of data, metadata, API discovery, and other important things ends up being a bit more work. This is where the resource oriented API frameworks come in. What makes a decent API Framework? … -
New pages available
We added the Zurich page to give you some more details about how to get in, how to get to our locations and how you get around in Zurich.We will soon add even more information about where to go in Zurich to get food and drinks and other useful information. In the meantime, if you have any questions or problems, please don't hesitate to contact us via Twitter or email.See you soon in Zurich! -
Django Requirements for a project
Today I'm starting a new project. I'm working as fast as I can and hope to launch on Friday. What are my package dependencies? Django==1.4 Unlike my last quick project which was Flask, this effort really falls into Django's sweet spot. I need sessions, forms, templates, and models to do things in an ideal Django pattern. psycopg2==2.4.5 I need transactions and hard-type validation in the database, which means PostgreSQL. If I didn't need transactions or the hard-type validation I would consider MongoDB instead. django-debug-toolbar==0.9.4 Because not using this tool is insane. django-extensions==0.8 Because amongst other things this library gives you, I never want to write my own TimeStampedModel ever again. :-) South==0.7.5 Django gives you the freedom to migrate data in the way you want. The way I want to do it is via South. django-registration==0.8.0 Normally django-social-auth is my go-to tool for registration, but in this case I need simple username/password registration. This is a very solid tool, but you do have to make your own templates or find someone's fork that has a copy of templates that match. django-floppyforms==0.4.7 An excellent tool for making your forms HTML5-ish out of the box. django-crispy-forms==1.1.3 The child of my own django-uni-forms, … -
Django Requirements for a project
Today I'm starting a new project. I'm working as fast as I can and hope to launch on Friday. What are my package dependencies? Django==1.4 Unlike my last quick project which was Flask, this effort really falls into Django's sweet spot. I need sessions, forms, templates, and models to do things in an ideal Django pattern. psycopg2==2.4.5 I need transactions and hard-type validation in the database, which means PostgreSQL. If I didn't need transactions or the hard-type validation I would consider MongoDB instead. django-debug-toolbar==0.9.4 Because not using this tool is insane. django-extensions==0.8 Because amongst other things this library gives you, I never want to write my own TimeStampedModel ever again. :-) South==0.7.5 Django gives you the freedom to migrate data in the way you want. The way I want to do it is via South. django-registration==0.8.0 Normally django-social-auth is my go-to tool for registration, but in this case I need simple username/password registration. This is a very solid tool, but you do have to make your own templates or find someone's fork that has a copy of templates that match. Update 2013/12/17: django-registration is no longer maintained and doesn't entirely work with modern Django's new user model system. Use django-allauth … -
Travis, give me my data back!
Inspired from this blog post about "Using Travis-CI With Python and Django" I started playing around to make this recipe fit my expectation from a CI enviroment. Running tests is the bare bottom of the whole thing. Email notifications and the handy badge to display in the project webpage are ok, but if you want to get somewhere metrics and coverage reports are the key to get the most out of the -
Don’t Deploy Broken Code
It’s been rather quiet around here lately, and that’s mainly due to the fact that I have a new job. I’m working as a Django application developer for a company based in Leicester. My job involves taking care of pretty much all the web-related technologies I have blogged about previously, and it challenges me every day. Since I started in February, I have put into place the software and processes I described in my 3-part series about Django in Production. In this post, though, I’d like to describe an extra nifty little trick I added to the deployment process: checking the project’s build status in Jenkins before allowing a deploy to continue. By performing this check before every deploy, we can reduce the risk that potentially broken code ever touches the production environment. Of course, its effectiveness is very much reliant on the quality and coverage of the unit tests but, as they say, every little helps! <!–more–> As I describe in Django in Production: Part 3, Fabric makes a great tool for automatic deployments (though there is an argument for not using this process, excellently described by Hynek Schlawack). To help reduce the risk of making an embarrassing mistake, … -
Distributing Work in Python Without Celery
We've been migrating a lot of data to various places lately at DISQUS. These generally have been things like running consistancy checks on our PostgreSQL shards, or creating a new system which requires a certain form of denormalized data. It usually involves iterating through the results of an en... -
Distributing Work in Python Without Celery
We've been migrating a lot of data to various places lately at DISQUS. These generally have been things like running consistancy checks on our PostgreSQL shards, or creating a new system which requires a certain form of denormalized data. It usually involves iterating through the results of an en... -
"Day against DRM": pragmatic programmer books are always DRM free
-
Distributing Work in Python Without Celery
We’ve been migrating a lot of data to various places lately at DISQUS. These generally have been things like running consistancy checks on our PostgreSQL shards, or creating a new system which requires a certain form of denormalized data. It usually involves iterating through the results of … -
Using Travis-CI with Python and Django
I’ve been using Travis-CI for a while now. Both my personal projects, and even several of the libraries we maintain at DISQUS rely on it for Continuous Integration. I figured it was about time to confess my undenying love for Travis, and throw up some notes about the defaults we use in our … -
Using Travis-CI with Python and Django
I've been using Travis-CI for a while now. Both my personal projects, and even several of the libraries we maintain at DISQUS rely on it for Continuous Integration. I figured it was about time to confess my undenying love for Travis, and throw up some notes about the defaults we use in our projec... -
On Fixtures and Factories
We’ve made it a general rule to move away from relying on fixtures in our projects. The main reasons are… -
On Fixtures and Factories
Click here to see this post in it's natural habitat and to watch and leave comments. We’ve made it a general rule to move away from relying on fixtures in our projects. The main reasons are: Fixtures are fragile. They often break when the schema changes or even worse they appear to work but introduce subtle bugs. Extra work is sometimes needed in order to make fixtures portable (for example defining natural keys). Processing large fixtures can be very slow, which slows down installation and testing cycles. Other smart people in the community are recommending the same approach. We look for good tools that are usually classified as either data generation or fixture factory. We’ve had some success with django-whatever and wanted to share a few tips. Some of the benefits of django-whatever: Generating one or many instances of a Model can be done in a line or two of code. Easy to handle things like non-standard primary keys or recursive relationships Using a random generator, you get fuzz testing for free. Like all powerful tools, it is easy to accidentally inflict pain. A few lessons we’ve learned: If you have tests that fail randomly, it may be caused by … -
Python Application Deployment with Native Packages
Speed, reproducibility, easy rollbacks, and predictability is what we strive for when deploying our diverse Python applications. And that’s what we achieved by leveraging virtual environments and Linux system packages. Preamble & Disclaimer To avoid excessive length, I’ll assume you’re somewhat experienced in DevOps/deployment matters and at least loosely familiar with Fabric to follow the examples. I also won’t be explaining configuration management like Ansible, Puppet, Chef or Salt. To reap all of the benefits, you’ll need to run a private debian repository server for your packages. That’s not hard, but it takes some effort. Fortunately, you can avoid running your own debian repository and still gain most of the advantages: a debian package (or a rpm package for that matter) can also be installed by hand using dpkg -i your-package.deb (rpm -Uhv your-package.rpm). If you want to go really light (or don’t have sufficient privileges on the production servers to install packages), you can employ most of the guidelines here except using vanilla tar balls instead of system packages and do the work of the package manager using custom tooling. The key point I’m trying to make is that the best way to have painless and reproducible deployments is … -
Using Travis-CI with Python and Django
I've been using Travis-CI for a while now. Both my personal projects, and even several of the libraries we maintain at DISQUS rely on it for Continuous Integration. I figured it was about time to confess my undenying love for Travis, and throw up some notes about the defaults we use in our projec... -
Working around Django's ORM to do interesting things with GFKs
In this post I want to discuss how to work around some of the shortcomings of djangos ORM when dealing with Generic Foreign Keys (GFKs). At the end of the post I'll show how to work around django's lack of correctly CAST-ing when the generic foreign key is of a different column type than the objects it may point to. -
Working around Django's ORM to do interesting things with GFKs
In this post I want to discuss how to work around some of the shortcomings of djangos ORM when dealing with Generic Foreign Keys (GFKs). At the end of the post I'll show how to work around django's lack of correctly CAST-ing when the generic foreign key is of a different column type than the objects it may point to. A quick primer on content-types and GFKs If the Generic Foreign Key did not exist, it would be necessary to invent it Thanks to the content-types framework, part of django.contrib, we do not have to do any inventing, however. The content-types framework is an app that is responsible for mapping python models to the database layer -- a dirty job, but it makes a number of other things easier to implement. Content-types are used to provide granular permissions via the auth/permissions framework and, notably, they have been used to implement GFKs. A GFK is simply a foreign key to a content-type and an additional column to store a related primary key. It is not really a foreign key at all in the sense of it being an actual database constraint. Nor is it a foreign key in the same sense … -
Working around Django's ORM to do interesting things with GFKs
In this post I want to discuss how to work around some of the shortcomings of djangos ORM when dealing with Generic Foreign Keys (GFKs). At the end of the post I'll show how to work around django's lack of correctly CAST-ing when the generic foreign key is of a different column type than the objects it may point to. A quick primer on content-types and GFKs If the Generic Foreign Key did not exist, it would be necessary to invent it Thanks to the content-types framework, part of django.contrib, we do not have to do any inventing, however. The content-types framework is an app that is responsible for mapping python models to the database layer -- a dirty job, but it makes a number of other things easier to implement. Content-types are used to provide granular permissions via the auth/permissions framework and, notably, they have been used to implement GFKs. A GFK is simply a foreign key to a content-type and an additional column to store a related primary key. It is not really a foreign key at all in the sense of it being an actual database constraint. Nor is it a foreign key in the same sense … -
Working around Django's ORM to do interesting things with GFKs
In this post I want to discuss how to work around some of the shortcomings of djangos ORM when dealing with Generic Foreign Keys (GFKs). At the end of the post I'll show how to work around django's lack of correctly CAST-ing when the generic foreign key is of a different column type than the objects it may point to. A quick primer on content-types and GFKs If the Generic Foreign Key did not exist, it would be necessary to invent it Thanks to the content-types framework, part of django.contrib, we do not have to do any inventing, however. The content-types framework is an app that is responsible for mapping python models to the database layer -- a dirty job, but it makes a number of other things easier to implement. Content-types are used to provide granular permissions via the auth/permissions framework and, notably, they have been used to implement GFKs. A GFK is simply a foreign key to a content-type and an additional column to store a related primary key. It is not really a foreign key at all in the sense of it being an actual database constraint. Nor is it a foreign key in the same sense …