Sunday 21 July 2019

Django Docker Installation

This blog is to explain Django  Docker installation. Docker is a software platform to create, deploy and manage virtualized application containers on a common operating system, with an ecosystem of allied tools.

First follow these steps to install Docker in Ubuntu.

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

sudo apt-get update

sudo apt-get install -y docker-ce


Next, install Docker Compose by running these
sudo curl -L https://github.com/docker/compose/releases/download/1.18.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose

sudo chmod +x /usr/local/bin/docker-compose


Next we are going to install Django in Docker.

Create a directory named docker_first somewhere in your home directory.
Create a file named Dockerfile in it. Add the following lines to it and save.
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/



Create a file named requirements.txt in the same location. Add the following lines into it.
Django>=2.0,<3.0
psycopg2>=2.7,<3.0


Create another file named docker-compose.yml
Add the following code into it
version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db



Next, create a Django project by run this
sudo docker-compose run web django-admin startproject composeexample .


Run this command to change the file permissions
sudo chown -R $USER:$USER .


Edit the composeexample/settings.py file. Copy following lines in place of DATABASES
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}


Add 'localhost' in ALLOWED_HOSTS in the same settings.py. It will look like this
ALLOWED_HOSTS = ['localhost']


Run the following command in the docker_first directory
sudo docker-compose up


Now open http://localhost:8000 to check the installation. Thank you

