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

来源:互联网 发布:免费最新看电影的软件 编辑:程序博客网 时间:2024/04/30 07:56

最近又用到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 HttpResponsefrom django.shortcuts import render_to_responsefrom 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, urlfrom django.contrib import adminimport viewsurlpatterns = 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)。

1 0