Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
使用django-emoji让你的Django APP显示流行的emojis图标
gaqzi 最近的开源项目 django-emoji 可心让你的django APP 在网站上显示流行的 em […] -
App enlight - log aggregation and application health monitoring service
App enlight, a Polish startup known as errormator in the past is a application-service that logs and aggregates you application health. Like for example Sentry can log exceptions and logs (like from logging module) then App Enlight does much more by hooking to the internals of the application - you will get executed SQLs, template rendering time, slow responses and more. So let us take a closer look on current app enlight features... -
Beginner's Guide to PyCon 2014
New to Python and/or conferences and attending the upcoming PyCon 2014 in Montreal, Canada? Or is this your first conference? Or perhaps your first conference longer than a weekend? Hoping to get the most out of joining thousands of Python enthusiasts? No worries! This guide will aid you in attending one of the best technical conferences on the planet. Even though I'm not attending on account of various reasons including finances, work, and surgery, I'm going to share how to get through the whole event in good shape. I'm also going to share some great tricks to optimize the event. Basics Take at least one shower per day. Please. Bring something to take notes. A paper notebook, laptop, or tablet. Anything! If you are looking for work, bring business cards. Seriously. At every meal (breakfast, lunch, dinner) make a point of sitting with or going out with different people. Introduce yourself. Make new friends and learn new things! If you can't make it to a talk, don't stress out. They are recorded and will be available later on http://www.pyvideo.org. Act Professionally (see next section) Be Professional PyCon is a professional event. Sure, lots of people are in t-shirts and are … -
Beginner's Guide to PyCon 2015
note: This post has been updated for PyCon 2015. Even though the URL is old, the content is new. New to Python and/or conferences and attending the upcoming PyCon 2015 in Montreal, Canada? Or is this your first conference? Or perhaps your first conference longer than a weekend? Hoping to get the most out of joining thousands of Python enthusiasts? No worries! This guide will aid you in attending one of the best technical conferences on the planet. Even though I'm not attending on account of various reasons including finances, work, and personal projects, I'm going to share how to get through duration of pycon in good shape. I'm also going to share some great tricks to optimize the event. Basics Take at least one shower per day. Please. Bring something to take notes. A paper notebook, laptop, or tablet. Anything! If you are looking for work, bring business cards. Seriously. At every meal (breakfast, lunch, dinner) make a point of sitting with or going out with different people. Introduce yourself. Make new friends and learn new things! If you can't make it to a talk, don't stress out. They are recorded and will be available later on http://www.pyvideo.org. Act … -
Two Scoops of Django 1.6 India Edition Sneak Peek
We finally have a finalized proof of the forthcoming Two Scoops of Django 1.6 India Edition in our hands! The US edition, on the left, is 7.5x9.25 inches. The India edition, on the right, is sized A4, which is about 8.3x11.7 inches. The US edition is slightly thicker, but not dramatically so. The cover of the India Edition has more vibrant color (admittedly slightly rumpled thanks to the clumsy hands of the male co-author). The SD memory card and garlic clove are for scale. Printing: Our Indian printer, pothi.com, has outdone themselves. We have extremely high standards and proudly say it's a BETTER printing than the US edition. The paper feels good in the hand. The slightly increased margins make it easier to annotate. In fact, it's such an amazing book we're planning on making it available world-wide. It's just that good. We appreciate pothi.com's service and attention to detail, and hope to use them for other future projects. Content: Besides the addition of 'India Edition' in the footer, the content is identical to the US edition. Pricing: Our pricing reflects the India Edition's international distribution. While it's actually more expensive to produce than our US edition, we're going to … -
Two Scoops of Django 1.6 India Edition Sneak Peek
We finally have a finalized proof of the forthcoming Two Scoops of Django 1.6 India Edition in our hands! The US edition, on the left, is 7.5x9.25 inches. The India edition, on the right, is sized A4, which is about 8.3x11.7 inches. The US edition is slightly thicker, but not dramatically so. The cover of the India Edition has more vibrant color (admittedly slightly rumpled thanks to the clumsy hands of the male co-author). The SD memory card and garlic clove are for scale. Printing: Our Indian printer, pothi.com, has outdone themselves. We have extremely high standards and proudly say it's a BETTER printing than the US edition. The paper feels good in the hand. The slightly increased margins make it easier to annotate. In fact, it's such an amazing book we're planning on making it available world-wide. It's just that good. We appreciate pothi.com's service and attention to detail, and hope to use them for other future projects. Content: Besides the addition of 'India Edition' in the footer, the content is identical to the US edition. Pricing: Our pricing reflects the India Edition's international distribution. While it's actually more expensive to produce than our US edition, we're going to … -
Two Scoops of Django 1.6 India Edition Sneak Peek
We finally have a finalized proof of the forthcoming Two Scoops of Django 1.6 India Edition in our hands! The US edition, on the left, is 7.5x9.25 inches. The India edition, on the right, is sized A4, which is about 8.3x11.7 inches. The US edition is slightly thicker, but not dramatically so. The cover of the India Edition has more vibrant color (admittedly slightly rumpled thanks to the clumsy hands of the male co-author). The SD memory card and garlic clove are for scale. Printing: Our Indian printer, pothi.com, has outdone themselves. We have extremely high standards and proudly say it's a BETTER printing than the US edition. The paper feels good in the hand. The slightly increased margins make it easier to annotate. In fact, it's such an amazing book we're planning on making it available world-wide. It's just that good. We appreciate pothi.com's service and attention to detail, and hope to use them for other future projects. Content: Besides the addition of 'India Edition' in the footer, the content is identical to the US edition. Pricing: Our pricing reflects the India Edition's international distribution. While it's actually more expensive to produce than our US edition, we're going to … -
Approval and acceptance in the tech community
For a long time, one of my fellow core developers on the Django project has had an email signature which contains the following: "I disapprove of what you say, but I will defend to the death your right to say it." -- Evelyn Beatrice Hall (summarising Voltaire) My perception of the reaction and noise around Brendan Eich's appointment (and subsequent resignation) as CEO of Mozilla has been that many (though by no means all) in the tech community haven't held true to this (though I think many would claim that they have). I'm afraid I can't be silent on this issue any more, and I have to speak out. You are more than welcome to disagree with me (as I'm sure many of you will!) but please at least hear me out. I was pushed further by a comment on a blog post (both of which have since disappeared) in which the author said that he would be very scared to speak out if he opposed gay marriage, and that fear is not the tactic we should be using to discourage this view. I agree completely with that sentiment. The current temperature in the programming community feels extremely hostile to … -
Two Scoops of Goblins
While Audrey Roy Greenfeld and I were contemplating our next Two Scoops Press book topic, it came down to a decision between Pyramid, Flask, and mythical creatures. Inspired by Django's magical flying pony, Pyramid's scary alien dude, and even the idea of a magical Flask pouring out wonderful projects, we've decided to go with mythical creatures. Specifically, we're writing about goblins, hence the title of this blog post. What that means is that the next book we publish will be fantasy. Going forward all the books we write will be fiction. If we ever write a new Two Scoops of Django book, it will be a fantasy about a magical flying pony who eats ice cream. That way we'll confuse the already muddled Amazon.com search requests for 'Django' even more. Since this is a technical blog, I'll be moving my fiction writing based articles to my author blog at dannygreenfeld.com. -
Two Scoops of Goblins
While Audrey Roy Greenfeld and I were contemplating our next Two Scoops Press book topic, it came down to a decision between Pyramid, Flask, and mythical creatures. Inspired by Django's magical flying pony, Pyramid's scary alien dude, and even the idea of a magical Flask pouring out wonderful projects, we've decided to go with mythical creatures. Specifically, we're writing about goblins, hence the title of this blog post. What that means is that the next book we publish will be fantasy. Going forward all the books we write will be fiction. If we ever write a new Two Scoops of Django book, it will be a fantasy about a magical flying pony who eats ice cream. That way we'll confuse the already muddled Amazon.com search requests for 'Django' even more. Since this is a technical blog, I'll be moving my fiction writing based articles to my author blog at danielroygreenfeld.com. -
Download CSV files via CSVResponseMixin
Providing csv files to people is annoying, but writing a custom mixin for use with your views can make it super easy. Often times we have to use a custom function, of some sort, and rejigger around how our views work to get a csv file, then set header information, and finally return a response. There is a Better Way Below is a custom mixin you can write, or use, to return a csv file based on a list of lists. class CSVResponseMixin(object): csv_filename = 'csvfile.csv' def get_csv_filename(self): return self.csv_filename def render_to_csv(self, data): response = HttpResponse(content_type='text/csv') cd = 'attachment; filename="{0}"'.format(self.get_csv_filename()) response['Content-Disposition'] = cd writer = csv.writer(response) for row in data: writer.writerow(row) return response The first few lines of code are simple. We are declaring the mixin, setting the filename, and returning the filename based on a method on the mixin. That leaves us with the render_to_csv method which takes a lsit of lists, and gives us a downloadable file. Line by Line Explanation response = HttpResponse(content_type='text/csv') We are creating a Django HttpResponse object which django returns, and we are setting the content type to a csv file so the browser knows what it is. response['Content-Disposition'] = 'attachment; filename="{0}"'.format(self.get_csv_filename()) We are … -
Django 1.6 最佳实践: 编码风格
看到这个标题, 你很有可能会跳过这篇文章. 但我们认为只需要在编码时稍加注意, 良好的编码风格会影响颇深. 1. 代码可阅读性的重要性 代码写出来之后, 更多的时间是被阅读. 一段代码可能只用了几分钟就被写了出来, 几十分钟或几小时用来测试debug, 但可能一年或 几十年后都不会再被人修改. 恰恰, 当你或者别人一年或几十年后再阅读时, 一贯简洁的编码风格显得尤为重要. 它使得你不用去猜 想代码的不连续性, 使得大项目更容易维护, 使得小项目也更容易扩展. 那么, 怎么才算是良好的编码风格呢? 避免过度缩写的变量名 清晰的写出function传入参数(argument)的名字 为class和method写注释 重构代码: 将重复的代码提取出来, 写成function或method 保持function和method简短: 一个简单的规则是, 阅读一个function或method时, 不需要翻页 这样, 当重新接触长时间没有查看的代码时, 你会发现阅读和理解代码的时间会大大缩短. 例如, 当你读到一个名为 blance_sheet_decrease的变量时, 是不是比bsd或b_s_d这样的变量名更容易理解? 类似这样的缩写名, 虽然能在编写代码是为你节 省几秒钟, 但当重新阅读时, 可能耗费你几个小时. 因此这种缩写是不值得的! 2. PEP8 PPE 8是Python官方的代码风格指导. 我们建议你详细的阅读并使用这些规范: http://www.python.org/dev/peps/pep-0008/ 需要注意的是, PEP8只适用于新的项目, 如果将PEP8带入到已有项目时, 在有代码风格冲突时, 应保持原有规范, 以防发生混乱. 举些例子, PEP 8中定义的代码规范有: 每一等级的缩进使用4个空格 在最高级function和class前空两行 class中定义的method, 应该与前面的代码空一行 关于每行字符数限制 PEP8中, 规定了每行字符数的限制是79. 因为这是绝大多数编辑器和开发团队都能支持的字符数. 但PEP8中也有条款, 可将该限制扩展到99个字符数. 我们的理解是, 当该项目是开源时, 应尽量 将字符数控制在每行79个, 而当项目是闭源时, 则可以扩大到79个字符数. 3. 关于import 我们建议import按以下顺序排列: Python标准库 Django自带库 第三方App库 项目中App库 例如: # Python标准库 from __future__ import absolute_import from math import sqrt from os.path import abspath # Django自带库 from django.db import models from django.utils.translation import ugettext_lazy as _ # 第三方App库 from django_extensions.db.models import TimeStampedModel # 项目中App库 from .models import BananaSplit 使用明确指明的相对路径引用 当在写代码时, 应当时刻注意所写的代码应当能方便的移动, 重命名和升级. 在Python中, 使用明确指明的相对路径引用 (explicit relative import), 降低了模块之间的耦合性, 为我们带来了以上三个优点. 以上代码中的"from django_extensions.db.models import TimeStampedModel"便是一个很好的例子. 避免使用* 大多数情况下, 为了避免引起不可预料的混乱, 我们都不应该使用import *. 4. 其他 虽然在PEP8中没有明确指明, 但在实践中, 因尽量使用下划线"_", 而不是横杠"-", 因为下划线对于大多数IDE和文本编辑器都很友好. 但在URl中, 两者没有差别. -
Speeding up a Django web site without touching the code
I’ve recently been tweaking my server setup for a Django 1.3 web site with the goal of making it a bit faster. Of course, there is a lot of speed to gain by improving e.g. the number of database queries needed to render a web page, but the server setup also has an effect on the web site performance. This is a log of my findings. All measurements have been done using the ab tool from Apache using the arguments -n 200 -c 20, which means that each case have been tested with 20 concurrent requests up to 200 requests in total. The tests was run from another machine than the web server, with around 45ms RTT to the server. This is not a scientific measurement, but good enough to let me quickly test my assumptions on what increases or decreases performance. The Django app isn’t particularly optimized in itself, so I don’t care much about the low number of requests per second (req/s) that it manages to process. The main point here is the relative improvement with each change to the server setup. The baseline setup is a Linode 1024 VPS (Referral link: I get USD 20 off my … -
Comics v2.2.0 released with Django 1.5 support
Version 2.2.0 of my comics aggregator is now released. It features a general upgrade of dependencies, including the move from Django 1.4 to Django 1.5, and a lot of updates to comic crawlers. The Django upgrade was completed months ago and it’s been running my Comics instance since, so it’s about time to get it released before Django 1.6 arrives in a month or two. Regarding the crawler updates, it’s a bit sad to see that many of the crawlers have been broken for months without me or anybody else noticing, but it’s hard to catch some content lacking in the middle of a firehose of similar content. I guess I’ll have to make it a monthly task to look through the crawler status page of my Comics instance and do patch releases with updated crawlers. Check out the project docs for more information about Comics and this release in particular. -
Using PayPal WPS with Cartridge (Mezzanine / Django)
I recently built a web site using Mezzanine, a CMS built on top of Django. I decided to go with Mezzanine (which I've never used before) for two reasons: it nicely enhances Django's admin experience (plus it enhances, but doesn't get in the way of, the Django developer experience); and there's a shopping cart app called Cartridge that's built on top of Mezzanine, and for this particular site (a children's art class business in Sydney) I needed shopping cart / e-commerce functionality. This suite turned out to deliver virtually everything I needed out-of-the-box, with one exception: Cartridge currently lacks support for payment methods that require redirecting to the payment gateway and then returning after payment completion (such as PayPal Website Payments Standard, or WPS). It only supports payment methods where payment is completed on-site (such as PayPal Website Payments Pro, or WPP). In this case, with the project being small and low-budget, I wanted to avoid the overhead of dealing with SSL and on-site payment, so PayPal WPS was the obvious candidate. Turns out that, with a bit of hackery, making Cartridge play nice with WPS isn't too hard to achieve. Here's how you go about it. -
Creating web applications with Django and ember.js tutorial gets an update for latest ember.js version
My tutorial about creating ember.js applications with Django got updated to the latest ember.js version and the source code got published on github. I'm planning to write more about this framework soon, as now I'm spending a lot of time working with ember and Django, django-rest-framework and other interesting libraries. Aside of that I still have some topics on my ToDo list - Facebook apps related packages (future; when they get published), more Python + electronics tutorials, and Django/Python related (like checking Cherokee server or testing AppEnlight). What you find most interesting? -
Factor Your Django Settings Into uwsgi Ini Files
Although this is certainly not the usual use case for a Django site, I am deploying a new site that will be used by several programs at the school where I work. Each program will have its own specific Django settings file with its own values (for example, the database connection info) but for the most part the sites share a base settings_production.py file. Here is a sample of this file: from mysite.settings import * DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS.append('.university.edu') INSTALLED_APPS.append( 'websso' ) MIDDLEWARE_CLASSES.append( 'django.contrib.auth.middleware.RemoteUserMiddleware' ) AUTHENTICATION_BACKENDS.append( 'websso.backends.RegistryRemoteUserBackend' ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('MYSITE_DB_NAME'), 'USER': os.environ.get('MYSITE_DB_USER'), 'PASSWORD': os.environ.get('MYSITE_DB_PASSWORD'), 'HOST': os.environ.get('MYSITE_DB_HOST'), 'PORT': '5432', } } As you can see, we get the database connection values from the environment. I am using Apache (with mod_proxy_uwsgi) and uwsgi in emperor mode to run the site, and each site has a uwsgi ini file that actually sets all the relevant per-site settings via the env configuration option. This was quite easy to set up, and this is an example uwsgi ini file: [uwsgi] chdir=/srv/myvirtualenv/mysite module=mysite.wsgi:application max-requests=5000 socket=127.0.0.1:3032 logto=/tmp/uwsgi-example.log env = DJANGO_SETTINGS_MODULE=mysite.settings_production env = MYSITE_DB_NAME=mysite_dbname env = MYSITE_DB_USER=mysite_username env = MYSITE_DB_PASSWORD=abc123 env = MYSITE_DB_HOST=mysite-dbname.hostname.us-east-1.rds.amazonaws.com So far so good -- … -
Factor Your Django Settings Into uwsgi Ini Files
Although this is certainly not the usual use case for a Django site, I am deploying a new site that will be used by several programs at the school where I work. Each program will have its own specific Django settings file with its own values (for example, the database connection info) but for the most part the sites share a base settings_production.py file. Here is a sample of this file: from mysite.settings import * DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS.append('.university.edu') INSTALLED_APPS.append( 'websso' ) MIDDLEWARE_CLASSES.append( 'django.contrib.auth.middleware.RemoteUserMiddleware' ) AUTHENTICATION_BACKENDS.append( 'websso.backends.RegistryRemoteUserBackend' ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('MYSITE_DB_NAME'), 'USER': os.environ.get('MYSITE_DB_USER'), 'PASSWORD': os.environ.get('MYSITE_DB_PASSWORD'), 'HOST': os.environ.get('MYSITE_DB_HOST'), 'PORT': '5432', } } As you can see, we get the database connection values from the environment. I am using Apache (with mod_proxy_uwsgi) and uwsgi in emperor mode to run the site, and each site has a uwsgi ini file that actually sets all the relevant per-site settings via the env configuration option. This was quite easy to set up, and this is an example uwsgi ini file: [uwsgi] chdir=/srv/myvirtualenv/mysite module=mysite.wsgi:application max-requests=5000 socket=127.0.0.1:3032 logto=/tmp/uwsgi-example.log env = DJANGO_SETTINGS_MODULE=mysite.settings_production env = MYSITE_DB_NAME=mysite_dbname env = MYSITE_DB_USER=mysite_username env = MYSITE_DB_PASSWORD=abc123 env = MYSITE_DB_HOST=mysite-dbname.hostname.us-east-1.rds.amazonaws.com So far so good -- … -
Congrats to PearlHacks Winners (Including Our Intern, Annie)!
Caleb Smith, Caktus developer, awarding the third place prize to TheRightFit creators Bipasa Chattopadhyay, Ping Fu, and Sarah Andrabi. Many congratulations to the PearlHacks third place winners who won Sphero Balls! The team from UNC’s Computer Science department created TheRightFit, an Android app that helps shoppers know what sizes will fit them and their families among various brands. Their prize of Sphero Balls, programmable balls that can interact and play games via smart phones, was presented by Caktus developer and Pearl Hacks mentor Caleb Smith as part of our sponsorship. PearlHacks, held at UNC-Chapel Hill, is a conference designed to encourage female high school and college programmers from the NC and VA area. Also, we’re deeply proud of our intern, Annie Daniel (UNC School of Journalism), who was part of the first place team for their application, The Culture of Yes. Excellent job, Annie! This is what Annie had to say about her team's first place project: The Culture of Yes was a web app that's meant to broaden the conversation on sexual assault on college campuses. We chose a flagship university from each of the 50 states, created a json file that summarized that university (population, male/female ratio, % … -
Reviewing Django REST Framework
Recently, we used Django REST Framework to build the backend for an API-first web application. Here I’ll attempt to explain why we chose REST Framework and how successfully it helped us build our software. Why Use Django REST Framework? RFC-compliant HTTP Response Codes Clients (javascript and rich desktop/mobile/tablet applications) will more than likely expect your REST service endpoint to return status codes as specified in the HTTP/1.1 spec. Returning a 200 response containing {‘status’: ‘error’} goes against the principles of HTTP and you’ll find that HTTP-compliant javascript libraries will get their knickers in a twist. In our backend code, we ideally want to raise native exceptions and return native objects; status codes and content should be inferred and serialised as required. If authentication fails, REST Framework serves a 401 response. Raise a PermissionDenied and you automatically get a 403 response. Raise a ValidationError when examining the submitted data and you get a 400 response. POST successfully and get a 201, PATCH and get a 200. And so on. Methods You could PATCH an existing user profile with just the field that was changed in your UI, DELETE a comment, PUT a new shopping basket, and so on. HTTP methods exist … -
First impressions of Django 1.7 beta upgrade in a young project
Since few days we have Django 1.7 beta, which brings many changes including built in migrations system. At the company we have one quite new project that is still in development so we decided to use it as a guinea pig and use Django 1.7b1 for it. The upgrade from 1.6 wasn't that problematic, but it required some search-and-fix actions... -
玩转Django1.7的新功能之Schema migrations
上周 Django 1.7 beta 1 released,这是Django 1.7正式版发布周期的一个重要里 […] -
Django-filter and custom querysets
Django-filter is a powerful tool, but the documentation is a little sparse. If you want to see examples of custom Filters you have to dive into the source code. I recently wanted to add a filter for methods on a custom QuerySet. Unlike custom managers, custom QuerySets allow you to chain methods. You can read this introduction or refer to the official documentation (at the time of this writing 1.7 wasn't released yet). Here is a short example of what's possible: Product.products.in_stock().price_below(100).has_color('red') You get the idea, it's just a convenient way to write shorter code. So I had my methods and wanted to use them with django-filter, but it took a while to figure out how. After some digging I took the DateRangeField class as a blueprint (0.7 source) and came up with this filter: class QuerySetFilter(django_filters.ChoiceFilter): def __init__(self, options, *args, **kwargs): self.options = options kwargs['choices'] = [ (key, value[0]) for key, value in six.iteritems(self.options)] super(QuerySetFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): method = self.options[value][1]['method'] if 'args' in self.options[value][1]: args = self.options[value][1]['args'] else: args = () if 'kwargs' in self.options[value][1]: kwargs = self.options[value][1]['kwargs'] else: kwargs = {} if method == '': return qs elif not hasattr(qs, method): raise Exception("Improperly configured", … -
Django-filter and custom querysets
Django-filter is a powerful tool, but the documentation is a little sparse. If you want to see examples of custom Filters you have to dive into the source code. I recently wanted to add a filter for methods on a custom QuerySet. Unlike custom managers, custom QuerySets allow you to chain methods. You can read this introduction or refer to the official documentation (at the time of this writing 1.7 wasn't released yet). Here is a short example of what's possible: Product.products.in_stock().price_below(100).has_color('red') You get the idea, it's just a convenient way to write shorter code. So I had my methods and wanted to use them with django-filter, but it took a while to figure out how. After some digging I took the DateRangeField class as a blueprint (0.7 source) and came up with this filter: class QuerySetFilter(django_filters.ChoiceFilter): def __init__(self, options, *args, **kwargs): self.options = options kwargs['choices'] = [ (key, value[0]) for key, value in six.iteritems(self.options)] super(QuerySetFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): config = self.options[value][1] method = config.get('method', '') args = config.get('args', ()) kwargs = config.get('kwargs', {}) if method == '': return qs elif not hasattr(qs, method): raise Exception("Improperly configured", "Unknown QuerySet method %s" % method) return getattr(qs, method)(*args, **kwargs) … -
Django-filter and custom querysets
Django-filter is a powerful tool, but the documentation is a little sparse. If you want to see examples of custom Filters you have to dive into the source code. I recently wanted to add a filter for methods on a custom QuerySet. Unlike custom managers, custom QuerySets allow you to chain methods. You can read this introduction or refer to the official documentation (at the time of this writing 1.7 wasn't released yet). Here is a short example of what's possible: Product.products.in_stock().price_below(100).has_color('red') You get the idea, it's just a convenient way to write shorter code. So I had my methods and wanted to use them with django-filter, but it took a while to figure out how. After some digging I took the DateRangeField class as a blueprint (0.7 source) and came up with this filter: class QuerySetFilter(django_filters.ChoiceFilter): def __init__(self, options, *args, **kwargs): self.options = options kwargs['choices'] = [ (key, value[0]) for key, value in six.iteritems(self.options)] super(QuerySetFilter, self).__init__(*args, **kwargs) def filter(self, qs, value): config = self.options[value][1] method = config.get('method', '') args = config.get('args', ()) kwargs = config.get('kwargs', {}) if method == '': return qs elif not hasattr(qs, method): raise Exception("Improperly configured", "Unknown QuerySet method %s" % method) return getattr(qs, method)(*args, **kwargs) …