Difference between revisions of "Django-Installation"

From Biowikifarm Metawiki
Jump to: navigation, search
m (Problem Solving: + section, +Category: Trouble shooting)
m (+sec: #Help Commands)
Line 1: Line 1:
 
(See also: [[Artenquiz documentation]])
 
(See also: [[Artenquiz documentation]])
 +
 +
== Help Commands ==
 +
 +
<source lang="bash">
 +
django-admin.py --version # 1.6.5
 +
</source>
  
 
== Install automatically ==
 
== Install automatically ==

Revision as of 15:03, 7 December 2021

(See also: Artenquiz documentation)

Help Commands

django-admin.py --version # 1.6.5

Install automatically

Under Debian 6, Squeeze

#default version is 1.2:
sudo apt-get update # get updated package data
apt-cache showpkg python-django # check version
sudo apt-get install python-django python-django-registration python-mysqldb
# Instead, it is possible to install 1.3.1 from squeeze backport - WE DID THIS:
sudo apt-get remove python-django
sudo apt-get -t squeeze-backports install python-django  python-django-registration
# Result was: Setting up python-django (1.3.1-2~bpo60+1)

Advantage of debian repository installation is that apt-get update will inject any necessary security updates.

NOTE: python-django-registration is NOT in a current version, but in an older one than we used before. Debian has only 0.7.x, we had used 0.8alpha. Thus: sudo apt-get remove python-django-registration and installed manually!

Use Python pip

Alternative 1: Use alternative python package installer (instead of easy_install):

sudo apt-get update # get updated package data
sudo apt-get install python-pip
# first install or install a specific version
pip install django==1.4.2
# upgrade: there is a upgrade option (pip install --upgrade) and may work, or deinstall and reinstall it
pip uninstall django
pip install django==1.5

Alterantive 2: use get-pip.py (documentation)

# go to home directory and create a temp folder and go into it
cd ~ && mkdir temp && cd ./temp
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py

Useful tools

pip install django-debug-toolbar
pip install django-annoying

Manually

Django

link = http://www.djangoproject.com/

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

Version in lenny is 1.0, which is too old.

# Download 
mkdir ~/temp
cd ~/temp
wget http://www.djangoproject.com/download/1.2.5/tarball/
# extract
tar xzvf Django-1.2.5.tar.gz
# install (see http://docs.djangoproject.com/en/1.2/topics/install/#installing-official-release)
cd ./Django-1.2.5
sudo python setup.py install --prefix /usr/local

# Install mod_wsgi for Apache (it is enabled automatically):
apt-get install libapache2-mod-wsgi

To use this version with the application “artenquiz”, add an apache virtual host (see /etc/apache2/sites-enabled/artenquiz).

Access to a MSSQL Server

Installations

Following the tutorial Accessing a SQL Server (MSSQL) database from Django (2013):

sudo apt-get install freetds-common freetds-bin tdsodbc
# subversion, unixodbc is already installed
sudo apt-get build-dep pyodbc
# undo build-dep
#   sudo aptitude markauto $(apt-cache showsrc build-dep | grep Build-Depends | perl -p -e 's/(?:[[(].+?[])]|Build-Depends:|,||)//g')
#   sudo apt-get autoremove
cd ~ && mkdir temp && cd ./temp
svn checkout http://django-pyodbc.googlecode.com/svn/trunk/ django-pyodbc-read-only
cd django-pyodbc-read-only
sudo python setup.py build install
# needs pip (python package installer)
sudo pip install pyodbc # does not work so follow the instructions given in the command line
sudo pip install --allow-external pyodbc pyodbc # does not work so follow the instructions given in the command line
sudo pip install --allow-unverified pyodbc pyodbc # OK

BUG Fix

Correct a BUG in operations.py around line 10

PYTHON_SITEPACKAGES_DIR=`python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"`
sudo vi "${PYTHON_SITEPACKAGES_DIR}/sql_server/pyodbc/operations.py"
old with BUG BUG corrected
 7 class DatabaseOperations(BaseDatabaseOperations):
 8     compiler_module = "sql_server.pyodbc.compiler"
 9     def __init__(self, connection):
10         super(DatabaseOperations, self).__init__()
11         self.connection = connection
12         self._ss_ver = None
 7 class DatabaseOperations(BaseDatabaseOperations):
 8     compiler_module = "sql_server.pyodbc.compiler"
 9     def __init__(self, connection):
10         super(DatabaseOperations, self).__init__(connection)
11         self.connection = connection
12         self._ss_ver = None

Configurations

And the configurations:

edit command content of configuration
sudo vi /etc/freetds/freetds.conf
[MSSQL-PYTHON]
host = host.of.sqlserver.de
port = 1234
tds version = 8.0
sudo vi /etc/odbc.ini

Make sure before configuring, that the path for “Driver” is correct you find it by searching files in /usr/

find /usr/ -name "*libtdsodbc*" -type f
[ODBC Data Sources]
ODBCNAME = Microsoft SQL Server
[MSSQL-PYTHON]
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Description = Connect to xy-database by MSSQL-PYTHON driver
Trace = No
Database = xy-database
Server = host.of.sqlserver.de
Port = 1234

After creating andjango project by

cd /myfolder/
django-admin startproject django_mssql_project
# tree django_mssql_project
# django_mssql_project/
# ├── django_mssql_project
# │   ├── __init__.py
# │   ├── settings.py
# │   ├── urls.py
# │   └── wsgi.py
# ├── __init__.py
# ├── manage.py
# ├── settings.py
# └── urls.py

Configure the database connection in django_mssql_project/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '<Database name>',                      # Or path to database file if using sqlite3.
        'USER': '<Database user>',                      # Not used with sqlite3.
        'PASSWORD': '<Database password>',                  # Not used with sqlite3.
        'HOST': 'MSSQL-PYTHON',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '1433',                      # Set to empty string for default. Not used with sqlite3.
        'OPTIONS': {
                'host_is_server': False,
                'dsn': 'MSSQL-PYTHON',
        },
    }
}
DATABASE_NAME = '<Database name>'
DATABASE_HOST = 'MSSQL-PYTHON'
DATABASE_PORT = '1433'
DATABASE_USER = '<Database user>'
DATABASE_PASSWORD = '<Database password>'
DATABASE_OPTIONS = {
        'host_is_server': False,
        'dsn': 'MSSQL-PYTHON',
}

