BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

5. Django 1.8 Server Build - CentOS 7 hosted on VPS - Install and Configure Django

django.png




Bookmark and Share





bogotobogo.com site search:




Django 1.8 server on VPS Tutorials
  1. Django 1.8 Server Build - CentOS 7 hosted on VPS
  2. Django 1.8 Server Build - CentOS 7 hosted on VPS - ssh login and firewall
  3. Django 1.8 Server Build - CentOS 7 hosted on VPS - Apache Install
  4. Django 1.8 Server Build - CentOS 7 hosted on VPS - Install and Configure MariaDB Database server & PHP

In this chapter, we'll install and configure Django.





install mod_wsgi

mod_wsgi is an Apache module which can host any Python WSGI application, including Django. Django will work with any version of Apache which supports mod_wsgi.

The purpose of mod_wsgi is to implement a simple to use Apache module which can host any Python application which supports the Python WSGI interface (How to use Django with Apache and mod_wsgi).

Let's check current Python version:

$ python
Python 2.7.5 (default, Jun 17 2014, 18:11:42)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

The WSGI specification provides a standard and efficient method for dynamic web applications to communicate with web servers. The recommended way to serve Python applications using Apache is to use mod_wsgi module.

It is not installed by default with neither Python nor Apache, so we have to install an additional package.

mod_wsgi provides a method for simply deploying WSGI applications with Apache. WSGI is used to deploy applications written with frameworks and tools like Django, Web.py, Chery.py, and Flask.

$ sudo yum install mod_wsgi
...
Installed:
  mod_wsgi.x86_64 0:3.4-12.el7_0
...





Install django

$ sudo yum install python-pip
...
Installed:
  python-pip.noarch 0:1.5.6-5.el7

Let's install Dajngo:

$ sudo pip install django
Downloading/unpacking django
  Downloading Django-1.8.2-py2.py3-none-any.whl (6.2MB): 6.2MB downloaded
Installing collected packages: django
Successfully installed django
Cleaning up...




Django project

[sfvue@sf www]$ sudo mkdir django
[sfvue@sf www]$ ls
django  pics.sfvue.com  sfvue.com

[sfvue@sf www]$ sudo chown -R sfvue django
[sfvue@sf www]$ cd django
[sfvue@sf django]$ pwd
/srv/www/django

[sfvue@sf django]$ django-admin.py startproject djangotest

We may want to create some folders for djangotest.sfvue.com:

[sfvue@sf www]$ pwd
/srv/www

[sfvue@sf www]$ sudo mkdir -p djangotest.sfvue.com/logs
[sfvue@sf www]$ sudo mkdir -p djangotest.sfvue.com/public_html


tree1.png

Note : as we can see from the picture above, we have a project(djangotest) created in an additional subdirectory (djangotest). If we don't want to create a subdirectory, we can add '.' after ' django-admin.py startproject':

[sfvue@sf django]$ django-admin.py startproject myProject .

So, instead of this,

django-subdir.png

we get this:

django-no-sub.png


Site configuration

[sfvue@sf conf.d]$ pwd
/etc/httpd/conf.d

[sfvue@sf conf.d]$ sudo cp vhost.conf djangotest.sfvue.com
[sfvue@sf conf.d]$ sudo mv djangotest.sfvue.com djangotest.sfvue.com.conf


Let's modify the file, /etc/httpd/conf.d/djangotest.sfvue.com.conf:

[sfvue@sf conf.d]$ sudo vim djangotest.sfvue.com.conf
<VirtualHost *:80>
    ServerAdmin webmaster@sfvue.com
    ServerName djangotest.sfvue.com
    DocumentRoot /srv/www/djangotest.sfvue.com/public_html/
    ErrorLog /srv/www/djangotest.sfvue.com/logs/error.log
    CustomLog /srv/www/djangotest.sfvue.com/logs/access.log combined
    WSGIScriptAlias / /srv/www/django/djangotest/djangotest/wsgi.py
    <Directory "/srv/www/djangotest.sfvue.com/">
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>
</VirtualHost>

WSGIPythonPath /srv/www/django/djangotest/
<Directory "/srv/www/django/djangotest/djangotest">
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

The WSGIScriptAlias directive tells Apache that for this VirtualHost, all requests below / should be handled by the WSGI script specified. In other words, it tells Apache and mod_wsgi where to find WSGI configuration. The wsgi.py supplied by Django contains the barebone default configuration for WSGI for serving Django application that works just fine.

