First step install dependencies.
sudo apt-get install git python-setuptools python-pip python-dev \
&& sudo apt-get install python3-pip python3-dev virtualenv
then install local envirement of Django project.
cd /to/your/project
virtualenv --nosite-packages env
pip install --upgrade pip setuptools wheel
activate your local envirement:
source env/bin/activate
or . env/bin/activate
then install Django:
easy_install Django
or pip install Django
.
to getting started check Django availabel commands
django-admin.py
start new project called project1 by
django-admin.py startproject project1
then run the project1
python manage.py runserver
to deactivate local envirement
deactivate # to deactivate envirement
reactive your local envirement then start new app called article
python manage.py startapp article # (to create article model folder)
syncdb command to add tables of app models to your database
for previous version 1.6>= django
python manage.py syncdb # (add tables synchronounslly)
python manage.py sql article # (to see SQL command for creating article table)
python manage.py reset article # (to delete article table)
the most amazing features that integrated in Django is shell connect to test your scripts depend on project and local envirement.
python manage.py shell # to add object to article table in terminal
inside the shell you can execute some script depend on project.
>>> from article.models import article
>>> Article.objects.all()
[]
>>> from django.utils import timezone
>>> a = Article(title="Test 1", body="blah", pub_date=timezone.now(), likes=0)
>>> a
<Article: Article object>
>>> a.save()
>>> a.id
1
if you have assets file you can collect them in your static directory.
python manage.py collectstatic # This command to copy your assets files for admin to static folder in your project
in this section we will learn how to integrate between Django and its MySQL database
to connect to mysql with django you need to install these dependencies.
sudo apt-get install build-essential python-dev python3-dev libmysqlclient-dev python-mysqldb libssl-dev # Debian / Ubuntu
sudo yum install python-devel mysql-devel # Red Hat / CentOS
brew install mysql-connector-c # macOS (Homebrew) (Currently, it has bug. See below)
after that you should install this library for global and local envirement.
pip install mysqlclient
finally you may synchronous your database without problem. Django 1.6 and lower
python manage.py syncdb
Django 1.7 and higher
python manage.py migrate --run-syncdb
install postgre dependencies
sudo apt-get update
sudo apt-get install libpq-dev postgresql-client postgresql-client-common
sudo apt-get install python-psycopg2 python3-psycopg2
sudo apt-get install postgresql postgresql-contrib
setting up postgres user and database
sudo passwd postgres
su - postgres
psql -d template1 -c "ALTER USER postgres WITH PASSWORD 'newpassword';"
or
sudo -u postgres psql
create role anyuser with password '123456';
alter role anyuser createrole login;
alter role anyuser createrole superuser;
creating database by:
create database anydb;
grant all privileges on database anydb to anyuser;
\q
to delete database by:
drop database anydb;
Export PostgreSQL Database
pg_dump -U username dbname > dbexport.pgsql
Import PosgreSQL Database
psql -U username dbname < dbexport.pgsql
Testing conntion to database in bash script
pg_isready -d <db_name> -h <host_name> -p <port_number> -U <db_user>
ALTER DATABASE target_database OWNER TO new_onwer;
\c target_database
ALTER TABLE target_table_name OWNER TO new_onwer;
According to: PostgreSQL Tutorial
\c selected_db;
REVOKE ALL ON ALL TABLES FROM USER user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO user;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public to user;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO user;
select * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;
source: here
SELECT client_addr,COUNT(*) FROM pg_stat_activity GROUP BY client_addr ORDER BY 2 DESC;
SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE state = 'active' and pid <> pg_backend_pid();
source: here
sudo adduser newuser
sudo gpasswd -a newuser sudo
su - newuser
working with xml and json api
pip install django-tastypie
pip install defusedxml "lxml>=3"
if it does not work you may do the following commands
sudo dpkg --configure -a
sudo apt-get install libxml2-dev libxslt1-dev python-dev
sudo apt-get install python-lxml
South Depricated in Django 1.7 and higher
database migrations and upating schema using south
pip install south
chmod +x manage.py
./manage.py
./manage.py schemamigration article --initial
after that the following command will be available
./manage.py migrate article
the following command is used for modify any change has happen in Article model
./manage.py schemamigration article --auto
if you want to delete or undo the migration we can go back to the preview migration like the following command
./manage.py migrate article 0002 # if the last one was 0003
if I want to go back to the version 0003
./manage.py schemamigration article
./manage.py migrate article --fake
./manage.py datamigration article convert_names
working with haystack and Whoosh.
Full text search using haystack and Whoosh.
pip install whoosh django-haystack
./manage.py rebuild_index
create notification app example filtering data by user and sending notification
./manage.py startapp notification
./manage.py schemamigration notification --initial
./manage.py migrate
using Twitter Bootstrap in Django Reusing apps and using twitter bootstrap
pip install django south django-bootstrap-toolkit
In this case I am using json format, when you backup whole database by using dumpdata command, it will backup all the database tables.
- If you use this database dump to load the fresh database(in another django project), it can be causes
IntegrityError
(If you loaddata in same database it works fine) - To fix this problem, make sure to backup the database by excluding contenttypes and auth.permissions tables
./manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
Now you can use loaddata command with a fresh database safely
./manage.py loaddata db.json
This is used to remove user's sessions on running django project, log into interactive shell:
python manage.py shell
then
>>> from django.contrib.sessions.models import Session
>>> Session.objects.all().delete()
(15428, {'sessions.Session': 15428})
This is the simplest and fasted way to learn Django very quickly, this is tutorial good for people has the basic knowledge in Python2 and Python3, and good for who is familier with Terminal and Unix envirement.