您的位置:首页 > 编程语言 > Go语言

django1.7 配置demo教程(环境搭建)

2014-10-29 15:27 351 查看
近期又用到django做个简单项目,1年多没用过了有些手生,按理说没啥问题吧

以下是一个简单的环境搭建demo过程:

前提条件:准备了python2.7已经安装

1、搭建django环境
下载 https://bootstrap.pypa.io/ez_setup.py
保存本地
运行 python ez_setup.py

2、安装pip
C:\Python27\Scripts>easy_install.exe pip

3、安装diango
pip install Django==1.7

3、创建Django project
C:\Python27\Lib\site-packages\django\bin\django-admin.py startproject bluescf

4、在工程文件夹下运行python manage.py runserver
打开浏览器:http://127.0.0.1:8000/

5、创建一个app+模型
python manage.py startapp demosite
注意:默认已经创建了一个 bluescf的app

6、加入�模板的路径
settings.py 加入�以下代码

import os.path

TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)



7、在templates加入� html文件,暂停:index.html

8、创建views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
#return HttpResponse("Hello, world. You're at the poll index.")
def index(request):
# View code here...
t = loader.get_template('index.html')
c = RequestContext(request, {'foo': 'bar'})
return HttpResponse(t.render(c),
content_type="application/xhtml+xml")

9、配置 urls.py

#coding=utf-8
from django.conf.urls import patterns, include, url
from django.contrib import admin
import views

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'bluescf.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),

url(r'^admin/', include(admin.site.urls)),

url(r'^$', views.index, name='home'),#默认直接进入views的index方法
)


10、打开浏览器:http://127.0.0.1:8000/ 预览效果,一切正常说明就ok了。

事实上我的views.py里的index方法 一開始不是这样子写得,原来写法:

def index(request):
return render_to_response('index.html')

结果报错了,



千万不用去百度和google搜索 __init__() got an unexpected keyword argument 'mimetype' ,无用的,会出来一堆无用的信息,搜出我这篇文章算是你的福气,^_^。

这样的问题明显就是api升级了用的老的写法(django1.3之前我都这样写)
所以须要我们好好查api:http://django.readthedocs.org/en/latest/topics/http/shortcuts.html#django.shortcuts.render_to_response


看到这就没有问题了吗?

事实上还是有问题的,

def index(request):
# View code here...
t = loader.get_template('index.html')
c = RequestContext(request, {'foo': 'bar'})
return HttpResponse(t.render(c),
content_type="text/xml")


事实上假设你的index.html 里仅仅是写了字符串或者不是完整的html(你肯定会用到一些template的继承),或者你的 content_type="
application/xhtml+xml
"奥,那就太不幸了,会提示你:

This page contains the following errors:

error on line 9 at column 1: Extra content at the end of the document

Below is a rendering of the page up to the first error.

事实上这个就是django依据content_type去解析你的html页面,具体的不深入研究,仅仅须要改为: content_type="text/html" ,就能正常显示html。

别到处乱抄网上的样例,知道一些细节非常重要的。

有什么问题,大家能够跟我交流(CSDN技术群QQ群:221057495)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