The first bit in the WSGIScriptAlias line is the base URL path we want to serve our application at (/ indicates the root url), and the second is the location of a "WSGI file" on our system, usually inside of our project package (djangotest in this example).

The WSGIPythonPath line ensures that our project package is available for import on the Python path. In other words, it ensures that import djangotest works.

The last <Directory> piece just ensures that Apache can access our wsgi.py file.


When we have configured our Apache VirtualHost, issue the following command to restart the web server:

$ sudo apachectl restart 

Open up a browser with an url: http://djangotest.sfvue.com/:

ItWorkedDjango.png

Then, we can go to admin page:

DjangoAdmin.png



Settings.py - DB setup

Let's setup a database.

First, we need to create a db and a user, djangotestdb and djangotestuser, respectively. We will use phpmyadmin via port forwarding from local 8080 port to remote localhost 80:

k@laptop:~$ ssh -L 8080:localhost:80 -l sfvue 45.79.90.218

phpmyadmin-creating-djangotest-db.png

phpmyadmin-creating-djangotest-user.png
CheckAllUser.png

Click "Go", and it actually does this:

CREATE USER 'djangotestuser'@'localhost' IDENTIFIED BY '***';GRANT ALL PRIVILEGES ON *.* TO 'djangotestuser'@'localhost' IDENTIFIED BY '***' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;


Edit /srv/www/django/djangotest/djangotest/settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangotestdb',
        'USER': 'djangotestuser',
        'PASSWORD': 'K3zHqeArA9S5v3DR',
    }
}

Now we want to restart apache:

$ sudo apachectl restart

Let's install MySQL-python for managy.py can do its work between Python and mySQL:

$ sudo yum install MySQL-python
Installed:
  MySQL-python.x86_64 0:1.2.3-11.el7

$ pwd
/srv/www/django/djangotest
[sfvue@sf djangotest]$ ls
djangotest  manage.py

$ python manage.py makemigrations
No changes detected




syncdb

$ python manage.py syncdb
/usr/lib64/python2.7/site-packages/django/core/management/commands/syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
  warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)

Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... 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 sessions.0001_initial... OK

You have installed Django's auth system, and don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'sfvue'):
Email address: k.hong@aol.com
Password:
Password (again):
Superuser created successfully.

Now, we'll be able to login Django Admin:


LoggedInAdmin.png

As we can see, all of our static contents are broken. Let's work on it.





static contents

We need to edit settings.py:

...
STATIC_URL = '/static/'
STATIC_ROOT = '/srv/www/djangotest.sfvue.com/public_html/static'

Also, we may want to create the directory:

$ sudo mkdir -p /srv/www/djangotest.sfvue.com/public_html/static

tree2.png

Another thing: setting Apache alias:

Alias /static/ /srv/www/djangotest.sfvue.com/public_html/static/

in /etc/httpd/conf.d/djangotest.sfvue.com.conf, and it looks loke this:

<VirtualHost *:80>
    ServerAdmin webmaster@sfvue.com
    ServerName djangotest.sfvue.com
    DocumentRoot /srv/www/djangotest.sfvue.com/public_html/
    ErrorLog /srv/www/djangotest.sfvue.com/logs/error.log
    CustomLog /srv/www/djangotest.sfvue.com/logs/access.log combined
    WSGIScriptAlias / /srv/www/django/djangotest/djangotest/wsgi.py
    Alias /static/ /srv/www/djangotest.sfvue.com/public_html/static/
    <Directory "/srv/www/djangotest.sfvue.com/">
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>
</VirtualHost>

WSGIPythonPath /srv/www/django/djangotest/
<Directory "/srv/www/django/djangotest/djangotest">
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

Restart Apache:

$ sudo apachectl restart

Run the following to collect the static files into STATIC_ROOT:

$ sudo python manage.py collectstatic
You have requested to collect static files at the destination
location as specified in your settings:

    /srv/www/djangotest.sfvue.com/public_html/static

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes
Copying '/usr/lib64/python2.7/site-packages/django/contrib/admin/static/admin/css/base.css'
Copying '/usr/lib64/python2.7/site-packages/django/contrib/admin/static/admin/css/rtl.css'
...
Copying '/usr/lib64/python2.7/site-packages/django/contrib/admin/static/admin/js/admin/DateTimeShortcuts.js'
Copying '/usr/lib64/python2.7/site-packages/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js'

