[ install Django on Ubuntu 13.10 ]
# apt-get install python-setuptools
# easy_install django
|
# python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()
'1.6.1'
>>>
|
start
# mkdir Django_works
# cd Django_works/
# django-admin.py startproject example
# cd example/
# python manage.py runserver 8080
Validating models...
0 errors found
January 20, 2014 - 09:00:15
Django version 1.6.1, using settings 'example.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.
|
access to http:// IP:8080
[ access to PostgreSQL ]
Reference
create a project
# django-admin.py startproject myblog
# cd myblog
|
install PostgreSQL
# apt-get install postgresql
# apt-get install postgresql-server-dev-9.1
# apt-get install postgresql-client postgresql-client-common
# /etc/init.d/postgresql status
9.1/main (port 5432): online
|
Create a DB
# su postgres
$ psql
psql (9.1.11)
Type "help" for help.
postgres=# CREATE USER foo01 WITH PASSWORD 'foo01';
CREATE ROLE
postgres=# CREATE DATABASE myblog;
CREATE DATABASE
postgres=# GRANT ALL PRIVILEGES ON DATABASE myblog TO foo01;
GRANT
postgres=# \q <- Ctrl + D
|
install PostgreSQL driver.
# easy_install psycopg2
|
edit mublog/settings.py to access PostgreSQL.
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myblog',
'USER': 'foo01',
'PASSWORD': 'foo01',
'HOST': 'localhost',
'POSRT': '',
}
}
|
initialize DB
# python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'root'):
Email address:
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
|
# python manage.py shell
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: root>]
>>> exit
|
[ write models ]
Reference
http://www.pythoncentral.io/writing-models-for-your-first-python-django-application/
create an App called blog in myblog project.
python manage.py startapp blog
|
create a models.
# cat myblog/myblog.py
from django.db import models
class Post(models.Model):
content = models.CharField(max_length=256)
created_at = models.DateTimeField('Datetime created')
class Comment(models.Model):
post = models.ForeignKey(Post)
message = models.TextField()
created_at = models.DateTimeField('Datetime created')
|
edit myblog/settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
|
check the DB command
# python manage.py sql blog
BEGIN;
CREATE TABLE "blog_post" (
"id" serial NOT NULL PRIMARY KEY,
"content" varchar(256) NOT NULL,
"created_at" timestamp with time zone NOT NULL
)
;
CREATE TABLE "blog_comment" (
"id" serial NOT NULL PRIMARY KEY,
"post_id" integer NOT NULL REFERENCES "blog_post" ("id") DEFERRABLE INITIALLY DEFERRED,
"message" text NOT NULL,
"created_at" timestamp with time zone NOT NULL
)
;
COMMIT;
|
creat the DB.
# python manage.py syncdb
Creating tables ...
Creating table blog_post
Creating table blog_comment
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
|
python interactive shell
# python manage.py shell
>>> from blog import models
>>> dir()
['__builtins__', 'models']
>>> dir(models)
['Comment', 'Post', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'models']
>>> dir(models.Comment)
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', u'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_base_manager', '_default_manager', '_deferred', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', 'clean', 'clean_fields', 'date_error_message', 'delete', 'full_clean', 'get_next_by_created_at', 'get_previous_by_created_at', 'objects', 'pk', 'post', 'prepare_database_save', 'save', 'save_base', 'serializable_value', 'unique_error_message', 'validate_unique']
>>>
|
Post object
>>> from django.utils import timezone
>>> p = models.Post(content='Django is awesome.', created_at=timezone.now())
>>> p
<Post: Post object>
>>> p.created_at
datetime.datetime(2014, 1, 21, 5, 19, 22, 790222, tzinfo=<UTC>)
>>> models.Post.objects.all()
[]
>>> p.save()
>>> models.Post.objects.all()
[<Post: Post object>]
>>> p.id
1
>>> p2 = m.Post(content='Pythoncentral is also awesome.', created_at=timezone.now())
>>> p2.save()
>>> models.Post.objects.all()
[<Post: Post object>, <Post: Post object>]
>>>
>>> models.Post.objects.all()[0].id
1
>>> models.Post.objects.all()[1].id
2
|
Comment Object
>>> dir(models.Comment)
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', u'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_base_manager', '_default_manager', '_deferred', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', 'clean', 'clean_fields', 'date_error_message', 'delete', 'full_clean', 'get_next_by_created_at', 'get_previous_by_created_at', 'objects', 'pk', 'post', 'prepare_database_save', 'save', 'save_base', 'serializable_value', 'unique_error_message', 'validate_unique']
>>> c = models.Comment(message='This is a comment for p', created_at=timezone.no
w())
|
class Comment(models.Model):
post = models.ForeignKey(Post)
>>> p
<Post: Post object>
>>> c.post = p <- post = models.ForeignKey(Post)
>>> c.post
<Post: Post object>
>>> p.comment_set.all()
[]
>>> c.save()
>>> p.comment_set.all()
[<Comment: Comment object>]
|
Retrieve
>>> p.comment_set.filter(created_at__year=2014)
[<Comment: Comment object>]
>>> p.comment_set.filter(message__startswith='This is a')
[<Comment: Comment object>]
|
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.