Django

From XennisWiki
Jump to: navigation, search

Django is a free and open source web application framework, written in Python, which follows the model–view–controller architectural pattern. (Wikipedia)

Install

Further information: Django documentation - Quick install guide

In this article a Apache web server with a MySQL database was setup on an Ubuntu machine. How to install Apache HTTP Server, PHP, MySQL and phpMyAdmin can be found in the article Setting up a Web Server (with Apache, PHP, Git, Redmine, etc.).

Install Python and pip

see Python#Installation

Python and Apache - Configure server

Further information: How to use Django with Apache and mod_wsgi

When using Apache as server, it is recommended[1] to install the Apache module mod_wsgi

sudo apt-get install libapache2-mod-wsgi

Afterwards it is necessary to configure the module.[1][2] (Configer file /etc/apache2/apache2.conf)

Restart Apache server

sudo service apache2 restart

Install Django

Further information: How to get Django

Optional: If you are using MySQL

pip install MySQL-python

Use pip to install Django

pip install Django==1.9.1

To test the success of the installation check the Django version

python
>>> import django
>>> print(django.get_version())

Tutorial

See Django - Write an app

Basic commands

Create a application named myproject and inside this applikation an app named myapp

$ django-admin startproject myproject
$ cd myproject/
$ chmod +x manage.py
$ python manage.py startapp myapp

Migrate database and create a super user

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py createsuperuser

Django has a buildin web server

$ python manage.py runserver

Errors and problems

No Access-Control-Allow-Origin

Further information: Django documentation - Middleware

Error

XMLHttpRequest cannot load http://localhost:8000/api/v1/USER/?format=json.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access

Solution

MIDDLEWARE_CLASSES = (
    # ... other stuff
    'MYAPP.django-crossdomainxhr-middleware.XsSharing',
)

mysql_config not found / No module named MySQLdb

Error

Error loading MySQLdb module: No module named MySQLdb

Error

EnvironmentError: mysql_config not found

Solution[3]

# Option 1
pip install MySQL-python
# Option 2
sudo apt-get install python-mysqldb

See also

References

External links