Tests

Test the access by displaying all tables:

isql -v MSSQL-PYTHON <Username> <Password>
SELECT * FROM INFORMATION_SCHEMA.TABLES;

Or use tha Django management program to check if it is working, e.g

python ./manage
python ./manage inspectdb

Install/Upgrade by script

Using the following bash script you can upgrade django to a certain version, here 1.3. It tries to download that version and optionally delete the old one first. For more details see also http://docs.djangoproject.com/en/dev/topics/install/#how-to-install-django

#!/bin/bash
# define a version
djversion=1.3
#get directories
#SITEPACKAGESDIRLOCAL=/usr/local/lib/python2.5/site-packages
SITEPACKAGESDIRLOCAL=`python -c "from distutils.sysconfig import get_python_lib; print get_python_lib(0, 0, '/usr/local')"`
SITEPACKAGESDIR=`python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"`

echo "Remove older django first?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) echo "Remove django..."; 
          cd $SITEPACKAGESDIRLOCAL
          sudo rm -r Django*
          sudo rm -r django*
          sudo rm -i /usr/local/bin/django-admin.py
          sudo rm -i $SITEPACKAGESDIR/django.pth
        break;;
        No ) break;;
    esac
done

echo "Download django $djversion and install?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) 
          echo "Download django..."; 
          # download
            wget "http://www.djangoproject.com/download/$djversion/tarball/" --output-document=Django-${djversion}.tar.gz
            if [ -a Django-${djversion}.tar.gz ]; then
              # extract
              tar xzf Django-${djversion}.tar.gz
                cd Django-${djversion}
              echo "Django extracted to ./Django-${djversion}"; 
              echo "Install to ${SITEPACKAGESDIRLOCAL}..."; 
              # install
              sudo python setup.py install --prefix /usr/local
              # some information
              echo "**************************************"
              echo "Files are in:"
              echo ${SITEPACKAGESDIRLOCAL}
              echo ${SITEPACKAGESDIR}
              echo "/usr/local/bin/django-admin.py"
              echo "**************************************"
            else
              echo "Could not download Django-${djversion}.tar.gz. Stop."
              exit
            fi # end Django-${djversion}.tar.gz
        break;;
        No ) echo "Exit."; exit;;
    esac
