sfs - django start from scratch
[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 commandcat 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
常见问题
添加和删除字段时可能会要求输入 default value(django里面models里面的许多字段默认都是null=False)
对于添加字段,输入的默认值必须和models定义的类型匹配,否则同步数据库的时候会报错
对于删除字段的情况,可以随意输入一个value而不管字段的默认类型,可以实现删除,但是并不可取,具体原因可以参见South的实现机制(rollback到删除字段之前会失败)。杀手锏
如果South在同步数据库的过程中出现错误,则migrations目录下面对应此次更改的python文件不会被执行,可以运行python manage.py migrate --list查看没有执行的py文件,文件名前面没有*表示该文件对应的更改没有反应到数据库,只需删除掉这些有问题的migrate,参照错误提示修改 models再同步即可,也可以直接更改对应的py文件修复错误
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的更多相关文章
- Django Push HTTP Response to users
Django Push HTTP Response to users I currently have a very simple web application written in Django, ...
- Django Model field reference
===================== Model field reference ===================== .. module:: django.db.models.field ...
- django源码分析 python manage.py runserver
django是一个快速开发web应用的框架, 笔者也在django框架上开发不少web应用,闲来无事,就想探究一下django底层到底是如何实现的,本文记录了笔者对django源码的分析过程 I be ...
- Django集成Markdown编辑器【附源码】
专注内容写作的你一定不要错过markdown 简单介绍 markdown是一种标记语言,通过简单的标记语法可以使普通的文本内容具有一定的格式,使用非常简单,学习成本极低 目前各大Blog平台都已支持m ...
- Django 2.0.1 官方文档翻译: 文档目录 (Page 1)
Django documentation contents 翻译完成后会做标记. 文档按照官方提供的内容一页一页的进行翻译,有些内容涉及到其他节的内容,会慢慢补上.所有的翻译内容按自己的理解来写,尽量 ...
- django学习之- Cookie
cookie:客户端游览器上的一个文件,以键值对进行保存,类似字典{'k':'sfs'},与服务器端没有关系,当游览器访问服务器时候,服务器会生成一个随机字符串保存在cookie中返回给客户端,这样当 ...
- 异步任务队列Celery在Django中的使用
前段时间在Django Web平台开发中,碰到一些请求执行的任务时间较长(几分钟),为了加快用户的响应时间,因此决定采用异步任务的方式在后台执行这些任务.在同事的指引下接触了Celery这个异步任务队 ...
- 《Django By Example》第四章 中文 翻译 (个人学习,渣翻)
书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:祝大家新年快乐,这次带来<D ...
- django server之间通过remote user 相互调用
首先,场景是这样的:存在两个django web应用,并且两个应用存在一定的联系.某些情况下彼此需要获取对方的数据. 但是我们的应用肯经都会有对应的鉴权机制.不会让人家随随便便就访问的对吧.好比上车要 ...
随机推荐
- jquery 使用attr() 函数对复选框无效的原因
复选框是网站开发的时候经常用到的网页标签之一,常见的在页面上对复选框的操作包括取值和修改复选框的状态.在jquery中,常见的操作标签的值得函数为attr,然而在操作复选框的时候,通常采用的却是pr ...
- Opencv+MFC获取摄像头数据,显示在Picture控件
分为两步:OpenCV获取摄像头数据+图像在Picture上显示 第一步:OpenCV获取摄像头数据 参考:http://www.cnblogs.com/epirus/archive/2012/06/ ...
- 使用SLT工具从SAP导入数据到SAP HANA
在配置完备的情况下,SLT工具的Replicate 工作是在SAP HANA Data Provisioning中完成的 1. Log on to the SAP HANA Studio 2. Cal ...
- url地址数据转换成json数据格式
var urlToJson = function(){ var ret = {}; window.location.search.substr(1).replace(/(\w+)=(\w+)/ig, ...
- Linux Samba服务主配文件smb.conf中文详解
从网上找到描述比较详细的smb.conf中文解释: 服务名:smb 配置目录:/etc/sabma/ 主配置文件:/etc/sabma/smb.conf #====================== ...
- IE8下 Select文字垂直居中的办法
.select { padding: 4px 0; height: 30px; line-height: 26px; vertical-align: middle;} 处理前: 处理后:
- JAVA MONGODB group查询的UTC时间问题
BasicDBList dateList = new BasicDBList(); dateList.add("$t"); dateList.add(28800000); DBOb ...
- Java中新建子文件夹和新建文件
File file = new File("地址"); file.mkdirs(); //新建文件夹,当没有父文件夹时,但是不会自动创建父文件夹 file.mkdirs(); // ...
- HBase常见问题答疑解惑【持续更新中】
HBase常见问题答疑解惑[持续更新中] 本文对HBase开发及使用过程中遇到过的常见问题进行梳理总结,希望能解答新加入的HBaser们的一些疑惑. 1. HTable线程安全吗? HTable不是线 ...
- Arrar.prototype.map()的用法
---恢复内容开始--- map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组. array.map(callback[, thisArg]) 注:[]在语法中[]内的内 ...