一、配置开发环境
我的开发环境是:Python2.7.9 + Django1.8 + Eclipse
1、安装Python
下载地址:http://www.python.org/getit/
安装完成后为了方便可以配置下环境变量:
2、安装Django—Python下用于开发网站的比较流行的web框架
下载地址:https://www.djangoproject.com/download/
下载完成后解压,在dos下进入解压后的文件目录,运行命令:
setup.py install
该过程有点漫长,请耐心等待。
3、安装Eclipse的Python插件PyDev
Eclipse下执行Help—Install New Software...,输入网址:http://update-production-pydev.s3.amazonaws.com/pydev/updates/site.xml
安装成功后在Windows—Preferences中进行配置,添加Python解释器
如果在新建工程中有PyDev这一项则表示安装成功:
二、用Python+Django在Eclipse环境下开发自己的网站
1.新建Django项目
选择sqlite数据库
2.创建网站模块app
3.测试新建的模块是否正常
服务器启动起来后,去浏览器输入网址:http://127.0.0.1:8000/admin
4.编辑代码
4.1修改 MyBlog.models.py
from django.db import models
from django.contrib import admin
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length = 150)
content = models.TextField()
timestamp = models.DateTimeField()
class BlogPostAdmin(admin.ModelAdmin):
list_display = ('title', 'content', 'timestamp')
admin.site.register(BlogPost, BlogPostAdmin)
4.2修改 MyBlog.views.py
# Create your views here.
from django.template import loader,Context
from django.http import HttpResponse
from MyBlog.models import BlogPost
def archive(request):
posts = BlogPost.objects.all()
t = loader.get_template('archive.html')
c = Context({'posts': posts})
return HttpResponse(t.render(c))
4.3 修改MySite.setting.py,找到下面部分进行修改
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyBlog',
)
4.4 修改MySite.urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from MyBlog.views import *
urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^MyBlog/$', archive),
)
5.建立样式网页模板
** 请在包MyBlog下添加templates文件夹,并在templates下建立两个网页文件:archive.html和base.html **
5.1 编辑archive.html
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<h1>{{ post.title}}</h1>
<p>{{ post.content }}</p>
<p>{{ post.timestamp|date:"1, F jS"}}</p>
{% endfor %}
{% endblock %}
5.2 编辑base.html
<html>
<style type="text/css">
body { color: #edf; background: #453; padding: 0 5em; margin:0 }
h1 { padding: 2em lem; background:#675 }
h2 { color: #bf8; border-top: 1px dotted #fff; margin-top: 2em }
p { margin: lem 0 }
</style>
<body>
<h1><center>Alexia's Blog</center></h1>
{% block content %}
{% endblock %}
</body>
</html>
6.同步数据库
6.1 创建超级用户
6.2 同步数据库
7.运行测试
登陆界面,登陆账号和密码是** 创建超级用户 **的时候设定的。