62 static files copied to '/srv/www/djangotest.sfvue.com/public_html/static'.

tree3.png

Now, if we want to refresh the Django Admin page:

We got good looking page!


DjangoAdminWithStaticFiles.png



Extra note for sfvue app

Let's create an app called sfvue under django folder:

[sfvue@sf django]$ pwd
/srv/www/django

[sfvue@sf django]$ django-admin.py startproject sfvue .

sfvue-app-dir-tree.png

Here is the configuration (/etc/httpd/conf.d/sfvue.com.conf):

<VirtualHost *:80>
    ServerAdmin webmaster@sfvue.com
    ServerName sfvue.com
    ServerAlias www.sfvue.com
    DocumentRoot /srv/www/sfvue.com/public_html/
    ErrorLog /srv/www/sfvue.com/logs/error.log
    CustomLog /srv/www/sfvue.com/logs/access.log combined
    WSGIScriptAlias / /srv/www/django/sfvue/wsgi.py
    Alias /static/ /srv/www/sfvue.com/public_html/static/
    <Directory "/srv/www/sfvue.com/">
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>
</VirtualHost>

WSGIPythonPath /srv/www/django/
<Directory "/srv/www/django/sfvue">
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>    


sfvue-com.png

django-admin-sfvue.png




Continue: 6. Model









Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Django 1.8



Introduction - Install Django and Project Setup

Creating and Activating Models

Hello World A - urls & views

Hello World B - templates

Hello World C - url dispatcher

Hello World D - Models and SQLite Database

MVC - Hello World

Hello World on a Shared Host A

Hello World on a Shared Host B

Hello World - Admin Site Setup

virtualenv

Creating test project on virtualenv

Test project's settings.py

Creating Blog app and setting up models

Blog app - syncdb A

Blog app - syncdb B

Blog app - views and urls

Blog app - templates

Blog app - class based templates

Image upload sample code - local host

Authentication on Shared Host using FastCGI

User Registration on Shared Host A

User Registration with a Customized Form on Shared Host B

Blogs on Shared Host

Serving Django app with uWSGI and Nginx

Image upload sample code - shared host

Managing (Deploying) Static files (CSS, Images, Javascript) on Shared Host

Forum application on a Shared Host

Django Python Social Auth : Getting App ID (OAuth2) - Facebook, Twitter, and Google

Django: Python social auth, Facebook, Twitter, and Google Auth

Django: Python social auth, Facebook, Twitter, and Google Auth with Static files

...

Django 1.8 hosted on Linode VPS ==>

1. Setup CentOS 7 hosted on VPS

1B. Setup CentOS 7 hosted on VPS (multi-domain hosting setup) - Name server and Zone File settings (from GoDaddy to Linode)

2. ssh login and firewall

3. Apache Install

4. Install and Configure MariaDB Database server & PHP

5. Install and Configure Django

6. Model

7. Model 2 : populate tables, list_display, and search_fields

8. Model 3 (using shell)

9. Views (templates and css)

10. Views 2 (home page and more templates)

11. TinyMCE

12. TinyMCE 2

13. ImageField/FileField : Serving image/video files uploaded by a user

14. User Authentication 1 (register & forms)

15. User Authentication 2 (login / logout)

16. User Authentication 3 (password reset) - Sent from Email (gmail) setup etc.

17. User Authentication 4 (User profile & @login_required decorator)

18. User Authentication 5 (Facebook login)

19. User Authentication 6 (Google login)

20. User Authentication 7 (Twitter login)

21. User Authentication 8 (Facebook/Google/Twitter login buttons)

22. Facebook open graph API timeline fan page custom tab 1

23. Facebook Open Graph API Timeline Fan Page Custom Tab 2 (SSL certificate setup)

24. Facebook open graph API timeline fan page custom tab 3 (Django side - urls.py, settings.py, and views.py)

...

A sample production site Django 1.8.7: sfvue.com / einsteinish.com ==>

A sample production app (sfvue.com) with virtualenv and Apache

2. Upgrading to Django 1.8.7 sfvue.com site sample with virtualenv and Apache

(*) Django 1.8.7 einsteinish.com site - errors and fixes

Django 1.8.12 pytune.com site - local with Apache mod_wsgi

Django 1.8.12 pytune.com site - local with Nginx and uWSGI

Django 1.8.12 pytune.com site - deploy to AWS with Nginx and uWSGI

Django Haystack with Elasticsearch and Postgres

Django Compatibility Cheat Sheet

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master