23 Jun 2017

feedDjango community aggregator: Community blog posts

django-debreach + DRF = sadness

I sunk 4 hours of my life into this problem yesterday so I thought I might post it here for future frustrated nerds like myself.

If you're using django-debreach and Django REST Framework, you're going to run into all kinds of headaches regarding CSRF. DRF will complain with CSRF Failed: CSRF token missing or incorrect. and if you're like me, you'll be pretty confused since I knew there was nothing wrong with the request. My token was being sent, but it appeared longer than it should be.

So here's what was happening and how I fixed it. Hopefully it'll be useful to others.

Django-debreach encrypts the csrf token, which is normally just fine because it does so as part of the chain of middleware layers in every request. However, DRF doesn't respect the csrf portion of that chain. Instead it sets csrf_exempt() on all of its views and then relies on SessionAuthentication to explicitly call CSRFCheck().process_view(). Normally this is ok, but with a not-yet-decrypted csrf token, this process will always fail.

So to fix it all, I had to implement my own authentication class and use that in all of my views. Basically all this does is override SessionAuthentication's enforce_csrf() to first decrypt the token:

class DebreachedSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):

        faux_req = {"POST": request.POST}

        CSRFCryptMiddleware().process_view(faux_req, None, (), {})
        request.POST["csrfmiddlewaretoken"] = faux_req["csrfmiddlewaretoken"]

        SessionAuthentication.enforce_csrf(self, request)

Of course, none of this is necessary if you're running Django 1.10+ and already have Breach attack protection, but if you're stuck on 1.8 (as we are for now) this is the best solution I could find.

23 Jun 2017 9:12pm GMT

Build GraphQL Web APIs with Django Graphene

On the previous tutorial we have introduced GraphQL to build Web APIs .In this tutorial we are going to build a real world example web application with Django ,which makes use of GraphQL and its Python implementation ,Graphene .

Tutorial Parts :

Building Better Django WEB APIs with GraphQL Tutorial

Build GraphQL Web APIs with Django Graphene

Lets start by creating a new virtual environment and install required packages including django ,

Head over to your terminal and enter :

virtualenv graphqlenv 
source graphqlenv/bin/activate 

This will create a new virtual environment and activate it .

Next install django and graphene packages with pip

pip install django 
pip install graphene_django

You can also install graphiql_django which provides a user interface for testing GraphQL queries against your server .

pip install graphiql_django

Next lets create a Django project with a single application :

python django-admin.py startproject inventory . 
cd inventory
python manage.py startapp inventory 

Open settings.py and add inventory and graphenedjango to installedapps array :

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'graphene_django',
    'inventory'
]

Then create your database :

python manage.py migrate 

Create models

Open inventory/models.py then add :

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

class Product(models.Model):

    sku = models.CharField(max_length=13,help_text="Enter Product Stock Keeping Unit")
    barcode = models.CharField(max_length=13,help_text="Enter Product Barcode (ISBN, UPC ...)")

    title = models.CharField(max_length=200, help_text="Enter Product Title")
    description = models.TextField(help_text="Enter Product Description")

    unitCost = models.FloatField(help_text="Enter Product Unit Cost")
    unit = models.CharField(max_length=10,help_text="Enter Product Unit ")

    quantity = models.FloatField(help_text="Enter Product Quantity")
    minQuantity = models.FloatField(help_text="Enter Product Min Quantity")

    family = models.ForeignKey('Family')
    location = models.ForeignKey('Location')


    def __str__(self):

        return self.title


class Family(models.Model):

    reference = models.CharField(max_length=13, help_text="Enter Family Reference")
    title = models.CharField(max_length=200, help_text="Enter Family Title")
    description = models.TextField(help_text="Enter Family Description")

    unit = models.CharField(max_length=10,help_text="Enter Family Unit ")

    minQuantity = models.FloatField(help_text="Enter Family Min Quantity")


    def __str__(self):

        return self.title


class Location(models.Model):


    reference = models.CharField(max_length=20, help_text="Enter Location Reference")
    title = models.CharField(max_length=200, help_text="Enter Location Title")
    description = models.TextField(help_text="Enter Location Description")

    def __str__(self):

        return self.title


class Transaction(models.Model):

    sku = models.CharField(max_length=13,help_text="Enter Product Stock Keeping Unit")
    barcode = models.CharField(max_length=13,help_text="Enter Product Barcode (ISBN, UPC ...)")

    comment = models.TextField(help_text="Enter Product Stock Keeping Unit")

    unitCost = models.FloatField(help_text="Enter Product Unit Cost")

    quantity = models.FloatField(help_text="Enter Product Quantity")

    product = models.ForeignKey('Product')

    date = models.DateField(null=True, blank=True)

    REASONS = (
        ('ns', 'New Stock'),
        ('ur', 'Usable Return'),
        ('nr', 'Unusable Return'),
    )


    reason = models.CharField(max_length=2, choices=REASONS, blank=True, default='ns', help_text='Reason for transaction')

    def __str__(self):

        return 'Transaction :  %d' % (self.id)

