首页 > 技术文章 > django开发笔记(一)

lqxy 2014-04-09 19:20 原文

 

开发环境配置

操作系统win8.1,64bit

开发环境:python 3.4.1+pycharm 3.1+django 1.6.2,安装配置如下

1、下载windows下的msi3.4.1,64位  python安装件,按照提示一路ok安装,安装完毕后在环境变量path中添加python的安装路径  C:\Python34,在cmd命令行下运行python命令,显示python版本信息说明python安装成功

2、下载pycharm,一路按照提示安装即可,安装完成后,提示激活

用户名:yueting3527

注册码:
===== LICENSE BEGIN =====
93347-12042010
00001FMHemWIs"6wozMZnat3IgXKXJ
2!nV2I6kSO48hgGLa9JNgjQ5oKz1Us
FFR8k"nGzJHzjQT6IBG!1fbQZn9!Vi
===== LICENSE END =====

输入,激活即可。创建django程序,提醒没有python解释器,按照提示选择本机安装python路径下的python.exe,等加载完毕,点击ok即可。

3、下载django1.6.2,解压缩,在路径.../django1.6.2下,打开cmd,输入python setup.py install,等待安装完毕。配置django环境变量。

在path中添加C:\Python34\Lib\site-packages\django\bin,以及C:\Python27\Scripts。

 

完成1.2.3步骤之后,环境变量配置完毕。cmd命令行启动效果如下图所示:

说明django+python环境配置成功。启动浏览器,输入http:\\127.0.0.1:8000显示如下图所示:

 

在pycharm中创建django项目如下步骤

1、在pycharm创建新项目,项目类型选择django,项目名称写time_test,application名称写show_time,工程目录如下图所示:

2、view是接收web请求返回web响应的python函数,打开创建时建立的views.py,填写如下代码:

 

#coding=utf-8
from django.shortcuts import render
from django.http import HttpResponse
import datetime


# Create your views here.
def current_datetime(request):

    now = datetime.datetime.now()

    html = "<html><body>It is now time %s.</body></html>" %now

    return HttpResponse(html)

每个视图函数都用HttpRequest对象作为参数,这里用的是request

3、URL映射

打开创建时建立的urls.py,填写如下代码:

 

from django.conf.urls import patterns, include, url
from test_time.views import current_datetime

from django.contrib import admin
admin.autodiscover()

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

    url(r'^time/$', current_datetime),
    #url(r'^admin/', include(admin.site.urls)),
)

首先,我们从模块中引入了 current_datetime 视图。接着,我们加入了 (r'^time/$', current_datetime), 这一行。该行就是所谓的 URLpattern ,它是一个 Python 元组,其第一个元素是简单的正则表达式,第二个元素是为该模式应用的视图函数。简单来说,我们只是告诉 Django,所有指向 URL /time/ 的请求都应由 current_datetime 这个视图函数来处理。

4、运行

在pycharm中点击运行按钮,选择运行项目,在pycharm中显示如下图所示:


说明启动成功,在浏览器中输入http://127.0.0.1:8000/time(此处的time是url定义中正则表达式  r'^time/$'  定义的,可以自己修改)显示如下图所示:

 

 

至此,一个初始新手开发python+django+pycharm的web开发环境就搭建好了。下面,就开始我们的charming之旅了。

 

PS:under linux os, it is no need to config the environment var "path". After the installion of django, under the command window type:python, and then "import django", and then "django.VERSION", if there is output about the version information of django, that means your django environment is ok. Your can enjoy the fun of python+django+pycharm.(This is tested under Linux Mint 15, python 2.7.5+, pycharm 3.1).

 

 

 

推荐阅读