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应用,并且两个应用存在一定的联系.某些情况下彼此需要获取对方的数据. 但是我们的应用肯经都会有对应的鉴权机制.不会让人家随随便便就访问的对吧.好比上车要 ...
随机推荐
- JAVA的if用法,比如if(...){} 和if()没有大括号直接写下面的区别是什么
有大括号的时候 大括号里面所有的 都归if管.只有条件为真的时候 才会执行.没有大括号的时候 只有下面的一句归if管,也就是说 当只有一句的时候 大括号可以省略 其它的 没区别.
- .net 可枚举类型的构建方法
数组可以使用foreach遍历数组,其实只要实现GetEnumertor方法的类型都可以使用foreach结构遍历数组. 首先看下代码: //笔类 public class Pencil { publ ...
- Redis链表相关操作命令
lists链表类型lists类型就是一个双向链表,通过push,pop操作.从链表的头部或者尾部添加删除元素,这样list即可以作为栈也可以作为队列 lpush key value 在链表key的头部 ...
- mysql 分组按条件统计
百度经验 COUNT(CASE WHEN (S.rank = 1) THEN S.loanContractId END ) AS 'MZ', //根据loanContractId 分组,并统计ran ...
- python安装pip
pip类似RedHat里面的yum,安装Python包非常方便.本节详细介绍pip的安装.以及使用方法. 1.pip下载安装 1.1 pip下载 # wget "https://pypi.p ...
- linux和windows双系统时间错误解决方法
转自http://www.2cto.com/os/201204/126212.html windows时间会慢8小时,原因: 两个概念: UTC即Universal Time Coordinated, ...
- java 枚举类型和数据二进制等问题思考
.以下代码的输出结果是什么? int X=100; int Y=200; System.out.println("X+Y="+X+Y); System.out.println(X+ ...
- Java参数传递问题
参考资料:http://blog.sina.com.cn/s/blog_59ca2c2a0100qhjx.html http://blog.csdn.net/a412588063/article/ ...
- Okhttp设置http缓存,在没有网络的情况下加载http缓存里面的内容
HTTP_CACHE_FILENAME为缓存地址根路径: private final String HTTP_CACHE_FILENAME = "HttpCache"; priva ...
- Servlet综述
Servlet 是在服务器上运行的小程序.这个词是在 Java applet 的环境中创造的.虽然后者已很少被使用,但 servlet 却发展的很好.是一般面试都会常考的知识. 由来 servlet ...