Next create migrations and appy them :

python manage.py makemigrations
python manage.py migrate

Adding an Admin Interface

The next thing is to add these models to the admin interface so we can add some data :

Open inventory/admin.py and add

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin

from .models import Product ,Family ,Location ,Transaction  
# Register your models here.

admin.site.register(Product)
admin.site.register(Family)
admin.site.register(Location)
admin.site.register(Transaction)

Next create a login to be able to access the admin app

python manage.py createsuperuser 

Enter username and password when prompted and hit enter .

Now run your web application with :

python manage.py runserver

Then go to http://127.0.0.1:8000/admin with your browser ,login and submit some data for created models .

Adding GraphQL support : Schema and Object Types

To be able to execute GraphQL queries against our web application we need to add a Schema ,Object Types and a view function which takes GraphQL queries .

Create app schema.py

Create inventory/schema.py then add

We first create a subclass of DjangoObjectType for each model we want to query with GraphQL

import graphene

from graphene_django.types import DjangoObjectType

from .models import Family , Location , Product , Transaction 

class FamilyType(DjangoObjectType):
    class Meta:
        model = Family 

class LocationType(DjangoObjectType):
    class Meta:
        model = Location 

class ProductType(DjangoObjectType):
    class Meta:
        model = Product 

class TransactionType(DjangoObjectType):
    class Meta:
        model = Transaction

Then we create a an abstract query ,a subclass of AbstractType .It's abstract because it's an app level query . For each app you have you need to create an app level abstract query and then combine all abstract queries with a concrete project level query .

You need to create a subclass of List members for each DjangoObjectType then create resolve_xxx() methods for each Query member

class Query(graphene.AbstractType):
    all_families = graphene.List(FamilyType)
    all_locations = graphene.List(LocationType)
    all_products = graphene.List(ProductType)
    all_transactions = graphene.List(TransactionType)

    def resolve_all_families(self, args, context, info):
        return Family.objects.all()

    def resolve_all_locations(self, args, context, info):
        return Location.objects.all()

    def resolve_all_products(self, args, context, info):
        return Product.objects.all()

    def resolve_all_transactions(self, args, context, info):
        return Transaction.objects.all()

Create project level schema.py

Next create a project level Query .

Create a project level schema.py file then add :

import graphene

import inventory.schema 


class Query(inventory.schema.Query, graphene.ObjectType):
    # This class extends all abstract apps level Queries and graphene.ObjectType
    pass

schema = graphene.Schema(query=Query)

So we first create a Query class which extends all abstract queries and also ObjectType then we create a graphene.Schema object which takes Query class as parameter .

Now we need to add a GRAPHINE config object in settings.py

GRAPHENE = {
    'SCHEMA': 'product_inventory_manager.schema.schema'
} 

Create GraphQL view

With GraphQL you don't need multiple endpoint but just one so lets create one

Open urls.py then add

from django.conf.urls import url
from django.contrib import admin

from graphene_django.views import GraphQLView

from product_inventory_manager.schema import schema

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^graphql', GraphQLView.as_view(graphiql=True)),
]

We have previously installed a GraphQL package for adding a user interface to test GraphQL queries so if you want to enable it you just set the graphiql parameter to True : graphiql=True

Serving app and testing GraphQL

Now you are ready to test the GraphQL API so start by serving your Django app :

python manage.py runserver 

Then go to localhost:8000/graphql and run some queries :

query {
allProducts {
    id
    sku
}
}   

You should get something like the following , depending on the data you have :

{
"data": {
    "allProducts": [
    {
        "id": "1",
        "sku": "Product001"
    }
    ]
}
}   

You can experiment with other models and you can also add fields but how do you know the name of the query ? It's simple just take the name of the field you create in the abstract query and transform it to camel case .

For example

all_families = graphene.List(FamilyType) => allFamilies

all_locations = graphene.List(LocationType) => allLocations

all_products = graphene.List(ProductType) => allProducts

all_transactions = graphene.List(TransactionType) => allTransactions

Then for each query specify the model fields you want to retrieve .

You can also query relationships .

Suppose we want all families with their products ,you just need to tell GraphQL what you need

query {
allFamilies {
    id
    reference 
    productSet {
        id
        sku 
    }
}
}

For my case I got :

{
"data": {
    "allFamilies": [
    {
        "id": "1",
        "reference": "FM001",
        "productSet": [
        {
            "id": "1",
            "sku": "Product001"
        }
        ]
    },
    {
        "id": "2",
        "reference": "FM001",
        "productSet": []
    }
    ]
}
}

Now what if you need the parent family and location of each product ,that's also easy doable with GraphQL :

