# 在下载好的django路径下执行django的安装
# https://pypi.python.org/pypi/Django/1.6.4
python3 setup.py install
#
# 新建django项目
django-admin.py startproject mysite
#
# 运行django项目
python3 manage.py runserver [port]
#
# 创建一个app
python3 manage.py startapp appname
#
# 模型定义特殊字段定义(后面一些Field被略去)
# AutoFiled  SlugField SmallIntegerField #Date,DateTime,Decimal,Char,File,Float,FilePath,Text#,Time,Binary,Boolean,BigInterger,NullBoolean,Image,#Interger,OneToOne
#PositiveSmallIntegerField, #PositiveIntergerField,Url,Email
#
# 创建一个model实体
from django.db import models
class Publisher(models.Model):
    name = models.CharField(max_length=30) // 普通字段
    website = models.URLField()   // url类型字段
    email = models.EmailField()   // email类型字段
    publication_date = models.DateField()   // 时间类型字段
    publisher = models.ForeignKey(Publisher)   // 引用信息(外键)
#
# 模型检测 (需要在settings.py中注册此app)
python3 manage.py validate
#
# 模型生成sql语句查看
python3 manage.py sqlall modelname (app的名字)
#
# 模型生成到db 要生成用户之前必须做这一步
python3 manage.py syncdb
#
# 建立管理超级员
python manage.py createsuperuser
#
# 将model加入到admin管理列表中 在admin中
from django.contrib import admin
from books.models import Publisher, Author, Book
admin.site.register(Author,AuthorAdmin)
#
# 附加管理视图
from django.contrib import admin
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'publisher', 'publication_date')   #显示列
    list_filter = ('publication_date',)    # 列过滤条件
    date_hierarchy = 'publication_date'   # 日期选择条件
    ordering = ('-publication_date',)   # 列表日期降序排列
    fields = ('title', 'authors', 'publisher')  # 编辑时显示需要添加的列   其他列   null=True
    raw_id_fields = ('publisher',)  # 编辑时 显示为id序号
#
# 定义模板路径
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'template').replace('\\','/'),
    # /Users/King/Documents/Ops/Python/HelloDjango/HelloDjango
    # /Users/King/Documents/Ops/Python/HelloDjango/HelloDjango/template
)
#
# 进入项目命令行模型
python manage.py shell
    from django.contrib.auth.models import Publisher
    p = Publisher.objects.create(name='Apress',website='www.apress.com')
    Publisher.name = 'tuling'
    所有的model都拥有一个objects管理器
    使用filter方法可以过滤obj    Publisher.objects.filter(name='usa')
    模糊查询        Publisher.objects.filter(name__contains='usa')
#   
    使用get方法可完成一个对象的获取,如果返回不止一个对象就会报错 Publisher.DoesNotExist
    使用order_by 排序    可 - 倒排
    p = Publisher.objects.filter(id=52).update(name='Apress Publishing')
    p.delete()   删除对象
    p.save()
#
# 导入静态文件
在setting.py中
    # 静态资源区域
    # 这是一个根目录区域   对应实际文件目录
    STATIC_ROOT = 'static/'
    # 这是url配置目录   给urls用的
    STATIC_URL = 'static/'
在模板页面中
    <link rel="stylesheet" href="` STATIC_URL `css/bootstrap.css">
    <script type="text/javascript" src="` STATIC_URL `js/bootstrap.js"></script>
在urls.py的配置中
    from django.conf.urls.static import static
    在最后加入
    admin.autodiscover()
    urlpatterns = patterns('',
        # Examples:
        # url(r'^$', 'HelloDjango.views.home', name='home'),
        # url(r'^blog/', include('blog.urls')),
        url(r'^admin/', include(admin.site.urls)),
        (r'^$', latest_books),
    ) + (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
在views.py对应的输出视图中
    return render_to_response('index.html', {
        'book_list': book_list,
        'STATIC_URL': STATIC_URL,
    })
#
# 其他解决方案
配置文件中
STATICFILES_DIRS = (
    '/Users/King/Documents/Ops/Python/HelloDjango/static',
)
#
#
# 一个app基本的设置
#
#
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
ROOT_URLCONF = 'HelloDjango.urls'
SECRET_KEY = '&%s+d(0$motnksr+0o+oo8z9k=2h*7gd%gnnylrnc^w5#nut)h'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
WSGI_APPLICATION = 'HelloDjango.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# # Absolute filesystem path to the directory that will hold user-uploaded files.
# # Example: "/home/media/media.lawrence.com/media/"
# MEDIA_ROOT = ''
#
# # URL that handles the media served from MEDIA_ROOT. Make sure to use a
# # trailing slash.
# # Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
# MEDIA_URL = ''
# BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# TEMPLATE_DIRS = ('templates',)
# 静态资源区域
# 这是一个根目录区域   对应实际文件目录
STATIC_ROOT = 'static/'
# 这是url配置目录   给urls用的
STATIC_URL = 'static/'
# STATICFILES_DIRS = (
# # Put strings here, like "/home/html/static" or "C:/www/django/static".
# # Always use forward slashes, even on Windows.
# # Don't forget to use absolute paths, not relative paths.
# )
# STATICFILES_FINDERS = (
#     'django.contrib.staticfiles.finders.FileSystemFinder',
#     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#     #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
# )
# 定义模板路径
# List of callables that know how to import templates from various sources.
# TEMPLATE_LOADERS = (
#     'django.template.loaders.filesystem.Loader',
#     'django.template.loaders.app_directories.Loader',
#     #     'django.template.loaders.eggs.Loader',
# )
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates').replace('\\','/'),
)
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
)
# LOGGING = {
#     'version': 1,
#     'disable_existing_loggers': False,
#     'filters': {
#         'require_debug_false': {
#             '()': 'django.utils.log.RequireDebugFalse'
#         }
#     },
#     'handlers': {
#         'mail_admins': {
#             'level': 'ERROR',
#             'filters': ['require_debug_false'],
#             'class': 'django.utils.log.AdminEmailHandler'
#         }
#     },
#     'loggers': {
#         'django.request': {
#             'handlers': ['mail_admins'],
#             'level': 'ERROR',
#             'propagate': True,
#             },
#         }
# }
Django框架中的基本交互
12345678910111213141516 # 服务器端展示数据
from django.shortcuts import render_to_response
def search(request):
    return render_to_response('search.html', {'books':books,})
#
# search.html的数据渲染 , 利用模板
{% if books %}
    <ul>
    发现 {{ books | length }} 本书
    {% for book in books %}
        <li>` book`.`title `</li>
    {% endfor %}
    </ul>
{% else %}
    <p>没有查询到任何图书信息</p>
{% endif %}
12345678910111213141516171819202122232425 # 客户端提交数据 search_form.html
<html><head>
<title>Search</title></head>
<body>
{% if error %}
<p style="color:red;">请输入查询条件</p>
{% endif %}
<form action="/search_form/" method="get">    
<input type="text" name="q">    
<input type="submit" value="Search">
</form>
</body>
</html>
#
# 收集客户端信息
# from django.http import HttpResponse
# request.path()   get_host()   get_full_path()   get_isecure()
# request.META[]   包含http头信息
def search_form(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        books = Book.objects.filter(title__icontains=q)
        return render_to_response('search_result.html', {'books':books,'query':q})
    else:
        return render_to_response('search.html', {'error': True})