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-nameif 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 -rfthen django will be uninstalled
Start Project
Create Project
django-admin.py startproject lwcshell 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应用,并且两个应用存在一定的联系.某些情况下彼此需要获取对方的数据. 但是我们的应用肯经都会有对应的鉴权机制.不会让人家随随便便就访问的对吧.好比上车要 ...
随机推荐
- hdu 1846 Brave Game 简单博弈
Problem Description 十年前读大学的时候,中国每年都要从国外引进一些电影大片,其中有一部电影就叫<勇敢者的游戏>(英文名称:Zathura),一直到现在,我依然对于电影中 ...
- 窗口、easyui-window、easyui-panel、easyui-linkbutton
//窗口 <script type="text/javascript" src="js/jquery.min.js"></script> ...
- 设计模式-GoF23
书呢,是2012年双11买的. 没有面向对象程序经验的人,果然还是看不懂的.
- 8、关于viewWithTag
1.viewWithTag检索tag的方法问题viewWithTag方法会对当前View和其子View进行搜索,查找符合tag的对象,但如果view和其多个子view中都含有相同tag值对象时,该方法 ...
- Jdk 1.8*安装并配置
转载自:http://www.cnblogs.com/zlslch/p/5658399.html 简单说下,jdk1.8*的下载,见http://www.cnblogs.com/zlslch/p/5 ...
- c++ inline关键字的理解
1. inline是实现修饰符,而非声明修饰符,所以应该用于实现部分的修饰(你也可以放置inline在声明,但是没有必要) 2. 所有中类中定义的函数都默认声明为inline函数,所有我们不用显示地去 ...
- FD.io vpp 框架转发图
在ip4-icmp-input 与 ip4-udp-input后可以注册后续的处理函数,ip4-icmp-input根据 icmp的报文类型选择相应的处理函数,而ip4-udp-input根据端口选择 ...
- python远程批量执行命令
#!/usr/bin/env python#-*- coding:utf-8 -*- from multiprocessing import Process,Poolimport time,param ...
- ModelDriven
功能: submit 之后显示结果 1.项目结构 2.web.xml <?xml version="1.0" encoding="UTF-8"?> ...
- L2-007. 家庭房产
L2-007. 家庭房产 题目链接:https://www.patest.cn/contests/gplt/L2-007 并查集 初学,看这题的时候完全没有什么好的想法,参考了@yinzm的blog用 ...