query {
    allProducts {
        id
        sku 
        family {
            id
        }
        location {
            id
        }

    }
}

Querying for single items

We have seen how query all items but what if we need just one item by its id for example ,how can we achieve that ?

Go back to your abstract query in app schema.py file then update to be able to query for a single product

Add

product = graphene.Field(ProductType,id=graphene.Int())

Then a resolve_xxx() method

def resolve_product(self, args, context, info):
    id = args.get('id')

    if id is not None:
        return Product.objects.get(pk=id)

    return None

Now you can query for a single product by its id

query {
product(id: 1) {
    sku
    barcode
}
}

In the same way you can add support for getting single families , locations and transactions .

Conclusion


GraphQL is a very powerful technology for building Web APIs and thanks to Django Graphene you can easily add support for GraphQL to your django project .

You can find the code it this GitHub repository

23 Jun 2017 5:00am GMT

22 Jun 2017

feedDjango community aggregator: Community blog posts

Setup Git & A Github Repo

Git is a version control syste...

22 Jun 2017 10:04pm GMT

Our Tech

This is what drives our busine...

22 Jun 2017 7:36pm GMT

Building Better Django WEB APIs with GraphQL : Tutorial Part 1

Django and GraphQL

GraphQL is a new technology of building APIs created and open sourced ,in February 2015 ,by Facebook so how does it differ from the old way of building HTTP Rest APIs ?

GraphQL allows you to query your server for the exact data that you want ,no less no more ,sending just one request even for multiple related models .

So the first difference ,when using the classic Rest APIs ,in many situations you either get less data ,in this case you will need to send more requests to retrieve all data you need ,or you get more data than what you actually need ,which consumes your server and your network resources .

The second difference ,when requesting some model data from a Rest endpoint ,if you need the related models data you usually end up with more requests to multiple endpoints .

Thanks to GraphQL ,the client can describe and define exactly the requested data in a JSON format and the server takes care of sending the data in the same format .

Lets take a simple example to understand how GraphQL works .

Suppose we have a Django web application with two models ,products and families :

class Product(models.Model):

class Family(models.Model):

Each product belongs to a family thus they are related with a foreign key .

Now if you need to build a Rest API for this web app ,you will end up with multiple endpoints ,such as :

/products : To Get all products or add a product with HTTP GET and PUT methods . /families : To Get all families .

/product/:id : To Get or edit a product by its id . /family/:id : To Get or edit a family by its id .

Now lets say you want to get all products of a specified family ,you will need to add another endpoint .

Something like :

/family/:id/products where :id is the identifier of the family of products .

Now lets say that a request to endpoint /product/1 returns a serialized object ,like :

{
    id : 1 ,
    reference : 'PR001' , 
    name : 'Product 001' ,
    description : 'Description of Product 001' ,
    quantity : 1000
}

That's good but what if you need to build another front end app maybe for mobile devices ,remember that one of the purposes of WEB APIs is having multiple clients ,that needs only some of this data ,maybe it doesn't need the description attribute ,you have two options here :either add another endpoint or modify the existing endpoint but that's not practical in most situations because it is going to break other existing clients .

So as you can see ,in the case of classic Rest APIs ,the server API architecture is strongly coupled with the client implementation ,as a result if you need to change the API implementation on the server ,you'll definitely end up breaking the API clients . And if you need to add another client for your API ,which either does need less or more data served by each endpoint ,you'll have to change the server code responsible for serving the API in a way that doesn't break the existing clients ,that means conserving the old endpoints and adding new endpoints .

If you have ever developed an API with Django or any other framework then you certainly experienced one or all of these problems we have talked about above and thanks to Facebook developers ,GraphQL has the solutions for you .

So continuing with the example above ,in the case of GraphQL we can send a query which looks like :

query {  
product(id:1) {
    id
    reference
    quantity
}
}

Which is going to return something like :

{
    id : 1 ,
    reference : 'PR001' , 
    quantity : 1000
}

As you can see we have omitted two attributes without causing any problems or changing the underlying server API .

Just query the data you want and the server will be able to send it without any extra .

Now if you need to get all products of a specified family with GraphQL ,say for example for family with id = 1 , you can simply write :

query {  
family(id:1) {
    id
    products {
        id,    
        reference,
        name,
        description,
        quantity
    }
}
}

If you send this query to your GraphQL server ,you'll get something like :

{
"id":"1",
"products":[{"id":"1","reference":"PR001","name":"Product1","description":"..."} , ... ]
}    

Even if this example is fairly simple but you can see how powerful this new technology for building Web APIs is .

In the next tutorial section we are going to build a real world web application with Django and Graphene ,the Python implementation for GraphQL .

Thanks for reading and see you on the next section .

22 Jun 2017 5:00am GMT

21 Jun 2017

feedDjango community aggregator: Community blog posts

