Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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) … -
Using tox with Django projects
Today I was adding tox and Travis-CI support to a Django project, and I ran into a problem: our project doesn’t have a setup.py. Of course I could have added one, but since by convention we don’t package our Django projects (Django applications are a different story) – instead we use virtualenv and pip requirements files - I wanted to see if I could make tox work without changing our project. Turns out it is quite easy: just add the following three directives to your tox.ini. In your [tox] section tell tox not to run setup.py: skipsdist = True In your [testenv] section make tox install your requirements (see here for more details): deps = -r{toxinidir}/dev-requirements.txt Finally, also in your [testenv] section, tell tox how to run your tests: commands = python manage.py test Now you can run tox, and your tests should run! For reference, here is a the complete (albeit minimal) tox.ini file I used: [tox] envlist = py27 skipsdist = True [testenv] deps = -r{toxinidir}/dev-requirements.txt setenv = PYTHONPATH = {toxinidir}:{toxinidir} commands = python manage.py test The post Using tox with Django projects appeared first on David Murphy. -
The limits of "unlimited" vacation
Obligatory Disclaimer: this post discusses unlimited vacation policies. My employer (Heroku) has one such policy. However, this post isn’t really specifically about Heroku’s policy; it’s about the concept in general, not any specific implementation. As is always the case, on this site I speak for myself, not my company or anyone else. Many companies, especially tech companies, have adopted “unlimited” vacation policies — instead of a set number of days of paid time off (PTO), employees are told something along the lines “take as much time as you need”. -
Using django-tables2, django-filters and django-crispy-forms together
I was recently working on a very CRUDy prototype and decided to use some Django applications and tools together I hadn't combined before: Django-tables2, an excellent application that allows you to quickly build tables Django-filter for easy filtering Django-crispy-forms for easy form creation A view that uses all three apps together could look like this: class FooTableView(TemplateView): template_name = 'myapp/foo_list.html' def get_queryset(self): return Foo.objects.all() def get_context_data(self, **kwargs): context = super(FooTableView, self).get_context_data(**kwargs) filter = FooFilter(self.request.GET, queryset=self.get_queryset()) filter.form.helper = FooFilterFormHelper() table = FooTable(filter.qs) RequestConfig(self.request).configure(table) context['filter'] = filter context['table'] = table return context While this is a basic example there's still a lot going on. The get_context_data method gets called automatically by the TemplateView and populates that template context with our filter and table objects. At first we create an instance of FooFilter and pass it the request's GET data, and the queryset to work on. The filter does what you'd expect and filters the queryset. The filter object also includes a form that's used to filter the data. We inject a crispy form helper to style the form. At last we create the table object based on our filtered queryset and configure it. Displaying everything on the frontend now becomes as easy … -
Using django-tables2, django-filter and django-crispy-forms together
I was recently working on a very CRUDy prototype and decided to use some Django applications and tools together I hadn't combined yet: Django-tables2, an excellent application that allows you to quickly build tables Django-filter for easy filtering Django-crispy-forms for easy form creation A view that uses all three apps together could look like this: from django.views.generic import TemplateView from django_tables2 import RequestConfig # Your write the four classes imported below # (and pick a better location) from foo.models import Foo from foo.models import FooFilter from foo.models import FooTable from foo.models import FooFilterFormHelper class FooTableView(TemplateView): template_name = 'app/foo_table.html' def get_queryset(self, **kwargs): return Foo.objects.all() def get_context_data(self, **kwargs): context = super(FooTableView, self).get_context_data(**kwargs) filter = FooFilter(self.request.GET, queryset=self.get_queryset(**kwargs)) filter.form.helper = FooFilterFormHelper() table = FooTable(filter.qs) RequestConfig(self.request).configure(table) context['filter'] = filter context['table'] = table return context While this is a basic example there's still a lot going on. The get_context_data() method gets called automatically by the TemplateView and populates the template context with the filter and table objects. At first the code creates an instance of your FooFilter (django_filters.FilterSet) and passes it the request's GET data, and the queryset to work on. The filter does what you'd expect and filters the queryset. The filter object also includes … -
Using django-tables2, django-filter and django-crispy-forms together
I was recently working on a very CRUDy prototype and decided to use some Django applications and tools together I hadn't combined yet: Django-tables2, an excellent application that allows you to quickly build tables Django-filter for easy filtering Django-crispy-forms for easy form creation A view that uses all three apps together could look like this: from django.views.generic import TemplateView from django_tables2 import RequestConfig # Your write the four classes imported below # (and pick a better location) from foo.models import Foo from foo.models import FooFilter from foo.models import FooTable from foo.models import FooFilterFormHelper class FooTableView(TemplateView): template_name = 'app/foo_table.html' def get_queryset(self, **kwargs): return Foo.objects.all() def get_context_data(self, **kwargs): context = super(FooTableView, self).get_context_data(**kwargs) filter = FooFilter(self.request.GET, queryset=self.get_queryset(**kwargs)) filter.form.helper = FooFilterFormHelper() table = FooTable(filter.qs) RequestConfig(self.request).configure(table) context['filter'] = filter context['table'] = table return context While this is a basic example there's still a lot going on. The get_context_data() method gets called automatically by the TemplateView and populates the template context with the filter and table objects. At first the code creates an instance of your FooFilter (django_filters.FilterSet) and passes it the request's GET data, and the queryset to work on. The filter does what you'd expect and filters the queryset. The filter object also includes … -
KnockoutJS HTML binding
TL;DR: Don't use KnockoutJS ``html`` binding lots of times in your page. I'm in the middle of rewriting a large part of our application in HTML: for a lot of the interactivity stuff, anything more than just a simple behaviour, I'm turning to KnockoutJS. Mostly, it's been awesome. Being able to use two-way binding is the obvious big winner, but dependency tracking is also fantastic. However, I have had some concerns with performance in the past, and this was always on my mind as I moved into quite a complicated part of the system. Our approach is that we are not creating a single page application: different parts of the system are at different URLs, and visiting that page loads up the relevant javascript. This is a deliberate tradeoff, mostly because for the forseeable future, our software will not work without a connection to our server: most of the logic related to shift selection is handled by that. We aren't about to change that. While rewriting the rostering interface, I initially had Django render the HTML, and I added behaviours. This was possible, and quite fast, however as the behaviours became more complex, I was doing things like sending back … -
Django Class-Based Generic Views: tips for beginners (or things I wish I’d known when I was starting out)
Django is renowned for being a powerful web framework with a relatively shallow learning curve, making it easy to get into as a beginner and hard to put down as an expert. However, when class-based generic views arrived on the scene, they were met with a lukewarm reception from the community: some said they were too difficult, while others bemoaned a lack of decent documentation. But if you can power through the steep learning curve, you will see they are also incredibly powerful and produce clean, reusable code with minimal boilerplate in your views.py. So to help you on your journey with CBVs, here are some handy tips I wish I had known when I first started learning all about them. This isn’t a tutorial, but more a set of side notes to refer to as you are learning; information which isn’t necessarily available or obvious in the official docs. Starting out If you are just getting to grips with CBVs, the only view you need to worry about is TemplateView. Don’t try anything else until you can make a ‘hello world’ template and view it on your dev instance. This is covered in the docs. Once you can handle … -
Memories of Malcolm
A year ago today Malcolm Tredinnick, core contributor to Django suddenly passed away. He was a mentor, and more importantly, a good friend. Here are some of my memories of Malcolm. DjangoCon US: September 2010 This is where Audrey and I first met Malcolm. We ended up spending a good amount of the conference with him just hanging out and having a good time. I remember being honored that such a luminary want to spend time with us, yet more importantly discovering a good friend. During the conference, he peered into the nascent code base of djangopackages.com and asked some pointed questions. We justified a few design decisions, and he nodded and we saw him using similar techniques later. He also gave us some great pointers on things we could do, and I believe we implemented all of them. Summer to Autumn of 2010 Malcolm and I worked together on a project in 2010. During this time we had a number of email and chat discussions. Going over them now I'm impressed by his friendship and generosity of knowledge. I know he was terribly busy but yet he always had time for me in 2010. After about emails where I … -
Memories of Malcolm
A year ago today Malcolm Tredinnick, core contributor to Django suddenly passed away. He was a mentor, and more importantly, a good friend. Here are some of my memories of Malcolm. DjangoCon US: September 2010 This is where Audrey and I first met Malcolm. We ended up spending a good amount of the conference with him just hanging out and having a good time. I remember being honored that such a luminary wanted to spend time with us, yet was more delighted in discovering a good friend. During the conference, he peered into the nascent code base of djangopackages.com and asked some pointed questions. We justified a few design decisions, and he agreed, and we saw him using similar techniques later. He gave us some great pointers on things we could do, and I believe we implemented all of them. Summer to Autumn of 2010 Malcolm and I worked together on a project in 2010. During this time we had a number of email and chat discussions. Going over them now I'm impressed by his friendship and generosity of knowledge. I know he was terribly busy but yet he always had time for me in 2010. After about 15 emails … -
Better Models Through Custom Managers and QuerySets
Learn what it takes to get common queries chain-able, and slimmer. This video goes over custom model managers and custom querysets so you can write better code, cleaner, code by harnessing the power of Django and OOP.Watch Now... -
Switching from Wordpress to Pelican
I run a couple of sites that are based on Wordpress and my blog was one of them. There are several things that annoy me when it comes to Wordpress: too many plugins that you need for a good site updates, updates, updates (I merely spend my time in updating everything and keeping compatible) the Wordpress core code the themes HTML and structure that are PHP files it's PHP PHP-FPM consumes to much memory (if configured to serve a Wordpress site with good performance) So for my blog, which really is static but for the comments, I looked around what tools or frameworks are there to replace the mighty Wordpress with a static site. I wanted something simple, something pythonic. By reading the blogs of people who also had switched from Wordpress I found two tools: Hyde, a pythonic fork of Jekyll, and Pelican. The majority of people who switched chose Pelican, so I did, too. It has more forks on Github and also a repository of plugins. In fact both tools are not very different from each other. Pelican just felt better while using. The switch took me some days, I had a couple of problems to solve/things to … -
Switching from Wordpress to Pelican
I run a couple of sites that are based on Wordpress and my blog was one of them. There are several things that annoy me when it comes to Wordpress: too many plugins that you need for a good site updates, updates, updates (I merely spend my time in updating everything and keeping compatible) the Wordpress core code the themes HTML and structure that are PHP files it's PHP PHP-FPM consumes to much memory (if configured to serve a Wordpress site with good performance) So for my blog, which really is static but for the comments, I looked around what tools or frameworks are there to replace the mighty Wordpress with a static site. I wanted something simple, something pythonic. By reading the blogs of people who also had switched from Wordpress I found two tools: Hyde, a pythonic fork of Jekyll, and Pelican. The majority of people who switched chose Pelican, so I did, too. It has more forks on Github and also a repository of plugins. In fact both tools are not very different from each other. Pelican just felt better while using. The switch took me some days, I had a couple of problems to solve/things to … -
Switching from Wordpress to Pelican
I run a couple of sites that are based on Wordpress and my blog was one of them. There are several things that annoy me when it comes to Wordpress: too many plugins that you need for a good site updates, updates, updates (I merely spend my time in updating everything and keeping compatible) the Wordpress core code the themes HTML and structure that are PHP files it's PHP PHP-FPM consumes to much memory (if configured to serve a Wordpress site with good performance) So for my blog, which really is static but for the comments, I looked around what tools or frameworks are there to replace the mighty Wordpress with a static site. I wanted something simple, something pythonic. By reading the blogs of people who also had switched from Wordpress I found two tools: Hyde, a pythonic fork of Jekyll, and Pelican. The majority of people who switched chose Pelican, so I did, too. It has more forks on Github and also a repository of plugins. In fact both tools are not very different from each other. Pelican just felt better while using. The switch took me some days, I had a couple of problems to solve/things to … -
django-content-bbcode - advanced BBCode alike tags parser for Django
Today I've released on Github one of my applications - django-content-bbcode. The parser code is used on my sites and I've decided to refactor it (it's quite old), add some new features (like the tag loader) and release it to the public. There is also pypi package for it. In short django-content-bbcode allows you to replace BBCode alike tags in text (like in articles, news) with whatever you code in Python. I use it to highlight code snippets (with pygments), make nice links to articles by given slug (fetches title, description from database), insert image thumbnails (integrated with frontend image lightbox) and few more. Makes plain text quite dynamic. More detailed description is on Github. -
Record Last Access Not Just Last Login
Knowing when a person last logged in is great, except when it isn't. Sometimes you want to know when a user last actually used your app. Since you can stay continually logged in to Django sites we need an alternative way to know when a person was last on your site. If you are using class based views, and you should, then writing a mixin is a good way to go. LastAccessMixin from django.utils import timezone class LastAccessMixin(object): def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): request.user.accessdata.last_access = timezone.now() request.user.accessdata.save(update_fields=['last_access']) return super(LastAccessMixin, self).dispatch(request, *args, **kwargs) What Does this Code Do? The first place class based views go is to the disatch method. This "dispatches" the request to the proper place. It determines what type of a request it is be it a GET, POST, HEAD etc. From there it goes to the appropriate method. def dispatch(self, request, *args, **kwargs): We are overriding the dispatch method because it is always called, and only once. We also want to use the dispatch method instead of say get because on some urls we might use a post method, then we wouldn't know the page was used. if request.user.is_authenticated(): request.user.accessdata.last_access = timezone.now() request.user.accessdata.save(update_fields=['last_access']) In the … -
Logging in to a Django site with a magic token
I have a simple video website for my kids and each kid has a separate login. This is so they can each have their own videos, but also so that some videos can be private (ie. hidden from the outside world, or other logged in users). I don't need crazy security though--it wouldn't be the end of the world if somehow someone guessed the magic token and saw some private videos, which are basically just home videos uploaded to Youtube. Videos that I really wouldn't want the public to see don't get uploaded to Youtube in the first place. I couldn't find how to do this easily, although one person on stackoverflow suggested "logging in the user in the view by calling login". The tricky part was figuring out that I had to set the User object's backend to 'django.contrib.auth.backends.ModelBackend'. It's a bit of a hack, but it works, and it's simple. models.py: class MagicToken(models.Model): user = models.OneToOneField(User) magictoken = models.CharField(max_length=128, unique=True) def __unicode__(self): return unicode(self.user) views.py: from django.http import HttpResponse, HttpResponseRedirect, Http404 import django.contrib.auth.login class MagicTokenLogin(View): def get(self, request, token): try: magic_token_obj = MagicToken.objects.get(magictoken=token) except MagicToken.DoesNotExist: raise Http404 user = magic_token_obj.user user.backend = 'django.contrib.auth.backends.ModelBackend' django.contrib.auth.login(request, user) … -
Two Scoops of Django 1.6 at DjangoCon Europe
Are you attending DjangoCon Europe? We have good news for you: DjangoCon Europe attendees can get a copy of Two Scoops of Django: Best Practices for Django 1.6 at the conference (pre-order required). How to Order Your Copy To order a copy for pickup at DjangoCon Europe, get it here: http://www.weezevent.com/djangocon-europe Note that you must pre-order it via that page, and that sales will close on May 1, 2014, 2 weeks before DjangoCon Europe. This is to give us an exact count of how many books to ship to DjangoCon Europe. Unfortunately, we can't sign or individualize these copies as they'll be sent directly from the drop shipper. The 1.6 edition is a thick book that is packed with tons of updated material. Feedback from those who already owned the 1.5 edition has been overwhelmingly positive. We honestly tried our hardest to provide a useful resource, and we hope it is greatly helpful to readers. Help a Speaker Attend Proceeds from sales of the book will be used to subsidize the expenses of a speaker on a low budget. As anyone who’s been a speaker at a conference knows, putting together a great talk is not easy. It can be … -
Two Scoops of Django 1.6 at DjangoCon Europe
Are you attending DjangoCon Europe? We have good news for you: DjangoCon Europe attendees can get a copy of Two Scoops of Django: Best Practices for Django 1.6 at the conference (pre-order required). How to Order Your Copy To order a copy for pickup at DjangoCon Europe, get it here: http://www.weezevent.com/djangocon-europe Note that you must pre-order it via that page, and that sales will close on May 1, 2014, 2 weeks before DjangoCon Europe. This is to give us an exact count of how many books to ship to DjangoCon Europe. Unfortunately, we can't sign or individualize these copies as they'll be sent directly from the drop shipper. The 1.6 edition is a thick book that is packed with tons of updated material. Feedback from those who already owned the 1.5 edition has been overwhelmingly positive. We honestly tried our hardest to provide a useful resource, and we hope it is greatly helpful to readers. Help a Speaker Attend Proceeds from sales of the book will be used to subsidize the expenses of a speaker on a low budget. As anyone who’s been a speaker at a conference knows, putting together a great talk is not easy. It can be … -
Two Scoops of Django 1.6 at DjangoCon Europe
Are you attending DjangoCon Europe? We have good news for you: DjangoCon Europe attendees can get a copy of Two Scoops of Django: Best Practices for Django 1.6 at the conference (pre-order required). How to Order Your Copy To order a copy for pickup at DjangoCon Europe, get it here: http://www.weezevent.com/djangocon-europe Note that you must pre-order it via that page, and that sales will close on May 1, 2014, 2 weeks before DjangoCon Europe. This is to give us an exact count of how many books to ship to DjangoCon Europe. Unfortunately, we can't sign or individualize these copies as they'll be sent directly from the drop shipper. The 1.6 edition is a thick book that is packed with tons of updated material. Feedback from those who already owned the 1.5 edition has been overwhelmingly positive. We honestly tried our hardest to provide a useful resource, and we hope it is greatly helpful to readers. Help a Speaker Attend Proceeds from sales of the book will be used to subsidize the expenses of a speaker on a low budget. As anyone who’s been a speaker at a conference knows, putting together a great talk is not easy. It can be …