sfs - django start from scratch

时间:2022-09-27 10:54:14

[TOC]

Launch with code

git spreading is obsolte
lwc

Installation

Path

  • D:\PythonWebSW\Django-1.5.5
    • add "D:\PythonWebSW\Python27\Script" to Environment Variable "Path", then django-admin.py can be run in any directory
    • add "D:\PythonWebSW\Python27\Lib\site-packages" to Environment Variable "Path"

How to uninstall django

[转]对于python setup.py install安装的包如何卸载

  • if you use easy_install

    easy_install -m package-name
  • if you install with source code
    python setup.py install --record log
    all the detailed information will record to "log" file
    excute command

    cat log | xagrs rm -rf

    then django will be uninstalled

    Start Project

    Create Project

    django-admin.py startproject lwc

    shell debug

    python manage.py shell
    >>> exit()

Create Database

create database "lwc" for this project

precondition

  • mysql installation ready
    ```
    C:\Users\alu>mysql -uroot -p123
    mysql> create database lwc;
    Query OK, 1 row affected (0.09 sec)

mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| lab_mgr |
| lwc |
| mysql |
| new_schema |
| performance_schema |
| sales |
| test |
+--------------------+
8 rows in set (0.26 sec)

### create django default tables set settings.py python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'lwc',
# Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'root',
'PASSWORD': '123',
'HOST': '',
# Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '',
# Set to empty string for default.
}
}
excute command python
python manage.py syncdb
it will create below tables and supper user python
D:\eclipse-workspace\git_python_spreading\spreading\lwc>python manage.py syncdb
Creating tables ...
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
Creating table django_site

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 'alu'):
Email address:

Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
## Launch Project python
python manage.py runserver
python manage.py runserver 8080
python manage.py runserver 0.0.0.0:8000

Django version 1.5.5, using settings 'lwc.settings'
Development server is running at http://127.0.0.1:8000/
# First Views ## enable admin setting.py python
INSTALLED_APPS = (
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
)
urls.py python

Uncomment the next two lines to enable the admin:

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
==>
url(r'^admin/', include(admin.site.urls)),
#add this
, otherwise, /admin will go to below next urlPattern, * means repeating precious char (0~n)
url(r'^(?P.*)$', 'joins.views.share', name='share'),
)
## Create your own view python
urlpatterns = patterns('',
# Examples:
url(r'^$', 'lwc.views.home', name='home'),
)
create views.py under lwc python
from django.shortcuts import render

def home():
context = {}
template = "home.html"
return render(request, template, context)
```

Create template

create lwc/templates & lwc/templates/home.html

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# print BASE_DIR ( show in command line )

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR,"templates")
    # "\" or "/" to join depending on your system Linux/Windows
)

Form

<form method = 'POST' action = '/abc'>{% csrf_token %}
{{form}}
<input type='submit' value='sign up'/>
</form>

Redirection

Create app

python manage.py startapp joins

settings.py

INSTALLED_APPS = (
    'joins'
    ...
)

update db

python manage.py syncdb

Admin

create admin.py

from django.contrib import admin
from .models import Join

class JoinAdmin(admin.ModelAdmin):
    list_display = ['__unicode__', 'friend', 'timestamp', 'updated']
    class Meta:
        model = Join

admin.site.register(Join, JoinAdmin)

South

使用South之前铭记:请你一定要相信他的能力,抛弃对他的不信任感。因为South给人的第一印象就是好像每个操作都在抛异常。

South概述

  • 针对django自带的syncdb同步models和数据库的缺陷开发的数据迁移工具,可以作为syncdb的替代,South能够检测对models的更改并同步到数据库.

South基本用法

  • 安装完South之后,要在django项目中使用South,先要将South作为一个App导入项目,所以设置INSTALL_APP添加south

setting.py

INSTALLED_APPS = (
    ...
    'South'
)

第一次使用South

(对于已存在的项目转用South见下一步的介绍)

python manage.py schemamigration youappname --initial
# --initial在数据库创建models定义的表,以及South需要的south_migrationhistory表,另外会在youappname目录下面创建一个migrations的子目录
#以后每次对models更改后,可以运行以下两条命令同步到数据库   