How To Exclude node_modules Directory When Running collectstatic Command in Django

If you use npm or yarn to install frontend packages inside your Django project, you may notice, that when you run python manage.py collectstatic command, it ends up collecting huge amounts of files.

That's because by default, collectstatic grabs all content of static directories inside the project, including thousands of ...

Read now

21 Jun 2017 12:06pm GMT

django-cabinet – A media library for Django

django-cabinet - A media library for Django

django-cabinet is a media library for Django implemented while trying to write as little code as possible to keep maintenance at a minimum. At the time of writing the projects consists of less than 1000 lines of code (excluding tests), but still offers hierarchical folders, downloads, images with primary point of interest (courtesy of django-versatileimagefield) and drag-drop uploading of files directly into the folder view.

You'll find more details and screenshots at Github and Read the Docs.

21 Jun 2017 10:20am GMT

20 Jun 2017

feedDjango community aggregator: Community blog posts

Making a Rails App Move Faster: A Tale of Lessons Learned

my experience, most performance improvement tasks take the following form: "This request is working too slow. We have to make it faster." Sound familiar? In general, to find and remove all mistakes and nonsense parts in the program code, the request itself and all related actions must be thoroughly examined. On this occasion, however, we had to come up with a completely different approach.

The post Making a Rails App Move Faster: A Tale of Lessons Learned appeared first on Distillery.

20 Jun 2017 7:28pm GMT

Create First Project and Start Development Server

Now that we have installed required development tools including Django framework ,it's time for the first real step to start building our real estate app while learning Django essentials from scratch .

Django framework includes a bunch of very useful utilities to create and manage projects that can be accessed from a Python file called django-admin.py that becomes available when we first installed Django .

In this section we are going to see how to :

Create a new Django project

Creating a new Django project is easy and quick so open your terminal or command prompt then enter :

$ django-admin.py startproject django_realestate

This command will take care of creating a bunch of necessary files for the project .

Executing the tree command in the root of our created project will show us the files that were created .

.
├── django_realestate
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

init is the just the Python way to mark the containing folder as a Python package which means a Django project is a Python package .

settings.py is the configuration file ,you can use this file to specify every configuration option of your project such as the installed apps , site language and database options etc .

urls.py is a special Django file which maps all your web app urls to views .

wsgi.py is necessary for starting a wsgi application server .

manage.py is another Django utility to manage the project including creating database and starting the local development server.

These are the basic files that you will find in every Django project .Now the next step is to set up and create the database .

Setting up database

Using your favorite code editor or IDE open your project settings.py file and lets configure the database .

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Django works with multiple database systems from simple to advanced systems (both open source and proprietary ) such as SQLite , MySQL ,PostgreSQL , SQL Server ,Oracle etc .Also you can switch to any database system whenever you want ,even after starting developing your web app ,without any problems thanks to Django ORM that abstracts how you can work with any database system .

For the sake of simplicity we'll be using SQLite since it comes already installed with Python so we actually have our database configuration already set up for development .Next for deployment you can use an advanced database system such as MySQL or PostgreSQL by just editing this configuration option .

Finally we need to tell Django to actually create the database and tables .Even if we didn't create actual code or data for our app yet ,Django needs to create many tables for its internal use .So lets create the database .

Creating the database and the tables is a matter of issuing this one command.

$ python manage.py migrate 

You should get an output like :

Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK

Since we are using a SQLite database you should also find a sqlite file under current directory :

.
├── db.sqlite3
├── django_realestate
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   └── wsgi.py
└── manage.py

Starting the local development server

Django has a local development server that can be used while developing your project .It's a simple and primitive server which is suitable only for development not for production .

To start the local server for your project you can simply issue the following command inside your project root directory :

$ python manage.py runserver

Performing system checks...

System check identified no issues (0 silenced).
June 20, 2017 - 20:29:22
Django version 1.11.2, using settings 'django_realestate.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Next navigate to http://localhost:8000/ with a web browser .

You should see a web page with a message :

It worked!
Congratulations on your first Django-powered page.

Next, start your first app by running python manage.py startapp [app_label].
You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!

To conclude this section lets summarize what we have done throughout this tutorial . We have created a new Django project ,created and migrated a SQLite database and started a local development server .

In the next tutorial we are going to start creating our real estate prototype .

20 Jun 2017 5:00am GMT

19 Jun 2017

feedDjango community aggregator: Community blog posts

Encodings — part 1

Has a UnicodeEncodeError ever got on your nerves? I think it has happened to pretty much everyone. I thought it's a good time to start demystifying this mystery, and to have fun while doing it.

You are probably familiar with the famous hello program, which does nothing but print "Hello, world!" Now we are going to create the bon program, which prints "Bon appétit!" Here it is, but don't type it in or copy/paste it:

import sys

sys.stdout.write("Bon appétit!\n")

