使用eclipse创建一个django项目

打开settings.py添加:

STATIC_ROOT = os.path.join(os.path.dirname(__file__),'static')
STATICFILES_DIRS = (
    ('css',os.path.join(STATIC_ROOT,'css').replace('\\','/') ),  
    ('js',os.path.join(STATIC_ROOT,'js').replace('\\','/') ), 
    ('p_w_picpaths',os.path.join(STATIC_ROOT,'p_w_picpaths').replace('\\','/') ), 
    ('upload',os.path.join(STATIC_ROOT,'upload').replace('\\','/') ), 
)
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
UPLOAD_DIRS = (
    os.path.join(os.path.dirname(__file__), 'upload').replace('\\','/'),
)


在项目下创建 templates ,static,upload目录,结构如图


django项目流程_项目


在项目下创建view.py输入:

from django.shortcuts import render_to_response
def main_index(request):
    return render_to_response('index.html', {})

打开urls.py 配置URL:

url(r'^$',main_index),


在templates目录下创建index.html

css,js,p_w_picpaths等调用写成:

<link rel="stylesheet" type="text/css" href="/static/css/easyui.css">
<script type="text/javascript" src="/static/js/jquery.min.1.8.2.js"></script>
.cs-north-bg {
width: 100%;
height: 100%;
background: url(/static/p_w_picpaths/header_bg.png) repeat-x;
}

其他html访问以此类推



mysql数据库访问:(mysqlTool已经安装的,没安装请百度)并且存在数据库

设置如下:打开settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'py_zsh',                      
        'USER': 'root',                       
        'PASSWORD': '',                   
        'HOST': '127.0.0.1',                           
        'PORT': '3306',                           
#         'OPTIONS': {
#             'autocommit': True,
#         },
    }
}

#在最后添加你的项目
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'py_zsh',
)


项目下创建:models.py

#coding=utf-8
from django.db import models

#用户表
class Users(models.Model):
    username = models.CharField(max_length=50) #用户名
    password = models.CharField(max_length=50)  #密码
    type = models.CharField(max_length=10)  #类型

使用命令行或者eclipse 下的带参数运行方式运行manage.py :

命令:python manage.py syncdb

系统自动创建该表



当设置上传表单时候会提示如下错误:

Forbidden (403)

CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.


设置如下:打开settings.py:

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
#     'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

井号注释掉即可


上传excel文件到upload目录:

#coding=utf-8
from django.shortcuts import render_to_response
import py_zsh.settings
from datetime import datetime
import time
def index(request):
    if request.method=="GET":
        return render_to_response('doc/index.html', {})
    else:
        try:
            data = request.POST
            datafile = request.FILES.get('file_stu', None)
            #/*判别是不是.xls文件,判别是不是excel文件*/   
            file_types = datafile.name.split('.')
            file_type = file_types[len(file_types) - 1]; 
            print file_type
            if file_type.lower()  != "xlsx" and file_type.lower()!= "xls": 
                return render_to_response('error.html', {"message":"请上传格式正确的excel文件"})
            file = handle_uploaded_file(datafile)
            return render_to_response('main.html', {})
        except:
            return render_to_response('error.html', {})
#表单提交后写入文件
def handle_uploaded_file(f):
    filename = py_zsh.settings.UPLOAD_DIRS[0]+"\\".replace('\\','/')+time.strftime('%Y%m%d%H%M%S')+f.name
    with open(filename, 'wb+') as info:
        for chunk in f.chunks():
            info.write(chunk)
    return filename