python manage.py schemamigration youappname --auto
#检测对models的更改
python manage.py migrate youappnam  #将更改反应到数据库

迁移到South

  • 对于一个已存在的项目(定义了models,创建了相应的数据库,保存了响应的数据),这时想要使用South替代原来的syncdb只需要一些简单的步骤:

  • 同样需要现在INSTALL_APP里面添加south,然后 python manage.py syncdb #syncdb已经被South更改,用来创建south_migrationhistory表

python manage.py syncdb
#syncdb已经被South更改,用来创建south_migrationhistory表
python manage.py convert_to_south youappname
#在youappname目录下面创建migrations目录以及第一次迁移需

# make change here
python manage.py schemamigration youappname --auto
python manage.py migrate youappname 
  • 以后在这个项目中就可以正常使用South了

South同步原理

  • 对应每次 models的更改执行schemamigration后会在migrations目录下面生成对应此次更改的py文件(South称之为 migrate),文件名形如0002_autodel_field_notes_create_user.py,同步数据库的时候会顺序(文件名 ASCII排序)执行这些py文件,文件里包含一个Migration的类,里面有两个方法forwards和backwards,将更改同步到数据库会 执行forwards方法,数据库操作失败会调用backwards实现rollback,South还提供了类似回溯的功能。

    You can also specify a specific migration to migrate: * python manage.py migrate 0002_autodel_field_notes_create_user.py Note that, if the system has already migrated past the specified migration, it will roll back to it instead. If you want to migrate all the way back, specify the special migration name zero: * python manage.py migrate zero

常见问题

  1. 添加和删除字段时可能会要求输入 default value(django里面models里面的许多字段默认都是null=False)
    对于添加字段,输入的默认值必须和models定义的类型匹配,否则同步数据库的时候会报错
    对于删除字段的情况,可以随意输入一个value而不管字段的默认类型,可以实现删除,但是并不可取,具体原因可以参见South的实现机制(rollback到删除字段之前会失败)。

  2. 杀手锏
    如果South在同步数据库的过程中出现错误,则migrations目录下面对应此次更改的python文件不会被执行,可以运行python manage.py migrate --list查看没有执行的py文件,文件名前面没有*表示该文件对应的更改没有反应到数据库,只需删除掉这些有问题的migrate,参照错误提示修改 models再同步即可,也可以直接更改对应的py文件修复错误

django-south使用

Middleware

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',
    'lwc.middleware.ReferMiddleware',
)

add ReferMiddleware.py

from joins.models import Join
class ReferMiddleware():
    def process_request(self, request):
        ref_id = request.GET.get("ref")
        try:
            obj = Join.objects.get(ref_id = ref_id)
        except:
            obj = None
        if obj:
            request.session['join_id_ref'] = obj.id

Foreign Key

staticfile

settings.py

STATIC_URL = '/static_lwc/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static','static_root')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static','static_dirs')
    )
MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media')
MEDIA_URL = '/media_lwc/'

src

  • static_root
  • static_dirs
  • img
  • css
  • js
  • media

Excute command to collect static files

python manage.py collectstatic

static files from static_dirs (user) and django/admin (system) will collect to static_root

D:\eclipse-workspace\git_python_spreading\spreading\lwc\src>python manage.py collectstatic

Type 'yes' to continue, or 'no' to cancel: yes

Copying 'D:\eclipse-workspace\git_python_spreading\spreading\lwc\src\static\static_dirs\img\iphone.png'
Copying 'D:\eclipse-workspace\git_python_spreading\spreading\lwc\src\static\static_dirs\img\launch.jpg'

Copying 'D:\PythonWebSW\Python27\lib\site-packages\django\contrib\admin\static\admin\css\base.css'
...
Copying 'D:\PythonWebSW\Python27\lib\site-packages\django\contrib\admin\static\admin\img\changelist-bg.gif'
...
Copying 'D:\PythonWebSW\Python27\lib\site-packages\django\contrib\admin\static\admin\js\actions.js'
...

HTML file

<!DOCTYPE thml>
{% load staticfiles %}
<html>
<head>
<link href = "{% static 'css/bootstrap.min.css' %}" rel = "stylesheet">
</head>

<img src = "{% static 'img/iphone.png' %}" class = "img-responsive" />

</html>