[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>

sfs - django start from scratch的更多相关文章

  1. Django Push HTTP Response to users

    Django Push HTTP Response to users I currently have a very simple web application written in Django, ...

  2. Django Model field reference

    ===================== Model field reference ===================== .. module:: django.db.models.field ...

  3. django源码分析 python manage.py runserver

    django是一个快速开发web应用的框架, 笔者也在django框架上开发不少web应用,闲来无事,就想探究一下django底层到底是如何实现的,本文记录了笔者对django源码的分析过程 I be ...

  4. Django集成Markdown编辑器【附源码】

    专注内容写作的你一定不要错过markdown 简单介绍 markdown是一种标记语言,通过简单的标记语法可以使普通的文本内容具有一定的格式,使用非常简单,学习成本极低 目前各大Blog平台都已支持m ...

  5. Django 2.0.1 官方文档翻译: 文档目录 (Page 1)

    Django documentation contents 翻译完成后会做标记. 文档按照官方提供的内容一页一页的进行翻译,有些内容涉及到其他节的内容,会慢慢补上.所有的翻译内容按自己的理解来写,尽量 ...

  6. django学习之- Cookie

    cookie:客户端游览器上的一个文件,以键值对进行保存,类似字典{'k':'sfs'},与服务器端没有关系,当游览器访问服务器时候,服务器会生成一个随机字符串保存在cookie中返回给客户端,这样当 ...

  7. 异步任务队列Celery在Django中的使用

    前段时间在Django Web平台开发中,碰到一些请求执行的任务时间较长(几分钟),为了加快用户的响应时间,因此决定采用异步任务的方式在后台执行这些任务.在同事的指引下接触了Celery这个异步任务队 ...

  8. 《Django By Example》第四章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:祝大家新年快乐,这次带来<D ...

  9. django server之间通过remote user 相互调用

    首先,场景是这样的:存在两个django web应用,并且两个应用存在一定的联系.某些情况下彼此需要获取对方的数据. 但是我们的应用肯经都会有对应的鉴权机制.不会让人家随随便便就访问的对吧.好比上车要 ...

随机推荐

  1. 关于json和字符串之间的转换

    在最近的工作中,使用到JSON进行数据的传递,特别是从前端传递到后台,前台可以直接采用ajax的data函数,按json格式传递,后台Request即可,但有的时候,需要传递多个参数,后台使用requ ...

  2. SQL LIKE语句多条件贪婪匹配算法

    在CMS开发中,经常会有类似这样的需求: 提问——回答模式,最经典的例子就是百度提问. 提问者提出问题,由其他人回答,其他人可以是用户,也可以是服务商. 在这个模式中,如何充分利用历史数据是最关键的技 ...

  3. MUI——页面的创建、显示、关闭

    一.打开子页面 mui.init({ subpages:[{ url:your-subpage-url,//子页面HTML地址,支持本地地址和网络地址 id:your-subpage-id,//子页面 ...

  4. 拦截QWebView弹出窗口

    环境 系统:win7 64位旗舰版 软件:VS2013.QT5.5.1-32位 概述 当网页打开一个新的窗口时,我们有时候需要根据URL地址来判断弹出窗口是否合理,如果合理则弹出新窗口,否则不弹出.本 ...

  5. Fighting For 2017 Season Contest 1

    比赛地址[https://vjudge.net/contest/147011#problem/A].960626 题目一:[http://codeforces.com/problemset/probl ...

  6. Python基础篇-day8

    本节目录1.抽象接口2.静态方法.类方法.属性方法3.类的特殊方法 3.1 __doc__ 表示类的描述信息(注释) 3.2 __module__ 和 __class__ 3.3 __init__ 构 ...

  7. if和switch的原理

    在C语言中,if和switch是条件分支的重要组成部分.if的功能是计算判断条件的值,根据返回的值的不同来决定跳转到哪个部分.值为真则跳转到if语句块中,否则跳过if语句块.下面来分析一个简单的if实 ...

  8. XPath相关笔记

    <?xml version="1.0" encoding="utf-8" ?> <employees>   <employee o ...

  9. SVM与LR的比较

    两种方法都是常见的分类算法,从目标函数来看,区别在于逻辑回归采用的是logistical loss,svm采用的是hinge loss.这两个损失函数的目的都是增加对分类影响较大的数据点的权重,减少与 ...

  10. javascript中关于继承的理解

    首先,你要理解在javascript中,每当一个新函数创建时,都会生成一个prototype属性,我们管它叫做原型对象.看一个例子: function foo(){ this.name='qiangq ...