Watch the video tutorial here (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw 




Sunday 16 September 2018

Load initial data into Django model

This article explains pre-populating or seeding the core tables in django with initial data. It may be helpful to insert tables like status,employee types automatically while port source code from one place to another. Example situations like copy code from development server to production server. You can provide this  initial data with migrations or fixtures.

Here I am explaining about load data using fixtures. A fixture is a collection of data that Django knows how to import into a database. Fixtures can be written as JSON, XML or YAML formats. This tutorial is based on JSON fixture. This tutorial is writing in django 2 but it works fine with django 1.11 also. I am using Ubuntu 16.

These are the steps ,first create a file named fixtures.json then write the data in json format, then run the command to write this data into database.

First, we need a django project. For that, create a directory named my_proj somewhere in your home directory. Open that folder, then open a terminal window in that location. Then run these commands to install Django.

virtualenv -p python3 env
source env/bin/activate
pip install Django


Then create a project named my_proj and app named my_app by run following commands

django-admin startproject my_proj .
django-admin startapp my_app


For detailed tutorial about installing Django locally, then create a project go to this link:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

Open my_proj/my_proj/settings.py then add  'my_app' to the INSTALLED_APPS section. Now it will look like this

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


The project is configured now. We need to create two sample models named Status and Employee_type.
For this add the following code in my_proj/my_proj/my_app/models.py

class Status(models.Model):
    name = models.CharField(max_length=200)
    meta_name = models.CharField(max_length=200)

    class Meta:
    db_table = 'status'



class Employee_type(models.Model):
    name = models.CharField(max_length=200)
    meta_name = models.CharField(max_length=200)

    class Meta:
    db_table = 'employee_type'


Run these commands to create the actual tables in the database.
python manage.py makemigrations
python manage.py migrate


Create a directory named fixtures in my_proj/my_proj/my_app directory. Then create a file named fixtures.json inside this directory.
Open this file and paste the following code in it


[
  {
    "model": "my_app.Status",
    "pk": 1,
    "fields": {
      "name": "Pending",
      "meta_name": "pending"
    }
  },
  {
    "model": "my_app.Status",
    "pk": 2,
    "fields": {
      "name": "Approved",
      "meta_name": "approved"
    }
  },
  {
    "model": "my_app.Status",
    "pk": 3,
    "fields": {
      "name": "Rejected",
      "meta_name": "rejected"
    }
  },


  {
    "model": "my_app.Employee_type",
    "pk": 1,
    "fields": {
      "name": "Admin",
      "meta_name": "admin"
    }
  },
  {
    "model": "my_app.Employee_type",
    "pk": 2,
    "fields": {
      "name": "Staff",
      "meta_name": "staff"
    }
  }
]



Look into the json data each element contains three fields named model,pk,fields. As the name says they are the model name, id of table row and fields of the table row respectively. In the model field the my_app represents the app name Status,Employee_type are the models.

Our fixture is ready now. Run this command to insert this fixture to the tables we created earlier
python manage.py loaddata fixtures.json


Here we are using sqlite db so open db.sqlite3 file in my_proj directory using a sqlite browser software.
Check the status and employee_type tables. The values provided in the fixtures.json is inserted into the tables.

You can download the example source code from here:-
https://dl.dropboxusercontent.com/s/dhrqxgkjuzlwze6/my_proj.zip

Watch the video tutorial here (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw 

Thursday 2 August 2018

Django jwt authentication example with angular 5

When thinking about token authentication for our rest apis first think coming to our mind is JWT. JSON Web Token or JWT is a JSON-based open standard for creating access tokens that can use for purposes like rest api authentication.

This article contains a django application structure with jwt authentication, angular 5 and bootstrap 4 in front end.  This example uses django rest framework to create rest apis, and django-rest-framework-jwt for jwt authentication.

This example uses renowned professional angular 5 admin template SB admin. So it can be used as a starting point for your small or big scale projects. This example app will work fine with both Django 2 and 1.11 versions. I am using Ubuntu 16 for creating this example.

You can download the source code from this link:-
https://dl.dropboxusercontent.com/s/bd7bv2agd8y04q2/admin_proj.zip

Follow these steps to configure the example.
Download and extract the project. Then open a terminal window in the root directory of the project.

First, we need to create a virtual environment to run our project

For Django 1.11 run this command
virtualenv env


For Django 2 run this command
virtualenv -p python3 env


Then run the following command to activate the virtual environment
source env/bin/activate


Read this article for detailed description about creating virtual enviornments:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

After that install django and related packages by run these commands

For Django 1.11
pip install certifi==2018.4.16
pip install Django==1.11
pip install django-cors-headers==2.4.0
pip install djangorestframework==3.8.2
pip install djangorestframework-jwt==1.11.0
pip install PyJWT==1.6.4
pip install pytz==2018.5


For Django 2
pip install certifi==2018.4.16
pip install Django==2.0.7
pip install  django-cors-headers==2.3.0
pip install djangorestframework==3.8.2
pip install djangorestframework-jwt==1.11.0
pip install PyJWT==1.6.4
pip install pytz==2018.5


Then run these to migrate database
python manage.py makemigrations
python manage.py migrate


Run this command to start django development server
python manage.py runserver


Make sure that the django development server is running at 8000 port.
Our backend is configured now.

Now open front_end directory in the project folder
open a terminal in that directory then run
npm install

Have any problems while install packages then use sudo

After all packages installed run
ng serve


Now the front end is available at http:127.0.0.1:4200
Open this in any browser. Click the register button, then create a user.
You can see the dashboard. Now start to add your custom functionalities.

Watch the video tutorial here (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw



Saturday 23 June 2018

Integrate bootstrap template in Django 2

This article explains how to integrate a bootstrap  template in Django. I am using renowned bootstrap admin template SBAdmin in this tutorial.This tutorial is written in Ubuntu 16.04.

Watch the demo here:- (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw



A bootstrap theme may have many dependencies like bootstrap library, jquery and other javascript plugins and css files.
So integrate these all to a Django project is something tricky.

We need to load the dependent libraries as static files. Then create parent templates for admin pages and normal pages. Copy body sections of each page in the template, then paste it into equivalent pages in our project. Then set view functions and urls correctly. I am explaining all these steps in this tutorial.
To download the full source file go to end of the tutorial.

First, create a directory named admin_proj somewhere in your home directory. Open that folder, then open a terminal window in that location. Then run these commands to install Django.

virtualenv -p python3 env
source env/bin/activate
pip install Django

Then create a project named admin_proj and app named admin_app by run following commands

django-admin startproject admin_proj .
django-admin startapp admin_app

For detailed tutorial about installing Django locally, then create a project go to this link:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

Open admin_proj/admin_proj/settings.py then add  'admin_app' to the INSTALLED_APPS section.

Next open admin_proj/admin_proj/urls.py.
Add an include keyword in the line from django.urls import path

Now it will look like
from django.urls import path,include

Add this line in the urlpatterns section
path('admin_app/', include('admin_app.urls'))


Now download SBAdmin 2 template files from this link, https://github.com/BlackrockDigital/startbootstrap-sb-admin-2/archive/gh-pages.zip
Then extract the zip file.

It is the time to load these template files to our Django project as static files.
For this check following line is included in the INSTALLED_APPS section of admin_proj/admin_proj/settings.py
'django.contrib.staticfiles'

Then check this line is exist in the same settings.py file
STATIC_URL = '/static/'

Go to this link, for the detailed tutorial about load static files: -  http://newprograminglogics.blogspot.com/2018/03/load-static-files-in-django-20.html

Then create a folder named static in admin_app folder.
Create a folder named admin_app inside it. Then copy vendor,dist,data directories from the extracted SBAdmin directory to admin_proj/admin_app/static/admin_app directory.
Now the static directory will look like this
├── migrations
├── static
│   └── admin_app
│       ├── data
│       ├── dist
│       └── vendor

All js and css files are now in correct location. Now we can create some templates to display.

In the admin_app folder, create a folder named templates Create another folder named admin_app in it. I am going to create two base templates. One for admin pages with sidebar and header and another for login and regular pages without sidebar and header. Create a file named admin.html

Now the templates directory will look like this

├── migrations
├── static
├── templates
│   └── admin_app
│       ├── admin.html


Open index.html in pages directory of downloaded SBAdmin theme. Copy and paste the contents to admin.html. Delete the content inside the div with id "page-wrapper".

Now add the code inside "page-wrapper" div.
{% block content %}{% endblock %}


Our admin template is ready now. Now we can create a child html file to consume  this template.
Create a file named dashboard.html in the same location of admin.html. Once again open index.html in pages directory of downloaded SBAdmin theme. Copy the content inside "page-wrapper" div and paste to dashboard.html

Then add these line in top of the same file.
{% extends "admin_app/admin.html" %}
{% block content %}


Add this code at the bottom of the file
{% endblock %}

Now we are going to change the source url of script files.
../vendor/jquery/jquery.min.js should change to
{% static 'admin_app/vendor/jquery/jquery.min.js' %}


Similarly ../data/morris-data.js should change to
{% static 'admin_app/data/morris-data.js' %}


Do this for all js files and css files. You should add this line in the top of the file
{% load static %}


Copy all scripts into <head> section. Keep only common scripts and css like jquery.js and bootstrap.js in admin.html. Move other scripts like morris-data.js into dashboard.html. Because it is only needed on the dashboard page.

Add the same code at the top of dashboard.html also
{% load static %}


Then change the sidebar menu urls like this {% url 'admin_app:index' %} in admin.html.
This will create a url to localhost:8000/admin_app .We hadn't created any urls yet, but we will create it later.


Now we have created an admin.html template and a file named dashboard.html which consume the admin.html.
In the same way you can create equivalent pages for every page in the downloaded theme like buttons.html,forms.html, flot.html, gridhtml,icons.html etc.

In the same manner create another template named front_end.html and page named login.html from login.html page of downloaded theme.


Open admin_proj/admin_app/views.py. Then add this code
def index(request):
    return render(request, 'admin_app/dashboard.html')


This means the view function named index return the contents of dashboard.html. Similarly create functions for all other pages we created earlier.

Now create a file named urls.py in the same location of views.py, then add these code
from django.urls import path

from . import views

app_name = 'admin_app'
urlpatterns = [
    path('', views.index, name='index')
]


In this code path('', views.index, name='index') means that call to root url should call the index function in views.py.
Similarly, connect all views functions to equivalent urls.

Done we have successfully integrated a bootstrap template to Django. Now run python manage.py runserver, the open http:localhost:8000/admin_app in any browser.

If you don't have time to execute all the steps mentioned  above you can buy the example source  code from here:-  https://payhip.com/b/I3sTL

After download completed, extract the folder to somewhere on your computer, then open a terminal window inside the extracted project directory. Then run the following commands
virtualenv -p python3 env

source env/bin/activate

pip install django

python manage.py runserver


Then open http://127.0.0.1:8000/admin_app in any browser.


Tuesday 1 May 2018

Django chat application

This article is about how to create a chat application or chat server using Django 2.0. This chat system depends Python 3 and Django restframework to create rest apis. Jquery ajax is using to call the api from the client side. I am using Ubuntu 16.04 to create this tutorial.

You can download the example source code from here:- https://dl.dropboxusercontent.com/s/obt4u4udlt30k8w/chatproj.zip

After download completed, extract the folder to somewhere on your computer, then open a terminal window inside the extracted project directory. Then run the following commands to create a virtual environment and activate.

virtualenv -p python3 env

source env/bin/activate


For complete details about create a virtual environment read this article:- http://newprograminglogics.blogspot.com/2018/02/install-python-3-and-set-up-local.html

Then install Django by run this command
pip install django


Then install Django rest framework
pip install djangorestframework


Then run these commands to create migrations
python manage.py makemigrations chatapp

python manage.py migrate


All configurations completed. Now start the server using this command
python manage.py runserver


To check the functionality open http://127.0.0.1:8000/index in any browser
For reduce complexity I am not using a user login. You can simply login to chat by using your name or nickname without any log up process.

Enter your name like John , Peter in the From text box. Open the same url http://127.0.0.1:8000/index in another tab, type another name in it.
You can see the online users in the right column. Click one of the Names, you can see a chat box is opened. You can write messages in it and send to the selected user.

Watch the video tutorial (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw



Tuesday 6 March 2018

Load static files in django 2.0

This article is about how to serve static files in Django 2.0. Static files means javascript libraries like jquery, css files or images.
Jquery is an essential part of modern web development. When we use the templating system of django we need to do some steps to include jquery to it.
Sometimes you may try to access the static files by some methods it may not work properly and ends up in a 404 error.

I am explaining the process with an example application. This example includes a button. When click in it it will show an image.

This tutorial assumes that you have created a virual enviorment and django 2 project with mysite and app with myapp were created.
To read about how to create a virtual enviornment and install django go this link:- Install Python 3 and Set Up a Local Programming Environment

Open mysite/mysite/settings.py. Paste following line in the INSTALLED_APPS section
'myapp.apps.MyappConfig'


Then check following line is included in the INSTALLED_APPS section
'django.contrib.staticfiles'


Then check this line is exist in the same settings.py file
STATIC_URL = '/static/'


Then create a folder named static in myapp folder.
Create a folder named myapp inside it.
Download jquery and an image in this folder.

Then in the myapp folder create a folder named templates
Create another folder named myapp in it
Then create a file named index.html in it
Then paste the following code in it
{% load static %}
<!DOCTYPE html>
<html>
<body>
<img width="400px" height="300px" style="display:none;" id="img" src="{% static 'myapp/flower.jpg' %}"/>
<br/>
<input type="button" value="Show Image" id="btn"/>
<script src="{% static 'myapp/jquery-3.3.1.min.js' %}"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
        $('#img').show();
});
});
</script>
</body>
</html>

Don't forget to add the line  {% load static %} in the top of the page.
In this code {% static 'myapp/flower.jpg' %} flower.jpg can replace with the image you downloaded in the static folder.
Also in {% static 'myapp/jquery-3.3.1.min.js' %} jquery-3.3.1.min.js can replace with your jquery version.

Open the file myapp/views.py
Paste the following code in it
def index(request):
    return render(request, 'myapp/index.html')


Create a file named urls.py in myapp folder
Then paste the following code in it
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index')
]