We could have written it with a single print statement, but for several reasons I prefer this version.

Now, I told you to not type in this program or copy/paste it. Instead, we are going to create it by writing down the bytes that comprise it. The file bon.py, like any file, is a series of bytes. These bytes represent the characters in the file. The first character is "i", which is represented by the byte 105; the second one is "m", represented by 109; and so on. You can find the table for all characters (except é) at Wikipedia.

In order to create the file, we will use another Python program. Here it is. You can copy and paste that one; name it createbon.py:

byte_values = [
    # i   m    p    o    r    t        s    y    s
    105, 109, 112, 111, 114, 116, 32, 115, 121, 115, 13, 10,

    13, 10,

    # s   y    s   .    s    t    d    o    u    t   .
    115, 121, 115, 46, 115, 116, 100, 111, 117, 116, 46,

    # w   r    i    t    e   (   "   B    o    n
    119, 114, 105, 116, 101, 40, 34, 66, 111, 110, 32,

    # a  p    p   +------+   t    i    t    !  \    n   "   )
    97, 112, 112, 195, 169, 116, 105, 116, 33, 92, 110, 34, 41, 13, 10,
]

with open('bon.py', 'wb') as f:
    f.write(bytearray(byte_values))

Type python createbon.py and it will create bon.py. Don't try to run it yet; instead, open bon.py in a UTF-8 editor to see it. By default, on GNU/Linux systems any editor should work properly. On Windows I experimented with Notepad and it worked, but you might need to tell it it's UTF-8.

You may have noticed that 32 is the space, and that I'm using the sequence 13 10 for a new line. 13 stands for "carriage return", and 10 for "line feed". On Windows both characters are needed to change line, whereas in Unixes only line feed is used. Here I used the Windows version. Python programs in GNU/Linux will rarely use 13 10 as the newline, they will normally use only 10, but if it happens that a file uses 13 10 it will work without problem.

Running bon.py is a different story. First of all, you can only run it in Python 3. Python 3 assumes that the encoding of the input file is UTF-8, which it is.

If you try to run bon.py with Python 3 on GNU/Linux, most likely it will work; however, on several environments, it might not work and instead give you a UnicodeEncodeError:

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 7: ordinal not in range(128)

Whether it succeeds or not, here is what happens: Python reads bon.py. When it reaches the "Bon appétit!\n" part, it reads the bytes and decodes them into a string of characters. Python assumes these bytes are the string encoded in UTF-8, which it is, so it is able to decode these bytes into an internal representation of the string.

When the time comes to print the string to the standard output, Python must convert the string from the internal representation to an encoding that will be understood by the terminal inside which Python is being run. The way Python determines that encoding depends on the system on which it is running.

Let's see some examples only for the word "appétit". If the terminal uses UTF-8, the bytes produced by the encoding will be 97, 112, 112, 195, 169, 116, 105, 116 (I've bolded é just to make it easier for you to read the whole sequence). If it uses ISO-8859-1, the bytes will be 97, 112, 112, 233, 116, 105, 116. If it uses UTF-16, the bytes will be 97, 0, 112, 0, 112, 0, 233, 0, 116, 0, 105, 0, 116, 0. In all cases, Python will throw these bytes to the terminal, and the terminal will decode them into its internal representation, and in co-operation with the operating system and the windowing system it will paint the corresponding glyphs on the screen.

If the terminal uses ASCII, Python will attempt to encode the string into ASCII. In addition, if the encoding used by the terminal is unknown to Python, Python will also use ASCII. But é cannot be encoded into ASCII, because the ASCII character set does not contain that character, so Python will throw the UnicodeEncodeError.

Python 2

While it is also a valid Python 2 program, Python 2 assumes that the encoding of the input file is ASCII, and in ASCII all bytes are a number between 0 and 127, and here we have two bytes that are more than 127-it's the two bytes that represent é, 195 and 169. So Python 2 will stop and complain ("SyntaxError: Non-ASCII character '\xc3' in file /tmp/bon.py on line 3, but no encoding declared").

You can also convince Python 2 by adding a comment on top of the file that tells Python that the encoding of the file is UTF-8, but we will not bother with that here; read PEP 263 if you are interested in that.

