Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

August 07 2017

Django Auth with JWT

This is an example of Django auth with JWT tokens

August 05 2017

Django Online Now Users - Middleware

django online users, usage: {{ request.online_now }} or {{ request.online_now_ids }}, complete tutorial: https://python.web.id/blog/django-count-online-users/, this snippet forked from: https://gist.github.com/dfalk/1472104

August 04 2017

Image as base64 in django

Easy way to get base64 for the image to display in the template, eg: <img src="{{ post.get_cover_base64 }}">

July 27 2017

Dynamic DEBUG setting for PyCharm

  1. Next to the Play button you can Edit Configuration
  2. Click the green + on the left, add 2 "Django Server". Call one DEBUG, call the other RUN.
  3. Add "DEBUG False" to RUN in its "Environment variables"
  4. Add "DEBUG True" to DEBUG in its "Environment variables" (make sure the port # is different ...

July 19 2017

Place a file in an object from command-line (Python 3.x only)

You can place this snippet in management/commands/ and have it upload files from disk into objects in your database.

Usage: python manage.py upload_file_to_model myapp mymodel myfield 1 field_name /some/file/path

July 06 2017

Friendly ID(Python 3.X)

This is just modified version of friendly id for make this script compatible with python 3.x

Invoice numbers like "0000004" are a little unprofessional in that they expose how many sales a system has made, and can be used to monitor the rate of sales over a given time ...

June 21 2017

Mixin to set url kwargs to Class Based Views

This mixin is for class based views. Kwargs passed from url patterns to views via the dispatch method.

June 12 2017

Python at Instagram (PyCon 2017 Must-See Talk 2/6)

Part two of six in the 2017 edition of our annual PyCon Must-See Series, highlighting the talks our staff especially loved at PyCon. While there were many great talks, this is our team's shortlist.

One of the talks that I considered a must-see was a keynote presentation by Instagram employees Lisa Guo and Hui Ding about upgrading Python and Django.

This is something that many businesses know they "should" do, but think is too impractical "right now". Instagram performed an upgrade without any downtime and without slowing down the pipeline of new features. Caktus carries out Django upgrades as part of our managed hosting and upgrade protection services, so this talk was especially relevant to what we do as a company.

June 09 2017

CSV file to Django Models

Handling CSV (comma separated ...

Use Gmail for Email in Django

This is a simple way to setup ...

Configure Email in Django

Email configuration is simple....

June 08 2017

How To Show Correct List Item Indexes When Using Pagination in Django

In your Django template put something like this:

  1. <ul>
  2. {% for object in object_list %}
  3. <li>{{ forloop.counter0|add:page_obj.start_index }}. {{ object }}</li>
  4. {% endfor %}
  5. </ul>


object_list - is a list of objects produced by pagination;

page_obj - is a page object produced by pagination

page_obj ...

Read now

June 07 2017

How to get a list of all user permissions available in Django based project

Django comes with a simple permissions system. It provides a way to assign permissions to specific users and groups of users. The system adds "change, remove and add" permissions automatically to every model class. And it's pretty easy to add custom permissions to a model class, like this:


  1. class ...

Read now

June 01 2017

Interview with Rivo Laks about Docker

This is an interview I took from Estonian Django developer Rivo Laks about Docker. Recorded in DjangoCon EU 2017, Florence, Italy.



A: Hello everyone, this is Antonis from djangodeployment.com. The date is 7 April 2017 and I am in Florence, Italy, at the European Django conference. I’m sitting with Rivo Laks, who is a developer from Estonia. He has a company called Thorgate, and we are going to be talking about Docker and similar things, mostly about deployment. Hello Rivo, how do you like the conference?

R: Hello Antonis. I like it a lot and I think it’s my fifth DjangoCon now, so it’s been a pleasant experience throught the years.

A: That’s very interesting because it’s actually my first Django conference. So what do you think it is that brings you here?

R: I guess it’s the people, most importantly; and also the fact that this is a good place to keep you up to date with everything that is going on in the Django world.

A: Would you like to tell me some examples of Django applications that your company makes?

R: Well, it usually begins with some sort of business problem. One recent example is a company that manufactures pipes, and they needed a better way of getting an overview and keeping an overview of their production process and production queues, so we helped them with that by creating a Django application that basically contains the schedule for the production, so that they can add new pipes there from their existing bookkeeping software, then do quality assurance as well as use it in the future for actual monitoring of the production.

A: You made an interesting presentation a few days ago about how you use Docker to deploy your Django apps. So the question, first of all, is if this is something you have been doing for a long time, and I would especially like to know what problem Docker is solving for you.

R: We started looking into Docker because we had some dependency isolation issues, because for more recent projects we wanted to use more recent versions of Python and PostgreSQL, and at the same time we had, in the same server, older projects, running on older versions of Python, which we didn’t feel like upgrading at that time. We hoped Docker would help us keep these requirements and different versions of Python separate for each project. I think it succeeded in that, because we are now able to accomplish that and we have been using Docker in test and production servers for something like six months now, perhaps slightly less. It’s a quite recent development, but all the projects we are starting today are based on Docker.

A: I understand that you mostly deploy on single server. So you may have a virtual server and you deploy some Django applications in there. When this problem arose, and you had made some applications that use newer versions of PostgreSQL and Python, why didn’t you just create another virtual server perhaps, and you needed to use Docker to isolate things on the same virtual server?

R: We do use quite a low number of servers and put multiple projects on a single server because the projects themselves are often quite small and they don’t require a full server and so on one hand it is financially more efficient to keep multiple projects on a single server, and on the other hand it’s also more efficient for us to not have to maintain multiple servers, because we only have to monitor, configure backups and everything else for a low number of machines.

A: There is a lot of hype about Docker; we were discussing this yesterday. It’s a relatively new technology, it’s changing a lot, and it seems like it’s the new fashion that is going to solve, somehow, magically, all your problems, like XML was 20 years ago—I can’t remember any more recent example though I’m certain there is. When would you advise someone NOT to use Docker?

R: I definitely agree with you about the hype, there’s lots of hype going around, and it makes it a bit difficult to find good and objective information. When would I advise to not use Docker? I think that if you have a project that’s already running, that’s perhaps a bit on the bigger side, and that you’re not that actively developing any more, then there’s probably no point in moving to Docker. Perhaps you don’t need Docker in some cases. For us there was a very clear need or desire of what we wanted to accomplish with Docker, so if you don’t have that need, if you are looking at the advantages Docker might give you, and decide that these advantages are not really something that are a problem for you, then I guess you can just skip on it.

A: Thank you very much Rivo, and I hope to see you again next year.

R: Thank you for having me, and likewise.


Related information:

Did you like this post?

© 2017 Antonis Christofides and Rivo Laks.
The interview is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License.

Photo by Bartek Pawlik
© 2017 DjangoCon Europe 2017
Original photo

The post Interview with Rivo Laks about Docker appeared first on Django deployment.

May 30 2017

On Conference Speaking

I’ve seen quite a bit of the world thanks to being invited to speak at conferences. Since some people are under the impression that serial conference speakers possess some special talents, I’d like to demystify my process by walking you through my latest talk from start to finish.

May 28 2017

Django REST Framework: JSON Web Tokens (JWT)

Our last post was about Authentication and Permissions and we covered the available methods of authentication in Django REST Framework. In that post, we learned how to use the built in Token based authentication in DRF. In this post, we will learn more about JSON Web Tokens aka JWT and we will see if JWT can be a better authentication mechanism for securing our REST APIs.

Understanding JSON Web Tokens (JWTs)

We have actually written a detailed blog post about JSON Web Tokens earlier. In case you have missed it, you probably should read it first. We have also described how to use JWT with Flask – reading that one might also help better understand how things work. And of course, we will briefly cover the idea of JWT in this post as well.

If we want to put it simply – you take some data in JSON format, you hash it with a secret and you get a string that you use as a token. You (your web app actually) pass this token to the user when s/he logs in. The user takes the token and on subsequent requests, passes it back in the “Authorization” header. The web app now takes this token back, “decodes” it back to the original JSON payload. It can now read the stored data (identity of the user, token expiry and other data which was embedded in the JSON). While decoding, the same secret is used, so third party attackers can’t just forge a JWT. We would want our token to be small in size, so the JSON payload is usually intentionally kept small. And of course, it should not contain any sensitive information like user password.

JWT vs DRF’s Token Based Authentication

So in our last blog post, we saw Django REST Framework includes a token based authentication system which can generate a token for the user. That works fine, right? Why would we want to switch to JSON Web Tokens instead of that?

Let’s first see how DRF generates the tokens:

    def generate_key(self):
        return binascii.hexlify(os.urandom(20)).decode()

It’s just random. The token generated can not be anyway related to the user that it belongs to. So how does it associate a token with an user? It stores the token and a reference to the user in a table in database. Here comes the first point – while using DRF’s token based auth, we need to query database on every request (unless of course we have cached that token which). But what if we have multiple application servers? Now we need all our application servers to connect to the same database or same cache server. How will that scale when the project gets really really big? What if we want to provide single sign on across multiple services? We will need to maintain a central auth service where other services request to verify a token. Can JWT simplify these for us?

JWT is just an encoded (read – hashed / signed) JSON data. As long as any webservice has access to the secret used in signing the data, it can also decode and read the embedded data. It doesn’t need any database calls. You can generate the token from one service and other services can read and verify it just fine. It’s more efficient and simply scales better.

JWT in Django REST Framework

DRF does not directly support JWTs out of the box. But there’s an excellent package that adds support for it. Let’s see how easily we can integrate JWT in our REST APIs.

Install and Configure

Let’s first install the package using pip –

pip install djangorestframework-jwt

That should install the package. Now we need to add rest_framework_jwt.authentication.JSONWebTokenAuthentication to the default authentication classes in REST Framework settings.


We added it to the top of the list. Next, we just have to add it’s built in view to our urlpatterns.

from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = router.urls + [
    url(r'^jwt-auth/', obtain_jwt_token),
Obtain a Token

The obtain_jwt_token view will check the user credentials and provide a JWT if everything goes alright. Let’s try it.

$ curl --request POST \
  --url http://localhost:8000/api/jwt-auth/ \
  --header 'content-type: application/json' \
  --data '{"username": "test_user", "password": "awesomepwd"}'


Awesome, everything worked just fine. We have got our token too. What do we do next? We use this token to access a secured resource.

Using the obtained JWT

We need to pass the token in the form of JWT <token> as the value of the Authorization header. Here’s a sample curl request:

$ curl -H "Content-Type: application/json" -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJlbWFpbCI6IiIsInVzZXJuYW1lIjoidGVzdF91c2VyIiwiZXhwIjoxNDk1OTkyOTg2fQ.sWSzdiBNNcXDqhcdcjWKjwpPsVV7tCIie-uit_Yz7W0" -X GET  http://localhost:8000/api/subscribers/

[{"id":1,"name":"Abu Ashraf Masnun","age":29,"email":"masnun@polyglot.ninja"},{"id":2,"name":"Abu Ashraf Masnun","age":29,"email":"masnun@polyglot.ninja"},{"id":3,"name":"Abu Ashraf Masnun","age":29,"email":"masnun@polyglot.ninja"},{"id":4,"name":"Abu Ashraf Masnun","age":29,"email":"masnun@polyglot.ninja"}]

So our token worked fine! Cool!

Where to go next?

Now that you have seen how simple and easy it is to add JSON Web Token based authentication to Django REST Framework, you probably should dive deeper into the package documentation. Specially these topics might be interesting –

  • Refresh Tokens: If you enable JWT token refreshing, you can exchange your current token with a new, fresh one before the existing one expires. The new token will of course have a renewed expiry time set.
  • Verify Token: If you just share the secret, all services can verify the user on their own. However, in modern micro service based architecture, you may want to provide an API end point that other services can use to verify a JWT they received from the user. This can be useful for those scenarios.
  • And of course look at the settings options available and see how you can customize the token generation process.

In the future, we shall try to cover more about Django, Django REST Framework and Python in general. If you liked the content, please subscribe to the mailing list so we can notify you when we post new contents.

The post Django REST Framework: JSON Web Tokens (JWT) appeared first on Polyglot.Ninja().

Create an Ionic 3 mobile app with Python Django as backend

Ionic 3 with Django backend

In this two parts tutorial ,we are going to recreate our previous Ionic 3 product inventory manager application which used a local SQLite database to use a Python Django backend .

Django 1.11 : Create or start your first project

Django 1.11 create/start project

Django is a Python based framework which offers developers all they need to create a web apps and websites in a clean ,rapid and a pragmatic way .

How do I start a Django project ? is the first quesion which gets asked by a beginner Django developer so lets answer it .

Tutorial requirements

To better grasp this tutorial ,you need to have some Python experience and also how to work with Linux bash commands or Windows command prompt if you are using Windows for development .

Development requirements

Before you can create or start a Django project you need to have you development environment setup .

Here is what you need to install before continuing with this tutorial :

Python 2.7.x or 3.4.x

PIP package manager



Code editor (Sublime,gedit etc.)

If you are using a Linux/MAC machine you should have Python already installed .

You can check that running the following command on your terminal

python -v 

If you don't have Python installed head over to Python download page

PIP is a Python package manager used to easily install Python packages and their dependencies .You can install PIP using curl utility

curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
python get-pip.py 

Then verify It's successfully installed

pip -V

Virtualenv is a tool which allows you to create virtual Python environments ot sandboxes .It's a common practice to create a virtual environment for each Python project to prevent different versions of packages and libraries from messing with each other .

To install Virtualenv ,run the following :

pip install virtualenv

After installing all development requirements .It's time to create a virtual development environment using Virtualenv :

mkdir django111-project
cd django111-project
virtualenv env

Then make sure to activate the environment with :

source env/bin/activate

In case you want to exit the environment ,you simply run :


Now we are ready to install Django .

pip install django

This will install the latest Django framework version .

When writing this tutorial the latest Django version is 1.11

Create/start Django project

At this point after installing the development environment ,setting up a new virtual environment and installing the latest version of Django .You can create and start a django project by running :

django-admin.py startproject django111-project

This will create a project with a basic directory structure

├── django111-project
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
└── manage.py

Next navigate inside your project :

cd django111-project 

Setup a database using :

python manage.py migrate 

This will create a SQLite database which is the default option for Django project but you can also use any other advanced database system such as MySQL or PostgresSQL etc .

SQLite comes pre-installed with Python so we are going to use it for this simple project .

Then run a local development server with :

python manage.py runserver

You should be able to visit your app at :

Create a Django app

A Django app is a collection of apps which are used to separate logical units of your app for better project organization .

To implement any project requirements you need first to create a Django app :

python manage.py startapp app1 

Your project directory structure becomes

├── app1
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── django111-project
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
└── manage.py

But not just that ,you need also to do some configuration .

Head over and open your project settings.py ,locate INSTALLED_APPS and your app there .


Next you need to create migrations files :

python manage.py makemigrations     

Then actually run migrations to create tables related to the second app

python manage.py migrate 


So we have seen how to create and start a new Django project by first installing the development environment then create the actual project .

Django vs Flask in 2017

The Python language has many great frameworks for building web applications among them Django and Flask .

Both frameworks are gaining more popularity steadily in time and there are no signs they are becoming less popular or obsolete even if the web has known many important changes since the data they have been created .

Django was created in 2005 while Flask was created in 2010 .Today we are in 2017 which means Django is 12 years old and Flask is 7 years old .They are both extremely popular frameworks to build web applications with Python but they are so different in principle from each other .While Django follows a battery included approach making it a full packed ,complete and an opinionated framework ,on the other hand Flask is a micro framework ,an un-opinionated framework that let you choose what tools you can use for building a web app from the ORM to the templating engine .

In this post we'll discuss some points you might want to consider if you need to learn Django or Flask or maybe both ? and which framework you should consider using to build your next project ? and in which situations ?

They are both so popular so there are more and more websites built using both of them and more job demands for both frameworks .

Flask is a simple and flexible and lets you decide how to implement each major component such as the ORM to interact with databases ,the template engine ,forms etc .

Django is a little bit heavy when compared to Django .It has its own ORM , a template engine and even an admin back office out of the box .

Django has a predefined project directory structure while when you can structure a Flask project as you want .

When ypu should choose Flask ?

If you are just beginning web development with Python then Flask is a good option for learning purposes since you can have more control of all components of the framework .

Also if you are building small web applications then Flask can be also your to go choice .

How about Django ?

If you are a professional developer who needs to build quick prototypes or final products Django might be a good choice since it's a batteries included framework .There is a package for common web development tasks so you don't have to reinvent the wheen or waste your time building what other developers have already created .Just include the batteries and build your specefic requirements above them .

The Django ORM is easy to grasp and straightforward and lets you express your businness domain requirements clearly then you have the Django admin interface ,a complete web application that lets you do crud operations on your models such as creating ,updating ,deleting and views database records from an intuitive user interface generated for you on the fly without writing more code .

So thanks to batteries Django is your choice for either quick prototypes and final products .

Now lets see how we can create a simple Hello World web application in both frameworks :

Starting with Flask .Create a Python file

    touch webapp.py

Import Flask from flask

from flask import Flask         

Create an instance

app = Flask(__name__)

Create a view function which responds to HTTP requests and a route /

def hello():
return "Hello, World!"    

This function responds with response "Hello, World!" when thr user visit / route .


if __name__ == "__main__":

We call the app run() method to start the web app .

Now you can run this app from terminal :

python webapp.py 

You should get

Running on (Press CTRL+C to quit)

If you visit this address with a web browser you should get a web page with Hello, World! response

For Django ,you should first generate a project with

django-admin startproject djwebapp 
cd djwebapp 

Next you should create an app

python manage.py startapp myapp

Then change your settings.py to include this app in Installed Apps array .

Next open myapp/views.py and create a view function

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, World!")

After that you should open your project urls.py file and add an url mapping for this view function

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),

You should now be able to run your web app from the terminal

python manage.py runserver

As you can see you can use Flask to rapidly create an example web app that receives http requests and responds with http responses but you need to do more work if you just to make the same example with Django .

Choosing the right framework depends on many criteria ,you should take into consideration your goals , ara you just learning server side web development or you are building a project for a client ? you should also consider your project requirements ,some projects may be better developed in Django ,some other projects can be better created in Flask .Also remember if you need grained control over each part of your framework or you need to swap and makes use of different existing tools you should use Flask where you only have the bar minimum functionality and you have to choose other components by yourself .

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!