Next open Open mysite/mysite/urls.py.
Add an include keyword in the line
from django.urls import path

Now it will look like
from django.urls import path,include


Add this line in the urlpatterns section
path('myapp/', include('myapp.urls'))


Then run the command in mysite folder
python manage.py runserver

Note that you must restart the development server in order to access static files.
Now open the url http://127.0.0.1:8000/myapp in any browser.It will show a button saying Show Image. Click it will show the image.

Watch the video tutorial (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw



You can download the example app from here: https://dl.dropboxusercontent.com/s/zjssc3xgpzmxqnd/mysite.zip

Sunday 11 February 2018

Install Python 3 and Set Up a Local Programming Environment then install Django locally on Ubuntu 16.04

This article is about installing python 3 virtual environment on Ubuntu 16.04. If you are looking to set up a python 3 development environment, this  tutorial will help you.

First install python 3 by run these commands in the terminal
sudo apt-get install python3.5

Then install pip3 the python package manager by running
sudo apt-get install python3-pip

Then install virtualenv package
sudo pip3 install virtualenv

Then create a directory named my_proj which is our project name in your home directory. Then open a terminal window in that directory. Run the following command to create a virtual environment
virtualenv -p python3 env

Then run this command to activate the virtual environment
source env/bin/activate

Our virtual environment is activated now. To check it run
which python3

It will give the result    /home/sukesh/sukesh/python/my_proj/env/bin/python3

To install Django 2 run this
pip install Django

Note that pip, and python commands can be used in our virtual environment instead of pip3 and python3.

 Run this to check django
python -m django --version

It will give result   2.0.5

Create a sample project by run this. Don't forget the trailing dot(.)
django-admin startproject my_proj .

Our project is created now. Run this to create an app
django-admin startapp my_app

Now we need to add the created app to our project. For that open my_proj/my_proj/settings.py, then add 'my_app' to the INSTALLED_APPS section. Our INSTALLED_APPS will looks like this
INSTALLED_APPS = [
         'django.contrib.admin',
         'django.contrib.auth',
         'django.contrib.contenttypes',
         'django.contrib.sessions',
         'django.contrib.messages',
         'django.contrib.staticfiles',
         'my_app'
]


You have finished. To start the development server run
python manage.py runserver

Our server has started now. To check this open this url in any browser:-  http://127.0.0.1:8000

Watch this video tutorial (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)

Thank You

Search This Blog