Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Tips #19 Protecting Sensitive Information
The internet is a wild land. Security must be priority one when deploying a web application on the internet. The Django framework does an amazing job providing reliable and secure APIs. But none of that matters if we don’t use them properly. Nothing new that we should never deploy a Django application with DEBUG=True, right? One of the features of having DEBUG=True is dumping lots of metadata from your environment, including the whole settings.py configurations, when a exception occurs. Even though you will never be using DEBUG=True, you need extra care when naming the configurations in the settings.py module. Make sure all sensitive variables use one of the keywords: API KEY PASS SECRET SIGNATURE TOKEN This way, Django will not dump those variables that may contain sensitive information. Do S3_BUCKET_KEY = 'xxxxxxxxxxxxxxxx' Don't S3_BUCKET = 'xxxxxxxxxxxxxxxx' CHAVE_DE_ACESSO = 'xxxxxxxxxxxxxxxx' # "access key" in portuguese Even when you are running your application with DEBUG=False, if it’s configured to send error reports via email, there is a chance of the error report being exposed, specially if you are transmitting error reports unencrypted over the internet. PS: I mention this a lot here in the blog, but it’s never enough: Don’t commit sensitive … -
How to Handle GitHub Webhooks Using Django
Webhooks are a convenient way to notify external services when a certain event occur. GitHub provides an easy way to create Webhooks for the git repositories. You can pick the events such as push, pull requests, and only be notified when they occur. It can be used to integrate external applications with GitHub, perform Continuous Integration tasks or automate deployments. In this tutorial I will show you how to securely handle those notifications in a Django application. Creating the Webhook Let’s create a basic example so we can get more comfortable with the concept. First create a route to handle to Webhook POST data: urls.py: from core import views urlpatterns = [ ... url(r'^api/hello/$', views.hello, name='hello'), ] views.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def hello(request): return HttpResponse('pong') Since by default Django protects views from receiving POST requests without the csrf middleware token, and in this case we are creating a view to actually handle a POST request from outside our application, we need to decorate the view function with the @csrf_exempt decorator. Now we go to GitHub and access the repository we want to create the Webhook. Go to Settings then Webhooks. Then inside Webhooks we … -
JSON Web Tokens in django application- part three
As we have working application now it's high time to make it more secure by authenticating users. To do this I will use JSON Web Tokens. Table of Contents: JWT in Django Rest Framework Implementing JWT in DRF application Other blog posts in this series JWT in Django Rest Framework There are few packages on pypi that provide JWT support but as I am already using DRF I choose package called REST framework JWT Auth. It's simple package and does it's job well so I can recommend it to everyone. But you have to make sure that your application is behind SSL/TLS as JWT tokens generated are not signed. But enough writing- let's jump into the code. Implementing JWT in DRF application First I added small change to my Task model definition in models.py: class Task(models.Model): # rest of model person = models.ForeignKey('auth.User', related_name='tasks') # rest of model It is the same model definition but written using string. The code in Django responsible for model lookup based on the string can be seen here. Then I added an additional field to UserSerializer- thanks to that when getting info about the user I also get info about which tasks this user … -
JSON Web Tokens in django application- part three
As we have working application now it's high time to make it more secure by authenticating users. To do this I will use JSON Web Tokens. Table of Contents: JWT in Django Rest Framework Implementing JWT in DRF application Other blog posts in this series JWT in Django Rest Framework … -
Django test optimization with no-op PIL engine
The Air Mozilla project is a regular Django webapp. It's reasonably big for a more or less one man project. It's ~200K lines of Python and ~100K lines of JavaScript. There are 816 "unit tests" at the time of writing. Most of them are kinda typical Django tests. Like: def test_some_feature(self): thing = MyModel.objects.create(key='value') url = reverse('namespace:name', args=(thing.id,)) response = self.client.get(url) .... Also, the site uses sorl.thumbnail to automatically generate thumbnails from uploaded images. It's a great library. However, when running tests, you almost never actually care about the image itself. Your eyes will never feast on them. All you care about is that there is an image, that it was resized and that nothing broke. You don't write tests that checks the new image dimensions of a generated thumbnail. If you need tests that go into that kind of detail, it best belongs somewhere else. So, I thought, why not fake ALL operations that are happening inside sorl.thumbnail to do with resizing and cropping images. Here's the changeset that does it. Note, that the trick is to override the default THUMBNAIL_ENGINE that sorl.thumbnail loads. It usually defaults to sorl.thumbnail.engines.pil_engine.Engine and I just wrote my own that does no-ops in … -
Handling statuses in Django #2
As discussed in the previous article, django-fsm is a great plugin to handle statuses in Django. Let's use it with an API. -
Handling statuses in Django #2
As discussed in the previous article, django-fsm is a great plugin to handle statuses in Django. Let's use it with an API. -
Presidential debate questions influenced by open source platform
During the past two presidential debates, moderators from ABC and Fox asked candidates Hillary Clinton and Donald Trump voter-submitted questions from PresidentialOpenQuestions.com. The site, created by the bipartisan Open Debate Coalition (ODC) with the support of Caktus Group, is built on top of the open source Django web framework. -
ShipIt Day Recap Q3 2016
This ShipIt day marks four years of ShipIt days at Caktus! We had a wide range of projects that people came together to build. Most importantly, we all had fun and learned through actively working on the projects. People explored new technologies and tools, and had a chance to dig a bit deeper into items that piqued their interest in their regular work. -
How to Add Social Login to Django
In this tutorial we will implement Facebook, Twitter and GitHub authentication using the python-social-auth library. They support several other services and the process should be somewhat similar. The python-social-auth library have several customization options, which sometimes makes it challenging to get started. So for this tutorial I will guide you through the mandatory steps where in the end you will have a fully functional social authentication. Installation As usual, go for pip: pip install python-social-auth Add the social.apps.django_app.default to your INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social.apps.django_app.default', # <-- 'mysite.core', ] Migrate the database: python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, social_auth Running migrations: Applying social_auth.0001_initial... OK Applying social_auth.0002_add_related_name... OK Applying social_auth.0003_alter_email_max_length... OK Applying social_auth.0004_auto_20160423_0400... OK Applying social_auth.0005_auto_20160727_2333... OK The library will automatically handle authentication tokens and all the required information to deal with OAuth and OAuth2. Generally speaking, you won’t need to handle it manually nor access the user’s social profile. Configuration Update the MIDDLEWARE_CLASSES by adding the SocialAuthExceptionMiddleware to the end of it: MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social.apps.django_app.middleware.SocialAuthExceptionMiddleware', # <-- ] Now we update the context_processors inside TEMPLATE: TEMPLATES = [ … -
JSON Web Tokens in django application- part two
In this blog post, I will deal with creating simple Django application for creating tasks using django rest framework. From this blog post, you can learn how to setup basic DRF application. Table of Contents: Overview of application Application code Other blog posts in this series Overview of application The main goal of this application is to create tasks. Each task has a title - string with a maximum length of 100 characters. Task also has a person to which it is bound (many to one relation - ForeginKey). The last thing that task have is date and time which given task is due to. The user can easily modify each of tasks so GET, POST, PUT and DELETE methods are supported. As we know how the application is designed let's jump into the code. Application code First, there is a need to create model for Task: from django.db import models from django.contrib.auth.models import User class Task(models.Model): title = models.CharField(max_length=100) person = models.ForeignKey(User) due_to = models.DateTimeField() def __str__(self): return 'Task with title: {}'.format(self.title) The arguments of Task correspond to what was written in the overview. As we have models ready now it's time to create serializers so data from database … -
JSON Web Tokens in django application- part two
In this blog post, I will deal with creating simple Django application for creating tasks using django rest framework. From this blog post, you can learn how to setup basic DRF application. Table of Contents: Overview of application Application code Other blog posts in this series Overview of application The … -
Basics of Webpack
Webpack can be complicated, but it doesn't have to be. Learn some of the basics of webpack, and how you can get started with it while actually understanding it. In this video we start our journey to working with react and django, but first we need to build our javascript and that is where webpack comes in.Watch Now... -
Sending HTML emails with embedded images from Django
Currently I'm working on an application which sends HTML emails with embedded or inline images and multiple CSV and PDF attachments. Let's assume that we will be using an object containing data for our email. I'm providing my models here just as a reference to get the idea: class RenderedReport(models.Model): report = models.ForeignKey('Report', related_name='rendered_reports') approved_by = models.ForeignKey('auth.User', blank=True, null=True) date_rendered = models.DateTimeField(auto_now_add=True) date_queried = models.DateTimeField(blank=True, null=True) date_approved = models.DateTimeField(blank=True, null=True) date_sent = models.DateTimeField(blank=True, null=True) class Meta: get_latest_by = 'date_rendered' ordering = ('-date_rendered',) def __unicode__(self): return str(self.report) class RenderedView(models.Model): rendered_report = models.ForeignKey('RenderedReport', related_name='rendered_views') view = models.ForeignKey('View', related_name='rendered_views') png = ImageField(upload_to='reports') pdf = models.FileField(upload_to='reports', blank=True) csv = models.FileField(upload_to='reports', blank=True) class Meta: ordering = ['view'] def __unicode__(self): return str(self.view) @property def image_filename(self): return os.path.basename(self.png.name) I don't like the idea of re-inventing the wheel, so I will be using a responsive email template from Zurb Studios. I'm skipping the entire HTML template code for brevity because it wasn't modified. We only need this part: <!-- BODY --> <table class="body-wrap"> <tr> <td></td> <td class="container" bgcolor="#FFFFFF"> <div class="content"> <table> <tr> <td> {% for view in views %} <h3>{{ view }}</h3> <p><img src="cid:{{ view.image_filename }}" /></p> {% if not forloop.last %}<p>&nbsp;</p>{% endif %} {% endfor %} </td> … -
Don't keep important data in your Celery queue
The Celery library (previous posts) makes it as easy to schedule a task to run later as calling a function. Just change: -
Django Tips #18 Difference Between ugettext And ugettext_lazy
The Django translation API provides several utility functions to help you translate your application. They are all available in the django.utils.translation module. For the most cases you will be using ugettext() and ugettext_lazy(). The “u” prefix stands for “unicode”, and usually it is a better idea to use ugettext() instead of gettext(), and ugettext_lazy() instead of gettext_lazy(), since for the most part we will be working with international charsets. As the name suggests, the “lazy” version of the function holds a reference to the translation string instead of the actual translated text, so the translation occurs when the value is accessed rather than when they’re called. It’s very important to pay attention to this details, because in a Django project there are several cases where the code is only executed once (on Django startup). That happens with definition modules like models, forms and model forms. So, what would happen if you use ugettext() (instead of ugettext_lazy()) in a model definition (let’s say on field labels): Django starts up, the default language is english; Django picks the english version of the field labels; The user changes the website language to spanish; The labels are still displayed in english (because the field … -
PyData Carolinas 2016 Recap
We had a great time at the inaugural PyData Carolinas hosted nearby at IBM in the Research Triangle Park. People from Caktus presented a number of talks and the videos are now up online: -
Handling statuses in Django #1
Whether you're building up a CMS or a bespoke application, chances are that you will have to handle some states / statuses. Let's discuss your options in Django. -
Handling statuses in Django
Whether you're building up a CMS or a bespoke application, chances are that you will have to handle some states / statuses. Let's discuss your options in Django. -
Django admin template structure
As you all (probably) know, Django is a magnificent Web framework to build the website of your dreams. There is a plethora of tutorials, how-to's, getting-started, django-for-dummies out there in the internet-wild. I am not going to show you the Django basics (models, views, templates or forms to name a few). I just want to share with you the template inheritance of the incredible Django admin contribution package. At this time of writing, I am dreaming of a much more appealing admin interface which is based on the super-fancy AdminLTE template (there is a free version you can download, under the MIT License -- more about licences here). But in order to adopt the new-dreamed template in my own project I must understand the template inheritance workflow of the built-in Django admin app. I know there is a package, already out there (django-adminlte-templates), that offer you the capability of using this admin template but I wanted to deeply understand how the Django admin template system is assembled and working so flawlessly. Lets get to work: The core ones In this section we will describe briefly, the core HTML templates where the rest inherit from. If you do not have Django … -
How to Deploy a Django Application to Digital Ocean
DigitalOcean is a Virtual Private Server (VPS) provider. In my opinion it’s a great service to get started. It’s cheap and very simple to setup. In this tutorial I will guide you through the steps I go to deploy a Django application using Ubuntu 16.04, Git, PostgreSQL, NGINX, Supervisor and Gunicorn. In this tutorial we will be deploying the following Django application: github.com/sibtc/urban-train It’s just an empty Django project I created to illustrate the deployment process. If you are wondering about the name, it is the repository name suggestion GitHub gave. Anyway! Let’s get started. Create a New Droplet Pick the Ubuntu 16.04.1 distribution: Select the size of the Droplet (cloud server): Select the region you want to deploy: Finally pick a name for the Droplet: And click on Create. After that you will see the recently created droplet in your profile: You will receive the root password via email. Now pick the IP Address and ssh into the server: ssh root@107.170.28.172 You will be asked to change the root password upon the first login. If you are using a Unix-like operating system you can use the terminal. If you are on Windows, you can perhaps download PuTTY. Also if … -
Common web site security vulnerabilities
I recently decided I wanted to understand better what Cross-Site Scripting and Cross-Site Request Forgery were, and how they compared to that classic vulnerability, SQL Injection. I also looked into some ways that sites protect against those attacks. Vulnerabilities SQL Injection SQL Injection is a classic vulnerability. It probably dates back almost to punch cards. Suppose a program uses data from a user in a database query. For example, the company web site lets users enter a name of an employee, free-form, and the site will search for that employee and display their contact information. A naive site might build a SQL query as a string using code like this, including whatever the user entered as NAME: "SELECT * FROM employees WHERE name LIKE '" + NAME + "'" If NAME is "John Doe", then we get: SELECT * FROM employees WHERE name LIKE 'John Doe' which is fine. But suppose someone types this into the NAME field: John Doe'; DROP TABLE EMPLOYEES; then the site will end up building this query: SELECT * FROM employees WHERE name LIKE 'John Doe'; DROP TABLE EMPLOYEES;' which might delete the whole employee directory. It could instead do something less obvious but even … -
Season of fixes
The last few months has been dominated by bug-fixing and testing in Evennia-land. A lot more new users appears to be starting to use Evennia, especially from the MUSH world where the Evennia-based Arx, After the Reckoning is, while still in alpha, currently leading the charge. With a new influx of users comes the application of all sorts of use- and edge-cases that stretch and exercise the framework in all the places where it matters. There is no better test of code than new users trying to use it unsupervised! Evennia is holding up well overall but there are always things that can be improved. I reworked the way on-object Attributes was cached (from a stupid but simple way to a lot more sophisticated but harder way) and achieved three times faster performance in certain special cases people had complained about. Other issues also came to view while diving into this, which could be fixed. I reworked the venerable batch command and batchcode processors (these allow to create a game world from a script file) and made their inputs make more sense to people. This was one of the older parts of Evennia and apart from the module needing a … -
How to Use Django's Generic Relations
You probably have already seen Django’s ContentTypes and wondered how to use it or what is it for anyway. Basically it’s a built in app that keeps track of models from the installed apps of your Django application. And one of the use cases of the ContentTypes is to create generic relationships between models. That’s what this post is about. Installation If you didn’t remove anything from settings generated by the python manage.py startproject command, it’s probably already installed. Also Django’s built in authentication system relies on it. Basically just make sure you have it in your INSTALLED_APPS: INSTALLED_APPS = [ ... 'django.contrib.contenttypes', ... ] Example Scenario Let’s say we have one social app where the users can ask and answer questions, up vote, down vote, favorite a question, like a post in the website, etc. To keep track of that we create a model named Activity. See below: class Activity(models.Model): FAVORITE = 'F' LIKE = 'L' UP_VOTE = 'U' DOWN_VOTE = 'D' ACTIVITY_TYPES = ( (FAVORITE, 'Favorite'), (LIKE, 'Like'), (UP_VOTE, 'Up Vote'), (DOWN_VOTE, 'Down Vote'), ) user = models.ForeignKey(User) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) date = models.DateTimeField(auto_now_add=True) post = models.ForeignKey(Post, null=True) question = models.ForeignKey(Question, null=True) answer = models.ForeignKey(Answer, null=True) comment … -
How kubeadm Initializes Your Kubernetes Master
`kubeadm` is a new tool that is part of the Kubernetes distribution as of 1.4.0 which helps you to install and set up a Kubernetes cluster. One of the most frequent criticisms of Kubernetes is that it's hard to install. `kubeadm` really makes this easier so I suggest you give it a try. The documentation for kubeadm outlines how to set up a cluster but as I was doing that I found how `kubeadm` actually sets up the master to be really interesting so I wanted to share that here. ## The Kubernetes Control Plane The Kubernetes control plane consists of the Kubernetes API server (`kube- apis[...]