done

Reloading Source Code

The mod_wsgi is an extra layer additionally to the apache. Usually when there is any code change on py-files it will reload. However sometimes it does not. Further reading: http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode

Miscellaneous

Management tasks

djangoPath=/to/my/django/application/
cd $djangoPath
# get help infos
  python manage.py help
  python manage.py help createsuperuser
# create a superuser
  python manage.py createsuperuser
# show django’s default database model descriptions based on the database in settings.py
  python manage.py inspectdb
# run developement server on http://127.0.0.1:8000/
  python manage.py runserver
# get python shell for django
  python manage.py shell

# start a project
  django-admin.py help
  django-admin.py startproject mysite 
# create an application
  django-admin.py help
  django-admin.py startapp myapp # in the current directory

Directory architecture

django-project-root
├─ apache/
│  └─ django.wsgi  mod_wsgi interface between webserver and Python applications
│
├─ yourapp/
│  ├─ models.py  model definitions
│  ├─ admin.py   admin GUI settings
│  └─ views.py   view layer definitions
│
├─ locale/  localized application messages for internationalisation
│  ├─ de/LC_MESSAGES/
│  │     ├─ django.po   string dictionary for German. Created with: django-admin.py makemessages -l de
│  │     └─ django.mo   machine readable output. Created with: django-admin.py compilemessages
│  ├─ en/LC_MESSAGES/
│  │     ├─ …
│  │     └─ …
│  └─  …/LC_MESSAGES/
│
├─ templates/  organizing HTML templates here
│  ├─ base.html
│  └─ quiz.html
│
├─ manage.py    management tasks
├─ settings.py  the program’s settings
└─ urls.py      settings of url patterns

Install django-registration

Version 0.7

sudo easy_install django-registration
# uninstall
sudo easy_install -m django-registration
cd /usr/lib/python2.5/site-packages/
sudo rm django_registration-0.7-py2.5.egg

Version 0.8 alpha will install into /usr/local/lib/python2.5/site-packages/ using --prefix /usr/local

wget https://bitbucket.org/ubernostrum/django-registration/downloads/django-registration-0.8-alpha-1.tar.gz
tar zxvf django-registration-0.8-*.tar.gz
cd django-registration-0.8-alpha/
sudo python setup.py install --prefix /usr/local

Admin UI

If you have created a super user account by:

  djangoPath=/to/my/django/application/
  cd $djangoPath
  # get help infos
  #  python manage.py help createsuperuser
  # create a superuser
  python manage.py createsuperuser

You have access now to http://your-website/admin. Which data base models are shown, is set in

django-project-root
└─ yourapp/
   └─ admin.py   admin GUI settings

Apache Configuration

  • create alias also for /admin UI
sudo vi /etc/apache2/sites-available/mysite
# apache config mysite alias
        WSGIScriptAlias / /path/to/django/app/django-wsgi-handler.wsgi
        Alias /static/admin/ /usr/share/pyshared/django/contrib/admin/static/admin/
        Alias /static/ /path/to/django/app/static/
        Alias /favicon.ico /path/to/django/app/static/img/favicon.ico

Additional useful software

  • python-docutils: enables the automatic generation of python code documentation that appears then in the Django admin user web-interface. A great help for administrators or programmers.

Problem Solving

Error:

ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Solution: Multiple. In general the MySQL database connection is lost see also https://stackoverflow.com/questions/29631430/error-loading-mysqldb-module-in-python-django#34976643

aptitude search '~i python-mysqldb' # search for installed package python-mysqldb

If it is not there and if pip list does not list package MySQL-python then the following install might resolve this in installing package python-mysqldb:

sudo apt-get install python-mysqldb