Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Rendering your STL files with matplotlib using numpy-stl
It’s been a while since the first version of numpy-stl and a lot has changed since. Most importantly, usage has become even easier. So here’s a demo on how to use matplotlib to render your stl files: from stl import mesh from mpl_toolkits import mplot3d from matplotlib import pyplot # Create a new plot figure = pyplot.figure() axes = mplot3d.Axes3D(figure) # Load the STL files and add the vectors to the plot your_mesh = mesh.Mesh.from_file('tests/stl_binary/HalfDonut.stl') axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors)) # Auto scale to the mesh size scale = your_mesh.points.flatten(-1) axes.auto_scale_xyz(scale, scale, scale) # Show the plot to the screen pyplot.show() You can make the render prettier yourself of course, but it is certainly useful for testing. Link to this post! -
Einladung zur Django-UserGroup Hamburg am 08. Juli
Das nächste Treffen der Django-UserGroup Hamburg findet am Mittwoch, den 08.07.2015 um 19:30 statt. Achtung: Neue Location! Dieses Mal treffen wir uns in den Räumen der Smaato Inc., Valentinskamp 70, Emporio 19. Stock in 20355 Hamburg. Auf diesem Treffen gibt es einen Vortrag über TDD für APIs von Michael Kuehne. Bitte seid um ca. 19:20 unten im Foyer, wir fahren dann gemeinsam in den 19. Stock. Wer später kommt, sagt bitte am Empfang bescheid, dass er zur Smaato Inc möchte und wird dann hoch gelassen. Eingeladen ist wie immer jeder der Interesse hat sich mit anderen Djangonauten auszutauschen. Eine Anmeldung ist nicht erforderlich, hilft aber bei der Planung. Weitere Informationen über die UserGroup gibt es auf unserer Webseite www.dughh.de. Die Organisation der Django-UserGroup Hamburg findet ab jetzt über Meetup statt. Um automatisch über zukünftige Treffen informiert zu werden, werdet bitte Mitglied in unserer Meetup-Gruppe: http://www.meetup.com/django-hh -
Observations on the nature of time. And javascript.
In the course of working on one of our latest projects, I picked up an innocuous looking ticket that said: “Date pickers reset to empty on form submission”. “Easy”, I thought. It’s just the values being lost somewhere in form validation.And then I saw the ‘in Firefox and IE’ description. Shouldn’t be too hard, it’ll be a formatting issue or something, maybe even a placeholder, right? Yeah, no. Initial Investigations Everything was fine in Chrome, but not in Firefox. I confirmed the fault also existed in IE (and then promptly ignored IE for now). The responsible element looked like this: <input class="form-control datepicker" data-date-format="{{ js_datepicker_format }}" type="date" name="departure_date" id="departure_date" value="{{ form.departure_date.value|default:'' }}"> This looks pretty innocent. It’s a date input, how wrong can that be? Sit comfortably, there’s a rabbit hole coming up. On Date Inputs Date type inputs are a relatively new thing, they’re in the HTML5 Spec. Support for it is pretty mixed. This jumps out as being the cause of it working in Chrome, but nothing else. Onwards investigations (and flapping at colleagues) led to the fact that we use bootstrap-datepicker to provide a JS/CSS based implementation for the browsers that have no native support. We have … -
Upgrading Django Projects - Introduction
One questions I am asked quite often is how to upgrade larger projects to a newer Django release. While upgrading to a newer minor release is usually really easy and does not require much work it can become a bit harder upgrading to a new major release. My oldest project points back to 0.9x, so it has seen some upgrades, and there are certain patters that proved to work pretty well. Upgrading a Django project is not harder or easier than upgrading any other project of the same size which is using a big third party framework as base and smaller libraries for certain parts of the system. I will try to start with general and simple principles on upgrading projects and move to more Python and Django specific topics later on. Before upgrading you should ask yourself if you have to. Let us assume your application is running fine and you are on a release that still gets bugfix and security updates. You could upgrade to get new features that eventually help you down the road. Or you could implement a new feature that separates your application from all competitors. The answer in that case is pretty obvious, isn’t … -
Upgrading Django Projects - Introduction
Upgrading Django Projects - Introduction One questions I am asked quite often is how to upgrade larger projects to a newer Django release. While upgrading to a newer minor release is usually really easy and does not require much work it can become a bit harder upgrading to a new major release. My oldest project points back to 0.9x, so it has seen some upgrades, and there are certain patters that proved to work pretty well. Upgrading a Django project is not harder or easier than upgrading any other project of the same size which is using a big third party framework as base and smaller libraries for certain parts of the system. I will try to start with general and simple principles on upgrading projects and move to more Python and Django specific topics later on. Before upgrading you should ask yourself if you have to. Let us assume your application is running fine and you are on a release that still gets bugfix and security updates. You could upgrade to get new features that eventually help you down the road. Or you could implement a new feature that separates your application from all competitors. The answer in that … -
Wrapping Up CycleMento
in this video we wrap up the Building a Product series by doing an overview of topics we discussed in the previous 11 videos.Watch Now... -
Announcing the Evennia example-game project "Ainneve"
The Evennia example-game project is underway! I was quite impressed with the response I got on the mailing list to my call for developing an Evennia example game (see my Need your Help blog post).The nature of the responses varied, many were from interested people with little to no experience in Evennia or Python whereas others had the experience but not the time to lead it. It was however clear that the interest to work on an "official" Evennia game is quite big. I'm happy to announce, however, that after only a week we now have a solid lead developer/manager, George Oliver. Helping him on the technical/architecture side is Whitenoise (who, despite a barren github profile, is a professional developer). George put together a game proposal based on the OpenAdventure rpg, an open-source (CC-SA) ruleset that is also found on github. The example game is to be named "Ainneve" and its development is found in a in a separate repository under the github Evennia organisation.All the relevant links and future discussion can be found on the mailing list.George and whitenoise have already made it clear that they aim to not only make Ainneve a good example Evennia game for others to … -
The Django template language
Basics: A template is a text document, or a normal Python string, that is marked-up using the Django template language. Template system in Python can be used in the following way: First, compile the raw template code into a Template object. Then, call the render() method of the Template object with a given context. Rendering a context: Once you have a compiled Template object, you can render a context or multiple contexts with it. We have a Context class at django.template.Context, and its constructor takes two (optional) arguments: 1. A dictionary mapping variable names to variable values. 2. The name of the current application. Example: from django.template import Template, Context # Creating a Template object by instantiating it and its constructor takes one argument i.e., raw template code. template = Template("My name is {{my_name}}") context = Context({"my_name":"XXX"}) # Calling the Template object's render() method with the context to fill the template. template.render(context) Templates: A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.). A template contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template. The following example … -
Inclusion Tags
Django’s template system comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag. Custom template tags and filters must be inside a Django app. If they relate to an existing app it makes sense to create them there; otherwise, you should create a new app to hold them. The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget to include __init__.py file to ensure the directory is treated as a Python package. Your custom tags and filters will be there in a module inside the templatetags directory. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app. For example, if your custom tags/filters are in a file called poll_extras.py, your app layout might look like this: polls/ |- __init__.py … -
The Django template language
Basics: A template is a text document, or a normal Python string, that is marked-up using the Django template language. Template system in Python can be used in the following way: First, compile the raw template code into a Template object. Then, call the render() method of the Template object with a given context. Rendering a context: Once you have a compiled Template object, you can render a context or multiple contexts with it. We have a Context class at django.template.Context, and its constructor takes two (optional) arguments: 1. A dictionary mapping variable names to variable values. 2. The name of the current application. Example: from django.template import Template, Context # Creating a Template object by instantiating it and its constructor takes one argument i.e., raw template code. template = Template("My name is {{my_name}}") context = Context({"my_name":"XXX"}) # Calling the Template object's render() method with the context to fill the template. template.render(context) Templates: A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.). A template contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template. The following example … -
Django Inclusion Tags
Django’s template system comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag. Custom template tags and filters must be inside a Django app. If they relate to an existing app it makes sense to create them there; otherwise, you should create a new app to hold them. The app should contain a template tags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget to include __init__.py file to ensure the directory is treated as a Python package. Your custom tags and filters will be there in a module inside the template tags directory. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app. For example, if your custom tags/filters are in a file called poll_extras.py, your app layout might look like this: polls/ |- … -
Reading MT940 files using Python
Some time ago I wrote a library to read MT940 files with Python. While there are multiple libraries available for this target, none of the others really work properly and/or support all variants of the format. The MT940 library I wrote is slightly different, it’s designed to be able to parse any MT940 file, regardless whether it’s correct or complete. The initial version of the library was very strict and only supported files that perfectly followed the standards, a few months after the release it became obvious that most banks either used different standards when implementing the standard or interpreted the standard different. Regardless, the library gave little to no results or even crashed on some MT940 files. Upon reflection I rewrote nearly all of the code to have a script that is flexible enough to support any format (even supporting custom processors for specific format) and wrote test code that tested every MT940 file I could find on the web. The result… a library that parsers pretty much everything out there while still maintaining a reasonable amount of results. Usage? As simple as you might imagine. After installing (pip install mt-940, note the dash) usage can be as simple … -
Django Birthday Party
Django Birthday Party -
Beyond Request-Response
Examining one of Django's key abstractions and how it could be updated for a more modern age. While I love Django dearly, and I think the rate of progress we keep on the project draws a fine balance between progress and backwards-compatibility, sometimes I look ahead to the evolving Web and wonder what we can do to adapt to some more major changes. We're already well-placed to be the business-logic and data backend to more JavaScript-heavy web apps or native apps; things like Django REST Framework play especially well into that role, and for more traditional sites I still think Django's view and URL abstractions do a decent job - though the URL routing could perhaps do with a refresh sometime soon. The gaping hole though, to me, was always WebSocket support. It used to be long-poll/COMET support, but we seem to have mostly got past that period now - but even so, the problem remains the same. As a framework, Django is tied to a strict request-response cycle - a request comes in, a worker is tied up handling it until a response is sent, and you only have a small number of workers. Trying to service long-polling would … -
Buildout and Django: djangorecipe updated for gunicorn support
Most people in the Django world probably use pip to install everything. I (and the company were I work, Nelen & Schuurmans) use buildout instead. If there are any other buildout users left outside of zope/plone, I'd love to hear it :-) First the news about the new update, after that I'll add a quick note about what's good about buildout, ok? Djangorecipe 2.1.1 is out. The two main improvements: Lots of old unused functionality has been removed. Project generation, for instance. Django's own startproject is good enough right now. And you can also look at cookiecutter. Options like projectegg and wsgilog are gone as they're not needed anymore. The latest gunicorn releases didn't come with django support anymore. You used to have a bin/django run_gunicorn (or python manage.py run_gunicorn) management command, but now you just have to run bin/gunicorn yourproject.wsgi. And pass along an environment variable that points at your django settings. With the latest djangorecipe, you can add a scripts-with-settings = gunicorn option and it'll create a bin/gunicorn-with-settings script for you that sets the environment variable automatically. Handy! Advantage of buildout. To me, the advantage of buildout is threefold: Buildout is more fool-proof. With pip/virtualenv you should remember … -
Need your help
This for all you developers out there who want to make a game with Evennia but are not sure about what game to make or where to start off.We need an example gameOne of the main critiques Evennia get from newbies is the lack of an (optional) full game implementation to use as an example and base to build from. So, Evennia needs a full, BSD-licensed example game. I'm talking "diku-like", something you could in principle hook up and allow players into within minutes of installing Evennia. The Tutorial world we already have is a start but it is more of a solo quest, it's not designed to be a full multiplayer game. Whereas Evennia supports other forms of MU* too, the idea is that the systems from a more "code-heavy" MUD could easily be extracted and adopted to a more freeform-style game whereas the reverse is not generally true. The exact structure of such a game would be up to the person or team taking this on, but it should be making use of Evennia's api and come distributed as a custom game folder (the folder you get with evennia --init). We will set this up as a separate … -
Stanford Social Innovation Review Highlights Caktus' Work in Libya
The Stanford Social Innovation Review recently featured Caktus in “Text the Vote” in Suzie Boss’ “What’s Next: New Approaches to Social Change” column. It describes how our team of developers built the world’s first SMS voter registration system in Libya using RapidSMS. Article excerpt In a classic leapfrogging initiative, Libya has enabled its citizens to complete voter registration via digital messaging technology. In late 2013, soon after Vinod Kurup joined Caktus Group, an open source software firm based in Durham, N.C., he became the lead developer for a new app. The client was the government of Libya, and the purpose of the app would be to support voter registration for the 2014 national elections in that country. Bomb threats and protests in Libya made in-person registration risky. “I realized right away that this wasn’t your standard tech project,” says Kurup. As a result of that project, Libya became the first country in the world where citizens can register to vote via SMS text messaging. By the end of 2014, 1.5 million people—nearly half of all eligible voters in Libya— had taken advantage of the Caktus-designed app during two national elections. “This never would have happened in a country like the … -
Django Model managers and properties
Model: A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. And an instance of that class represents a particular record in the database table. 1. Each model(database table) is a Python class that subclasses django.db.models.Model. 2. Each attribute of the model represents a database field(column). Example: from django.db import models class User(models.Model): name = models.CharField(max_length=100) email = models.EmailField() def __str__(self): return self.name To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. Assume models are in a file project1/app1/models.py Example: from app1.models import User user = User(name="xxx", email="xxx@xxx.xxx") user.save() To create and save an object in a single step, use the create() method. Example: from app1.models import User user = User.objects.create(name="xxx", email="xxx@xxx.xxx") Managers: A Manager is the interface through which database query operations are provided to Django models.By default, Django adds a Manager with the name "objects" to every Django model class. Example: from django.db.models import Model, Manager class User(Model): … -
Django Model managers and properties
Model: A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. And an instance of that class represents a particular record in the database table. 1. Each model(database table) is a Python class that subclasses django.db.models.Model. 2. Each attribute of the model represents a database field(column). Example: from django.db import models class User(models.Model): name = models.CharField(max_length=100) email = models.EmailField() def __str__(self): return self.name To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. Assume models are in a file project1/app1/models.py Example: from app1.models import User user = User(name="xxx", email="xxx@xxx.xxx") user.save() To create and save an object in a single step, use the create() method. Example: from app1.models import User user = User.objects.create(name="xxx", email="xxx@xxx.xxx") Managers: A Manager is the interface through which database query operations are provided to Django models. By default, Django adds a Manager with the name "objects" to every Django model class. Example: from django.db.models import Model, Manager class User(Model): … -
Robots Robots Ra Ra Ra!!! (PyCon 2015 Must-See Talk: 6/6)
Part six of six in our PyCon 2015 Must-See Series, a weekly highlight of talks our staff enjoyed at PyCon. I've had an interest in robotics since high school, but always thought it would be expensive and time consuming to actually do. Over the past few years, though, I've observed the rise of open hardware such as the Arduino and the Raspberry Pi, and modules and kits built on top of them, that make this type of project more affordable and accessible to the casual hobbyist. I was excited by Katherine's talk because Robot Operating System (ROS) seems to do for the software side what Arduino and such do for the hardware side. ROS is a framework that can be used to control a wide range of robots and hardware. It abstracts away the hard work, allowing for a publish-subscribe method of communicating with your robot's subsystems. A plus side is that you can use higher-level programming languages such as Python or Lisp, not just C and C++, and there is an active and vibrant open source community built up around it already. Katherine did multiple demonstrations with a robot arm that she'd brought to the talk, that did much … -
Why Doesn't Python Have Switch/Case?
Unlike every other programming language I've used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping: def numbers_to_strings(argument): switcher = { 0: "zero", 1: "one", 2: "two", } return switcher.get(argument, "nothing") This code is analogous to: function(argument){ switch(argument) { case 0: return "zero"; case 1: return "one"; case 2: return "two"; default: return "nothing"; }; }; While the Python code is often more terse than the standard method of handling cases, I could argue it is more arcane. When I first started Python it felt weird and distracting. Over time it grew on me, the use of a dictionary key being the identifier in a switch becoming more and more habitual. Dictionary Mapping for Functions In Python we can also include functions or lambdas in our dictionary mapping: def zero(): return "zero" def one(): return "one" def numbers_to_functions_to_strings(argument): switcher = { 0: zero, 1: one, 2: lambda: "two", } # Get the function from switcher dictionary func = switcher.get(argument, lambda: "nothing") # Execute the function return func() While the code inside zero() and one are simple, many Python programs use dictionary mappings like this to dispatch complex procedures. Dispatch Methods … -
Why Doesn't Python Have Switch/Case?
Unlike every other programming language I've used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping: def numbers_to_strings(argument): switcher = { 0: "zero", 1: "one", 2: "two", } return switcher.get(argument, "nothing") This code is analogous to: function(argument){ switch(argument) { case 0: return "zero"; case 1: return "one"; case 2: return "two"; default: return "nothing"; }; }; While the Python code is often more terse than the standard method of handling cases, I could argue it is more arcane. When I first started Python it felt weird and distracting. Over time it grew on me, the use of a dictionary key being the identifier in a switch becoming more and more habitual. Dictionary Mapping for Functions In Python we can also include functions or lambdas in our dictionary mapping: def zero(): return "zero" def one(): return "one" def numbers_to_functions_to_strings(argument): switcher = { 0: zero, 1: one, 2: lambda: "two", } # Get the function from switcher dictionary func = switcher.get(argument, lambda: "nothing") # Execute the function return func() While the code inside zero() and one are simple, many Python programs use dictionary mappings like this to dispatch complex procedures. Dispatch Methods … -
Why Doesn't Python Have Switch/Case?
Unlike every other programming language I've used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping: def numbers_to_strings(argument): switcher = { 0: "zero", 1: "one", 2: "two", } return switcher.get(argument, "nothing") This code is analogous to: function(argument){ switch(argument) { case 0: return "zero"; case 1: return "one"; case 2: return "two"; default: return "nothing"; }; }; While the Python code is often more terse than the standard method of handling cases, I could argue it is more arcane. When I first started Python it felt weird and distracting. Over time it grew on me, the use of a dictionary key being the identifier in a switch becoming more and more habitual. Dictionary Mapping for Functions In Python we can also include functions or lambdas in our dictionary mapping: def zero(): return "zero" def one(): return "one" def numbers_to_functions_to_strings(argument): switcher = { 0: zero, 1: one, 2: lambda: "two", } # Get the function from switcher dictionary func = switcher.get(argument, lambda: "nothing") # Execute the function return func() While the code inside zero() and one are simple, many Python programs use dictionary mappings like this to dispatch complex procedures. Dispatch Methods … -
Deploying a Django application - Part I
Well, first and foremost, this blog just crossed 1000 page views. Sincere thanks to all readers. Despite what the title indicates, this is not the last post. The world of Django is ever changing and there's always new stuff to learn. But this post (or series of posts, haven't decided yet) will show you how to deploy the project you've created to a server and make it battle ready.I was recently drafted by my college to create and deploy an online mentorship platform. We have a mentorship process that involves scheduling meetings with mentors and discussing attendance, marks and also stuff like grievances. The college wants to make it paper free. So here I am. It's a point of pride, because I'm creating and deploying all by myself.Anyway, first off, let's see what all we need to pull this off. Here's the list:Working Django code (duh.)A dedicated computer that will act as a server. Specifications:At least 4 GB RAM (to handle multiple concurrent requests)At least 500 GB Hard Disk space (to store the database and static files)Django installation: same as or one compatible with the one you developed your project inA static IP address that is unique within the network … -
Testing Client-Side Applications with Django Post Mortem
I had the opportunity to give a webcast for O’Reilly Media during which I encountered a presenter’s nightmare: a broken demo. Worse than that it was a test failure in a presentation about testing. Is there any way to salvage such an epic failure? What Happened It was my second webcast and I chose to use the same format for both. I started with some brief introductory slides but most of the time was spent as a screen share, going through the code as well as running some commands in the terminal. Since this webcast was about testing this was mostly writing more tests and then running them. I had git branches setup for each phase of the process and for the first forty minutes this was going along great. Then it came to the grand finale. Integrate the server and client tests all together and run one last time. And it failed. I quickly abandoned the idea of attempting to live debug this error and since I was at the end away I just went into my wrap up. Completely humbled and embarrassed I tried to answer the questions from the audience as gracefully as I could while inside …