Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Handle X-Forwarded-Port Header in Django
Handle X-Forwarded-Port Header in Django When running on a non-standard port, and behind a load balancer/proxy, it has become "standard"[1] to forward along a header called X-Forwarded-Port. This header is very similar to X-Forwarded-Host, X-Forwarded-Proto, and X-Forwarded-For in the sense that it's forwarding relevent information about the originating request and telling your backend to ignore the values it's aware of. In this case, X-Forwarded-Port is not supported by Django natively, and the easiest way to handle it is through a simple middleware: class XForwardedPort(object): def process_request(self, request): try: request.META['SERVER_PORT'] = request.META['HTTP_X_FORWARDED_PORT'] except KeyError: pass return None This will allow urls to be properly reversed with the correct port as you'd expect. References https://gist.github.com/4439597 Footnotes [1] I use quotes because nobody has a fucking clue what's really going on with this shit. There isn't a standard, just an idea that a few people started implementing. -
Handle X-Forwarded-Port Header in Django
Handle X-Forwarded-Port Header in Django When running on a non-standard port, and behind a load balancer/proxy, it has become "standard"[1] to forward along a header called X-Forwarded-Port. This header is very similar to X-Forwarded-Host, X-Forwarded-Proto, and X-Forwarded-For in the sense that it's forwarding relevent information about the originating request and telling your backend to ignore the values it's aware of. In this case, X-Forwarded-Port is not supported by Django natively, and the easiest way to handle it is through a simple middleware: class XForwardedPort(object): def process_request(self, request): try: request.META['SERVER_PORT'] = request.META['HTTP_X_FORWARDED_PORT'] except KeyError: pass return None This will allow urls to be properly reversed with the correct port as you'd expect. References https://gist.github.com/4439597 Footnotes [1] I use quotes because nobody has a fucking clue what's really going on with this shit. There isn't a standard, just an idea that a few people started implementing. -
New Year's Resolutions for 2013
I'm one of those people who not only likes to make New Year's Resolutions, I like to blog about them. Resolution Go to at least one technical conference in North America, South America, Europe, Asia, Africa, and Australia. Visit at least one new nation. It's hard to come up with preferences since the whole world is so exciting. Go back to at least one of the nations I've visited before. Take a road trip across the USA. See the Grand Canyon. Keep to a 32 waist for the whole year. Visit friends and family back east. Blog once a week. That is at least 52 blog entries! Visit the beach for more than one day. Take a fun class with Audrey. Teach some Python or Django. Build something real using Twisted as a critical component. Take a high level Python class from the likes of Raymond Hettinger or David Beazley. Commit to core Python Visit my Son. Upload all my outstanding pictures to Flickr! Pull off an Aú sem Mão (no-handed cartwheel). Attend my first Capoeira Batizado (formal gathering). Work out at least three times a week. Learn how to surf or snowboard. Have a beer with Thomas, Andy, Andy, … -
New Year's Resolutions for 2013
I'm one of those people who not only likes to make New Year's Resolutions, I like to blog about them. Resolutions Go to at least one technical conference in South America, Asia, Africa, and Australia. Visit at least one new nation. It's hard to come up with preferences since the whole world is so exciting. Take a road trip across the USA. See the Grand Canyon. Keep to a 32 waist for the whole year. Blog once a week. That is at least 52 blog entries! Take a fun class with Audrey. Build something real using Twisted as a critical component. Take a high level Python class from the likes of Raymond Hettinger or David Beazley. Commit to core Python Upload all my outstanding pictures to Flickr! Pull off an Aú sem Mão (no-handed cartwheel). Attend my first Capoeira Batizado (formal gathering). Work out at least three times a week. Learn how to surf or snowboard. Have a beer with Thomas, Andy, Andy, Tony, Garrick, Bernd, and the rest of Ye Aulde Gange. See my old DC area friends such as Eric, Chris, Steve, Beth, Sarah, Daye, Renee, Kenneth, Leslie, Whitney, Dave, and many others. Accomplished Teach some Python or … -
Rackspace Temporary URLs with django-cumulus
We love Rackspace at Imaginary Landscape. Recently, we needed to store a number of large files securely, and for logistical reasons, we chose to store them via Rackspace’s Cloud Files. Rackspace provides the ability to create temporary URLs for files stored via their service. This allows temporary access to ... -
New Year's Resolutions for 2013
I'm one of those people who not only likes to make New Year's Resolutions, I like to blog about them. Go to at least one technical conference in North America, South America, Europe, Asia, Africa, and Australia. Visit at least one new nation. It's hard to come up with preferences since the whole world is so exciting. Go back to at least one of the nations I've visited before. Take a road trip across the USA. See the Grand Canyon. Keep to a 32 waist for the whole year. Visit friends and family back east. Blog once a week. That is at least 52 blog entries! Visit the beach for more than one day. Take a fun class with Audrey. Teach some Python or Django. Build something real using Twisted as a critical component. Take a high level Python class from the likes of Raymond Hettiger or David Beazly. Commit to core Python Visit my Son. Upload all my outstanding pictures to Flickr! Pull off an Aú sem Mão (no-handed cartwheel). Attend my first Capoeira Batizado (formal gathering). Work out at least three times a week. Learn how to surf or snowboard. Have a beer with Thomas, Andy, Andy, Tony, … -
Mapas com GeoDjango e PostGIS
GeoDjango Tive muitos desafios em 2012, mas quero destacar o aprendizado de novas tecnologias e novos conceitos de desenvolvimento. Neste post quero destacar o GeoDjango, que foi motivo de estudos e desenvolvimento nos últimos 6 meses. Eu precisava manipular informações geográficas completas, que inclui o básico da latitude e longitude, mas também trabalhar com shapes, cálculos de área, aproximações, agrupamento de áreas, distâncias, etc. Precisava mesmo desenvolver um SIG/GIS completo e muito específico para uma demanda de projeto. O primeiro passo foi estudar sobre GIS, entender alguns conceitos básicos sobre mapas, projeções e demais conceitos. Encontrei muito material pela internet, mas também comprei alguns ebooks e livros sobre o assunto. Engana-se quem pensa que GIS está relacionado apenas a latitude e longitude. O conceito é bem amplo e complexo, cheio de variáveis e padrões diferentes de mapas, projeções e demais utilitários que te obrigam a conhecer bem o assunto para saber como processar e organizar as informações adequadamente. Depois de aprender bastante sobre GIS, o próximo passo foi encontrar tecnologias livres que atendam os pré-requisitos do projeto. Essa parte eu achei que seria difícil, mas acabou sendo uma das mais simples, pois as tecnologias que eu já trabalho no dia … -
New Year's Python Meme 2012
Tarek Ziade has a habit of ending the year with a Python-themed meme. I've matched his meme the times he previousstarted it, and as you can tell from the title of this blog post I'm matching him yet again. 1. What’s the coolest Python application, framework or library you have discovered in 2012? This question took some thought. It was a toss-up between these three choices: Django Class Based Views (CBVs) allow developers do amazing things with Django, but needed some polish (improved documentation, missing functionality) to be able to shine. ReportLab for generating PDF allowed me to create some impressive results, but the API needed updating. The other Python PDF libraries might be better, but getting images to work trivially in them If I didn't completely agree with Armin Ronacher on the subject, I might have gone with a combination of PyMongo, MongoEngine, and MongoKit. Just like Armin, I've learned through working with schemaless databases to know that schemas are awesome. The winner? Django Class Based Views In 2012 what I managed to accomplish with Django CBVs was incredible. From early self-instructional work I did for django-mongonaut, to client efforts and personal projects where I honed my craft, plus … -
New Year's Python Meme 2012
Tarek Ziade has a habit of ending the year with a Python-themed meme. I've matched his meme the times he previousstarted it, and as you can tell from the title of this blog post I'm matching him yet again. 1. What’s the coolest Python application, framework or library you have discovered in 2012? This question took some thought. It was a toss-up between these three choices: Django Class Based Views (CBVs) allow developers do amazing things with Django, but needed some polish (improved documentation, missing functionality) to be able to shine. ReportLab for generating PDF allowed me to create some impressive results, but the API needed updating. The other Python PDF libraries might be better, but getting images to work trivially in them If I didn't completely agree with Armin Ronacher on the subject, I might have gone with a combination of PyMongo, MongoEngine, and MongoKit. Just like Armin, I've learned through working with schemaless databases to know that schemas are awesome. The winner? Django Class Based Views In 2012 what I managed to accomplish with Django CBVs was incredible. From early self-instructional work I did for django-mongonaut, to client efforts and personal projects where I honed my craft, plus … -
New Year's Python Meme 2012
Tarek Ziade has a habit of ending the year with a Python-themed meme. I've matched his meme the times he previousstarted it, and as you can tell from the title of this blog post I'm matching him yet again. 1. What’s the coolest Python application, framework or library you have discovered in 2012? This question took some thought. It was a toss-up between these three choices: Django Class Based Views (CBVs) allow developers do amazing things with Django, but needed some polish (improved documentation, missing functionality) to be able to shine. ReportLab for generating PDF allowed me to create some impressive results, but the API needed updating. The other Python PDF libraries might be better, but getting images to work trivially in them If I didn't completely agree with Armin Ronacher on the subject, I might have gone with a combination of PyMongo, MongoEngine, and MongoKit. Just like Armin, I've learned through working with schemaless databases to know that schemas are awesome. The winner? Django Class Based Views In 2012 what I managed to accomplish with Django CBVs was incredible. From early self-instructional work I did for django-mongonaut, to client efforts and personal projects where I honed my craft, plus … -
Saved by a nose-blockage
Was slightly pleased to see today that nose-blockage saved our test suite. A change in the django-browserid library meant that on each call to login in our test suite, it was going to make a HTTP request to verifier.login.persona.org. Fortunately nose-blockage stops that request and 1,012 tests failed. If we didn't have that blockage in place, out test suite would have made over 1,012 HTTP requests to the persona.org server on each test run. That would have made our test suite slower and dependent on an external service. Not a big issue to fix, but this is a really good example of why nose-blockage can be useful to save you from libraries that change. Example failure: -------------------- >> begin captured logging << -------------------- django_browserid.base: INFO: Verification URL: https://verifier.login.persona.org/verify requests.packages.urllib3.connectionpool: INFO: Starting new HTTPS connection (1): verifier.login.persona.org blockage.plugins: WARNING: Denied HTTP connection to: verifier.login.persona.org --------------------- >> end captured logging << --------------------- -
Lettuce - scenario based tests for Django and other frameworks
lettuce is a test system driven by scenarios used in behavior driven development (BDD). The scenarios are described expressively in English and can be read and understood even for non programmers. Test system like lettuce parsers the scenarios and executes required tests for each step. -
Django import export
django-import-export is a Django application and library for importing and exporting data with included admin integration. Features: support multiple formats (Excel, CSV, JSON, ... and everything else that tablib support) admin integration for importing preview import changes admin integration for exporting export data respecting admin filters Define import-export resource example class BookResource(resources.ModelResource): class Meta: model = Book widgets = { 'published': {'format': '%d.%m.%Y'}, } Integrate with admin Source code and example app are available on GitHub: https://github.com/bmihelac/django-import-export Documentation: https://django-import-export.readthedocs.org/en/latest/ django-import-export is currently beta software. -
Full screen WebView Android app
I decided to make an Android app for my Bible memory verse site (created using Django). The main motivation for the app is to get rid of the unnecessary and annoying address bars and status bars when using the site on an Android phone. The site is already designed to adapt to mobiles, so I'm not creating a native app — I just want a better way to access the web app from an Android phone. I tried appsgeyser, but discovered they put adverts on your site, which I definitely don't want — this is an entirely free app, for a free (and ad-free) site. My requirements are: Full screen without any controls ever popping up, because you don't need them. Progress bar for page loading. Javascript works. Links work as expected. Back button works like builtin browser, until you get back to the home page, where it will cause the app to exit. There are lots of pages and wizards with solutions for bits of these, but putting them together turned out to be harder — for example, it seems that the normal way of showing a progress bar for the whole window doesn't work if you've gone full … -
Docstring inheritance in Django REST framework
Django REST framework has a nice html-based interface that, for every one of your REST views, renders the docstring as an explanation at the top of the page. Those views, they're class based views, at least the ones I use. I'm making views that ought to be base views for other Django app's API. We have a bunch of django apps for various data sources that can present their data in more or less the same way. So... I've put a decent docstring, explaining the API, in my base views. Only... they didn't show up in the interface for the subclasses. Apparently docstrings aren't inherited by subclasses! So I asked a question on stack overflow and promptly got an answer. What I ended up doing was modifying .get_description(), the method Django REST framework uses to grab and render the docstring: import inspect # Fancy standardlibrary Python internal inspection tool. import docutils from django.contrib.admindocs.utils import trim_docstring from django.utils.safestring import mark_safe .... class MyBaseAPIView(...): def get_description(self, html=False): description = self.__doc__ # Our docstring. if description is None: # Try and grab it from our parents. try: description = next( cls.__doc__ for cls in inspect.getmro(type(self)) if cls.__doc__ is not None) except StopIteration: pass … -
Enable APIs for your django apps in djangoish way
A small django helper to let you create and manage app-centric API url mappings. django-api-enabler lets you: Enable/disable APIs associated with any specific app. Enable/disable entire project APIs. Use prefix like '/api/' to identify and distinguish between API and non-API URLs. The URL to view maps are maintained within app code. Customizable app specific prefixes. urlconf compliant. Simple, yet powerful and useful! For details: https://github.com/subhranath/django-api-enabler -
Django Extensions 1.0.2
Minor version update Django-Extensions 1.0.2 is out. This release fixes the following problems: tests: fix keyzcar test failure: ImproperlyConfigured: You must set the ENCRYPTED_FIELD_KEYS_DIR setting to your Keyczar keys directory. fields: fix docstring for UUID docs: Make README links clickable and organized. show_urls: Revive --unsorted option Added LoggingBaseCommand that logs run time errors to Python logger django.commands -
Shortcomings in the Django ORM and a look at Peewee, a lightweight alternative
In this post I'd like to talk about some of the shortcomings of the Django ORM, the ways peewee approaches things differently, and how this resulted in peewee having an API that is both more consistent and more expressive. Alex Gaynor, one of the more outspoken core developers on the Django project, gave a great talk at ChiPY titled "Why I Hate the Django ORM" (slides). I think he did a great job identifying what I agree are the two biggest issues with Django's ORM: inconsistent API lack of composability The Django ORM has an inconsistent API Django wants to expose consistent APIs The framework should be consistent at all levels. Consistency applies to everything from low-level (the Python coding style used) to high-level (the “experience” of using Django). On the whole I think Django does a good job with this - the big exception being the ORM. Alex gives 4 examples, which should be familiar to Django developers and which are indicative of the underlying issues: filter(field_name=value) Q(field_name=value) F('field_name') Aggregate('field_name') filter() is the most basic method and is the most common. It is used to express a SQL Where clause and takes as parameters a list of keyword arguments … -
Shortcomings in the Django ORM and a look at Peewee, a lightweight alternative
In this post I'd like to talk about some of the shortcomings of the Django ORM, the ways peewee approaches things differently, and how this resulted in peewee having an API that is both more consistent and more expressive. Alex Gaynor, one of the more outspoken core developers on the Django project, gave a great talk at ChiPY titled "Why I Hate the Django ORM" (slides). I think he did a great job identifying what I agree are the two biggest issues with Django's ORM: inconsistent API lack of composability The Django ORM has an inconsistent API Django wants to expose consistent APIs The framework should be consistent at all levels. Consistency applies to everything from low-level (the Python coding style used) to high-level (the “experience” of using Django). On the whole I think Django does a good job with this - the big exception being the ORM. Alex gives 4 examples, which should be familiar to Django developers and which are indicative of the underlying issues: filter(field_name=value) Q(field_name=value) F('field_name') Aggregate('field_name') filter() is the most basic method and is the most common. It is used to express a SQL Where clause and takes as parameters a list of keyword arguments … -
Shortcomings in the Django ORM and a look at Peewee, a lightweight alternative
In this post I'd like to talk about some of the shortcomings of the Django ORM, the ways peewee approaches things differently, and how this resulted in peewee having an API that is both more consistent and more expressive. Alex Gaynor, one of the more outspoken core developers on the Django project, gave a great talk at ChiPY titled "Why I Hate the Django ORM" (slides). I think he did a great job identifying what I agree are the two biggest issues with Django's ORM: inconsistent API lack of composability The Django ORM has an inconsistent API Django wants to expose consistent APIs The framework should be consistent at all levels. Consistency applies to everything from low-level (the Python coding style used) to high-level (the “experience” of using Django). On the whole I think Django does a good job with this - the big exception being the ORM. Alex gives 4 examples, which should be familiar to Django developers and which are indicative of the underlying issues: filter(field_name=value) Q(field_name=value) F('field_name') Aggregate('field_name') filter() is the most basic method and is the most common. It is used to express a SQL Where clause and takes as parameters a list of keyword arguments … -
Shortcomings in the Django ORM and a look at Peewee, a lightweight alternative
In this post I'd like to talk about some of the shortcomings of the Django ORM, the ways peewee approaches things differently, and how this resulted in peewee having an API that is both more consistent and more expressive. Alex Gaynor, one of the more outspoken core developers on the Django project, gave a great talk at ChiPY titled "Why I Hate the Django ORM" (slides). I think he did a great job identifying what I agree are the two biggest issues with Django's ORM: inconsistent API lack of composability The Django ORM has an inconsistent API Django wants to expose consistent APIs The framework should be consistent at all levels. Consistency applies to everything from low-level (the Python coding style used) to high-level (the “experience” of using Django). On the whole I think Django does a good job with this - the big exception being the ORM. Alex gives 4 examples, which should be familiar to Django developers and which are indicative of the underlying issues: filter(field_name=value) Q(field_name=value) F('field_name') Aggregate('field_name') filter() is the most basic method and is the most common. It is used to express a SQL Where clause and takes as parameters a list of keyword arguments … -
Shortcomings in the Django ORM and a look at Peewee, a lightweight alternative
In this post I'd like to talk about some of the shortcomings of the Django ORM, the ways peewee approaches things differently, and how this resulted in peewee having an API that is both more consistent and more expressive. Alex Gaynor, one of the more outspoken core developers on the Django project, gave a great talk at ChiPY titled "Why I Hate the Django ORM" (slides). I think he did a great job identifying what I agree are the two biggest issues with Django's ORM: inconsistent API lack of composability The Django ORM has an inconsistent API Django wants to expose consistent APIs The framework should be consistent at all levels. Consistency applies to everything from low-level (the Python coding style used) to high-level (the “experience” of using Django). On the whole I think Django does a good job with this - the big exception being the ORM. Alex gives 4 examples, which should be familiar to Django developers and which are indicative of the underlying issues: filter(field_name=value) Q(field_name=value) F('field_name') Aggregate('field_name') filter() is the most basic method and is the most common. It is used to express a SQL Where clause and takes as parameters a list of keyword arguments … -
Django 1.5 Custom User GeoManager
AttributeError: ‘GeoManager’ object has no attribute 'get_by_natural_key’ Using geo fields on a Django model requires the use of GeoManager. Custom User models require an object manager that implements BaseUserManager.get_by_natural_key. If you’re trying to add geo fields to your custom User model you’ll need create a custom manager that mixes a user manager and GeoManager. Lucky us, this is a piece of cake! http://gist.github.com/4291351 -
Caktus Celebrates 5 Year Anniversary
Caktus celebrated the end of our fifth year in business recently. We threw ourselves a party and invited our local friends who helped us grow from our infancy through our awkward phases into a successful and sustainable small business. We started out as four college friends moving across the country from the corn fields of Indiana to Carrboro, North Carolina to work together building awesome interactive web applications. We were ready to put what we had learned in school to work and continue to learn and develop new technical and business skills. Since then we've grown, steadily bringing on developers, an office manager, project managers, and a designer totaling 15 people in all. We were fostered locally by Carrboro Creative Coworking as a technical and creative hub for the Carrboro area and by the incredible number of local technology companies in the Raleigh-Durham-Chapel Hill Research Triangle area. The party was to celebrate that local community, but we have made amazing connections all over the world. We wish everyone could have been there but had a wonderful time with those who attended while talking, reminiscing, and speculating about Caktus' future. Through all of this growth and change we have maintained the … -
RestORM - The client side of REST
RestORM structures the way you access a RESTful API and allows you to easily access related resources. It tries to be as generic as possible so it's not tailored to any specific API or server-side API library. With RestORM you can mock an entire API and replace the real client with a mock version in unit tests. RestORM is very extensible but offers many functionalities out of the box to get you up and running quickly.