(Python 3 always works with UTF-8, whereas Python 2 needs a PEP 263 comment, and if you use one it should always be UTF-8; don't use anything else, otherwise you will be in trouble when porting your code to Python 3).

The post Encodings - part 1 appeared first on Django deployment.

19 Jun 2017 4:34pm GMT

Why Your Dockerized Application Isn’t Receiving Signals

Proper cleanup when terminating your application isn't less important when it's running inside of a Docker container. Although it only comes down to making sure signals reach your application and handling them, there's a bunch of things that can go wrong.

19 Jun 2017 5:00am GMT

Learn Django From Scratch By Building A Real Estate Web Application

Learn Django From Scratch

Throughout this beginner's tutorial we are going to learn how to build web applications with Python and Django framework .This tutorial assumes no prior experience with Django so we will be covering the the basic concepts and elements of Django by emphasizing essential theory with practice .Basically we are going to learn Django fundamental concepts while building a real world real estate web application starting from the idea to database design to full project implementation and deployment .

This tutorial doesn't only cover fundamental basics of Django but also advanced concepts such as how to use and integrate Django with modern front end frameworks like Angular 2+ and React .

19 Jun 2017 5:00am GMT

Introduction to Django Framework

Django is an open source Python based web framework for building web applications quickly and effortlessely .It's a pragmatic framework designed for developers working on projects with dead lines .It's perfect for quickly creating prototypes and then continue building them after clients approval .

Django uses Python language , a general purpose ,powerful , feature rich programming language ,and follows a Model View Controller (MVC) design pattern .But what is MVC ?

What is MVC ?

MVC is a software architectural design pattern which encourages separation of concerns and seamless cooperation between designers and developers when working on the same project .It basically divides or separates your app into three parts : The Model , the View and the Controller .

The Model is responsible for data storage and management .

The View is responsible of representing and rendering the user interface or view .

The Controller is responsible for handling logic to control the user interface and work with data model.

Thanks to MVC you as a developers can work with controller to handle model data without being concerned about the user interface which is left to designers so if anything changes on the side of designers on the user interface you can rest assured that will not affect you code and vice versa.

What is Python ?

Python is a general purpose programing language that's suitable for developing all kind of applications including web apps .Python is known by a clean syntax and a large standard library which contains a wide range of modules that can be used by developers to build their applications instead of reinventing the wheel .

Python is an Object Oriented Language just like Java . Also like Java ,Python is an interpreted language that runs on top of its own virtual machine which makes it a portable language that can runs across every machine and operating system such as Linux ,Windows and MAC .

Python is especially popular among the scientific community where it's used for creating numeric applications .

Python is also known by the great performance of its runtime environment which makes it a good alternative to PHP for developing web applications .

For more information you can head to http://python.org/ where you can also download Python binaries for supported systems .

For Linux and MAC Python is included by default so you don't have to install .For Windows just head over to the official Python website and grab your installer .Just like any normal Windows program ,the installation process is easy and straightforward .

Why using Django ?

Due to its popularity and large community ,Python has numerous web frameworks among them Django so what makes Django the right choice for you or your next project ?

Django is a batteries included framework

Django includes a set of batteries that can be used to solve common web problems without reinventing the wheels such as the sites framework ,the Auth system ,forms generation ,an ORM for abstracting database systems and a a very powerful templating engine ,caching system ,RSS generation framework etc.

Django ORM

Django has a powerful ORM or Object Relational Mapper which allows developers to use Python OOP classes and methods instead of SQL tables and queries to work with SQL based databases .Thanks to Django ORM ,developers can work wit any database system such as MySQL or PostgresSQL without knowing anything about SQL .In the same time the ORM doesn't get in the way ,you can write custom SQL anytime you want especially if you need to optimize the queries against your server database for increased performance .

Support for internationalization : i18n

You can use Django for writing web applications for other languages than English with a lot of ease thanks to its powerful support for internationalization or you can also create multi lingual websites

The Admin interface or back office

Django is a very suitable framework for quickly building prototypes thanks to its auto-generated admin interface .

You can generate a full fledged admin application that can be used to do all sorts of CRUD operations against your database models that you have registered with the Admin module using one line of code.

Community and extensive documentation

Django has a great community that has contributed all sorts of awesome things to Django from tutorials and books to reusable open source packages that extend the core framework to include solutions for even more web development problems without reinventing the wheel or wasting time implementing what other developers have already created .

Django has also one of the most extensive and useful documentation on the web which can gets you up and running with Django in no time .

As a conclusion ,if you are looking for a web framework full of features that makes building web applications fun and easy and that has all what you can expect from a modern framework that Django is the right choice for you if you are a Python developer .

19 Jun 2017 5:00am GMT

Introduction to Django Framework

Django is an open source Python based web framework for building web applications quickly and effortlessely .It's a pragmatic framework designed for developers working on projects with dead lines .It's perfect for quickly creating prototypes and then continue building them after clients approval .

Django uses Python language , a general purpose ,powerful , feature rich programming language ,and follows a Model View Controller (MVC) design pattern .But what is MVC ?

What is MVC ?

MVC is a software architectural design pattern which encourages separation of concerns and seamless cooperation between designers and developers when working on the same project .It basically divides or separates your app into three parts : The Model , the View and the Controller .

The Model is responsible for data storage and management .

The View is responsible of representing and rendering the user interface or view .

The Controller is responsible for handling logic to control the user interface and work with data model.

Thanks to MVC you as a developers can work with controller to handle model data without being concerned about the user interface which is left to designers so if anything changes on the side of designers on the user interface you can rest assured that will not affect you code and vice versa.

What is Python ?

Python is a general purpose programing language that's suitable for developing all kind of applications including web apps .Python is known by a clean syntax and a large standard library which contains a wide range of modules that can be used by developers to build their applications instead of reinventing the wheel .

Python is an Object Oriented Language just like Java . Also like Java ,Python is an interpreted language that runs on top of its own virtual machine which makes it a portable language that can runs across every machine and operating system such as Linux ,Windows and MAC .

Python is especially popular among the scientific community where it's used for creating numeric applications .

Python is also known by the great performance of its runtime environment which makes it a good alternative to PHP for developing web applications .

For more information you can head to http://python.org/ where you can also download Python binaries for supported systems .

For Linux and MAC Python is included by default so you don't have to install .For Windows just head over to the official Python website and grab your installer .Just like any normal Windows program ,the installation process is easy and straightforward .

Why using Django ?

Due to its popularity and large community ,Python has numerous web frameworks among them Django so what makes Django the right choice for you or your next project ?

Django is a batteries included framework

Django includes a set of batteries that can be used to solve common web problems without reinventing the wheels such as the sites framework ,the Auth system ,forms generation ,an ORM for abstracting database systems and a a very powerful templating engine ,caching system ,RSS generation framework etc.

Django ORM

Django has a powerful ORM or Object Relational Mapper which allows developers to use Python OOP classes and methods instead of SQL tables and queries to work with SQL based databases .Thanks to Django ORM ,developers can work wit any database system such as MySQL or PostgresSQL without knowing anything about SQL .In the same time the ORM doesn't get in the way ,you can write custom SQL anytime you want especially if you need to optimize the queries against your server database for increased performance .

Support for internationalization : i18n

You can use Django for writing web applications for other languages than English with a lot of ease thanks to its powerful support for internationalization or you can also create multi lingual websites

The Admin interface or back office

Django is a very suitable framework for quickly building prototypes thanks to its auto-generated admin interface .

You can generate a full fledged admin application that can be used to do all sorts of CRUD operations against your database models that you have registered with the Admin module using one line of code.

Community and extensive documentation

Django has a great community that has contributed all sorts of awesome things to Django from tutorials and books to reusable open source packages that extend the core framework to include solutions for even more web development problems without reinventing the wheel or wasting time implementing what other developers have already created .

Django has also one of the most extensive and useful documentation on the web which can gets you up and running with Django in no time .

As a conclusion ,if you are looking for a web framework full of features that makes building web applications fun and easy and that has all what you can expect from a modern framework that Django is the right choice for you if you are a Python developer .

19 Jun 2017 5:00am GMT

Installing Development Environment On Windows ,Linux and MAC

Python is a portable programming language that can be used anywhere its runtime environment is installed .

Django is a Python framework which can be installed on any system which supports Python language .

In this tutorial part we are going to see how to install Python and Django on major available operating systems i.e Windows , Linux and MAC .

Installing Python

Depending on your operating system you may need or may not need to install Python .In Linux and MAC OS Python is included by default ,you may only need to update it if the installed version is outdated .

Installing Python On Windows

Python is not installed by default on Windows so you'll need to grab the official installer from the official Python website at http://www.python.org/download/ . Launch the installer and follow the wizard to install Python just like any other Windows program .

Also make sure to add Python root folder to system path environment variable so you can execute the Python executable from any directory using the command prompt .

Next open a command prompt and type python .You should be presented with a Python Interactive Shell printing the current version of Python and prompting you to enter your Python commands (Python is an interpreted language )

Installing Python On Linux

If you are using a Linux system ,there is a great chance that you already have Python installed but you may have an old version .In this case you can every easily install it via your terminal depending on your Linux distribution .

For Debian based distributions like Ubuntu you can use apt package manager

sudo apt-get install python

This will update your Python version to the latest available version .

For other Linux distributions you should look for equivalent commands to install or update Python which is not a daunting task if you already use a package manager to install packages for your system then you should follow the same process to install or update Python .

Installing Python on MAC OS

Just like Linux , Python is included by default on MAC but in case you have an old version you should be able to update it by going to http://www.python.org/download/mac/ and grab a Python installer for MAC .

Now if you managed to install or update Python on your own system or in case you have verified that you already have an updated version of Python installed on your system let is continue by installing Django .

Installing PIP

PIP is a Python package manager which is used to install Python packages from Python Package Index which more advanced that easy_install the default Python package manager that's installed by default when you install Python .

You should use PIP instaed of easyinstall whenever you can but for installing PIP itself you should use easyinstall .So lets first install PIP :

Open your terminal and enter :

$ sudo easy_install pip

You can now install Django on your system using pip

$ sudo pip install django

While you can do this to install Django ,globally on your system ,it's strongly not recommend ,instead you need to use a virtual environement to install packages.

virtualenv

virtualenv is a tool that allows you to work with multiple Python projects with different or the same ( often different and conflicting versions ) requirements , on the same system without any problems by creating multiple and isolated virtual environments for Python packages .

Now lets first install virtualenv using pip :

sudo pip install virtualenv      

Or you can install virtualenv before even installing pip from its official website .

In this case you don't need to install pip because it comes installed with virtualenv and gets copied into any virtual environment you create .

Creating a virtual environment

After installing virtualenv you can now create your first virtual environment using your terminal :

$ cd ~/where-ever-you-want 
$ virtualenv env 

New python executable in env/bin/python
Installing setuptools............done.
Installing pip...............done.

Next you should activate your virtual environment :

source env/bin/activate 

Now you can install any Python package using pip inside your created virtual environment .

Lets install Django !

Installing Django

After creating a new virtual environment and activating it ,it is time to install Django using pip

$ pip install django 

Rest assured that Django is only installed on the activated virtual environment not globally .

As a conclusion lets summarize what we have done .We first installed Python depending on the operating system ,we then installed pip and virtualenv to install packages from PyPI and create isolated virtual environments for multiple Python projects and finally created a virtual environment and installed Django inside this virtual env .

19 Jun 2017 5:00am GMT

Installing Development Environment On Windows ,Linux and MAC

Python is a portable programming language that can be used anywhere its runtime environment is installed .

Django is a Python framework which can be installed on any system which supports Python language .

In this tutorial part we are going to see how to install Python and Django on major available operating systems i.e Windows , Linux and MAC .

Installing Python

Depending on your operating system you may need or may not need to install Python .In Linux and MAC OS Python is included by default ,you may only need to update it if the installed version is outdated .

Installing Python On Windows

Python is not installed by default on Windows so you'll need to grab the official installer from the official Python website at http://www.python.org/download/ . Launch the installer and follow the wizard to install Python just like any other Windows program .

Also make sure to add Python root folder to system path environment variable so you can execute the Python executable from any directory using the command prompt .

Next open a command prompt and type python .You should be presented with a Python Interactive Shell printing the current version of Python and prompting you to enter your Python commands (Python is an interpreted language )

Installing Python On Linux

If you are using a Linux system ,there is a great chance that you already have Python installed but you may have an old version .In this case you can every easily install it via your terminal depending on your Linux distribution .

For Debian based distributions like Ubuntu you can use apt package manager

sudo apt-get install python

This will update your Python version to the latest available version .

For other Linux distributions you should look for equivalent commands to install or update Python which is not a daunting task if you already use a package manager to install packages for your system then you should follow the same process to install or update Python .

Installing Python on MAC OS

Just like Linux , Python is included by default on MAC but in case you have an old version you should be able to update it by going to http://www.python.org/download/mac/ and grab a Python installer for MAC .

Now if you managed to install or update Python on your own system or in case you have verified that you already have an updated version of Python installed on your system let is continue by installing Django .

Installing PIP

PIP is a Python package manager which is used to install Python packages from Python Package Index which more advanced that easy_install the default Python package manager that's installed by default when you install Python .

You should use PIP instaed of easyinstall whenever you can but for installing PIP itself you should use easyinstall .So lets first install PIP :

Open your terminal and enter :

$ sudo easy_install pip

You can now install Django on your system using pip

$ sudo pip install django

While you can do this to install Django ,globally on your system ,it's strongly not recommend ,instead you need to use a virtual environement to install packages.

virtualenv

virtualenv is a tool that allows you to work with multiple Python projects with different or the same ( often different and conflicting versions ) requirements , on the same system without any problems by creating multiple and isolated virtual environments for Python packages .

Now lets first install virtualenv using pip :

sudo pip install virtualenv      

Or you can install virtualenv before even installing pip from its official website .

In this case you don't need to install pip because it comes installed with virtualenv and gets copied into any virtual environment you create .

Creating a virtual environment

After installing virtualenv you can now create your first virtual environment using your terminal :

$ cd ~/where-ever-you-want 
$ virtualenv env 

New python executable in env/bin/python
Installing setuptools............done.
Installing pip...............done.

Next you should activate your virtual environment :

source env/bin/activate 

Now you can install any Python package using pip inside your created virtual environment .

Lets install Django !

Installing Django

After creating a new virtual environment and activating it ,it is time to install Django using pip

$ pip install django 

Rest assured that Django is only installed on the activated virtual environment not globally .

As a conclusion lets summarize what we have done .We first installed Python depending on the operating system ,we then installed pip and virtualenv to install packages from PyPI and create isolated virtual environments for multiple Python projects and finally created a virtual environment and installed Django inside this virtual env .

19 Jun 2017 5:00am GMT