pycharm+django搭建简单blog

0 工程环境

  • windows8.1
  • python2.7.8
  • django1.5

1 创建项目

方法一:命令行创建
django-admin.py startproject myweb
方法二:用pycharm这个IDE来创建
pycharm+django搭建简单blog_第1张图片

pycharm+django搭建简单blog_第2张图片

工程目录:
pycharm+django搭建简单blog_第3张图片
这里pycharm会自动创建模板目录tmplates,并且在settings.py文件中加入这个模板的相对路径,可以手动添加这个目录
在settings里面修改时区为Asia/Shanghai 语言为zh-cn

运行服务:
命令行
manage.py runserver 80
Validating models...


0 errors found
December 28, 2014 - 14:24:38
Django version 1.5.11, using settings 'myweb.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
也可以直接在pycharm里面点击运行,IDE自带的控制台与此显示相同,点击停止就停止服务器

2 创建应用

python manage.py startapp blog 
前面的python关键字可省
目录结构:
pycharm+django搭建简单blog_第4张图片

设置model
打开blog目录下的models.py
from django.db import models

# Create your models here.
class BlogsPost(models.Model):
    title=models.CharField(max_length=150)
    body=models.TextField()
    timestamp=models.DateTimeField()
创建BlogsPost类,继承django.db.models.Model父类,定义三个变量,title (博客标题),body(博客正文),timestamp(博客创建时间)
在settings 的APP选项里面加入blog

3 设置数据库

这里用sqlite3,简单小巧,设置settings文件数据库选项  'ENGINE': 'django.db.backends.sqlite3'   'NAME': 'mydb'   其他项对于sqlite3来说不用填
运行命令创建数据库:
D:\codetest\myweb>python manage.py sql blog
BEGIN;
CREATE TABLE "blog_blogspost" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(150) NOT NULL,
    "body" text NOT NULL,
    "timestamp" datetime NOT NULL
)
;

COMMIT;
可以看到自动添加了主键id
运行命令行同步:
D:\codetest\myweb>python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Creating table blog_blogspost

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'tashaxing'):
Email address:
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
邮箱可不填,用户名不填则默认是系统名

4 设置admin

注意在主站点目录的urls.py中将admin的那行解注释
# Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
并且在settings文件里的APP选项中解注释admin
 # Uncomment the next line to enable the admin:
    'django.contrib.admin',
再次打开myweb/blog/models.py 文件进行修改
from django.db import models
from django.contrib import admin

# Create your models here.
class BlogsPost(models.Model):
    title=models.CharField(max_length=150)
    body=models.TextField()
    timestamp=models.DateTimeField()

admin.site.register(BlogsPost)
官方文档中的方法是在blog目录下新建admin.py然后在里面注册,这里简化了这个步骤,直接写道models.py
修改了models.py之后要同步一下
python manage.py syncdb
启动服务器,在浏览器中输入127.0.0.1/admin,进入管理页面
pycharm+django搭建简单blog_第5张图片

添加博客
pycharm+django搭建简单blog_第6张图片

设置admin显示页面,以列表的形式显示博客标题和时间,在models.py中修改
from django.db import models
from django.contrib import admin

# Create your models here.
class BlogsPost(models.Model):
    title=models.CharField(max_length=150)
    body=models.TextField()
    timestamp=models.DateTimeField()

class BlogPostAdmin(admin.ModelAdmin):
    list_display = ('title','timestamp')

admin.site.register(BlogsPost,BlogPostAdmin)
修改后
pycharm+django搭建简单blog_第7张图片



5 创建template,view,URL

下面的内容就是创建blog的公共部分,模板,视图,url

在templates目录下创建archive.html
{% for post in posts %}
    <h2>{{ post.title }}</h2>
    <p>{{ post.timestamp }}</p>
    <p>{{ post.body }}</p>
{% endfor%}

创建视图views,打开blog目录下的views.py
from django.shortcuts import render
from django.template import loader,Context
from django.http import HttpResponse
from blog.models import BlogsPost

# Create your views here.
def archive(request):
    posts=BlogsPost.objects.all()
    t=loader.get_template('archive.html')
    c=Context({'posts':posts})
    return HttpResponse(t.render(c))


在主站点myweb目录下urls.py中修改
from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'myweb.views.home', name='home'),
    # url(r'^myweb/', include('myweb.foo.urls')),
    
    url(r'^blog/',include('blog.urls')),
    
    # Uncomment the admin/doc line below to enable admin documentation:
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)
在blog目录下创建urls.py文件,*号表示导入了很多模块比如:patterns, include, url
from django.conf.urls import *
from blog.views import archive

urlpatterns=patterns('',
            url(r'^$',archive),                            
             )

由于新增加了文件,要重启服务器,网页如下
pycharm+django搭建简单blog_第8张图片


6 添加样式

templates目下添加主模板base.html
<!DOCTYPE html>
<html>
<style type="text/css">
        body{color:#efd;background:#453;padding:0 5em;margin:0}
        h1{padding:2em 1em;background:#675}
        h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
        p{margin:1em 0}
      </style>
<body>
    <h1>踏莎行blog</h1>
    <h3>疏影横斜水清浅,暗香浮动月黄昏</h3>
    {% block content %}
    {% endblock %}
</body>
</html>

在archive.html中继承
<!DOCTYPE html>
<html>
<body>
{% extends "base.html" %}
  {% block content %}
      {% for post in posts %}
      <h2>{{  post.title }}</h2>
      <p>{{ post.timestamp }}</p>
      <p>{{ post.body }}</p>
      {% endfor %}
  {% endblock %}
</body>
</html>
更新博客页面
pycharm+django搭建简单blog_第9张图片

但是这样不是很爽,如果变成目录页和具体博客页两级网页多好。下面具体实现。

7 增加页面


views修改
from django.shortcuts import render
from django.template import loader,Context
from django.http import HttpResponse
from blog.models import BlogsPost

# Create your views here.
def index(request):
    posts=BlogsPost.objects.all()
    t=loader.get_template('bloglist.html')
    c=Context({'posts':posts})
    return HttpResponse(t.render(c))

def archive(request,blog_id):
    p=BlogsPost.objects.get(pk=blog_id)
    t=loader.get_template('archive.html')
    c=Context({'p':p})
    return HttpResponse(t.render(c))

blog/urls.py修改
from django.conf.urls import *
from blog.views import index,archive

urlpatterns=patterns('',
            url(r'^$',index),
            url(r'^(?P<blog_id>\d+)/$',archive)
             )

增加一个目录页模板bloglist.html
<!DOCTYPE html>
<html>
{% extends "base.html" %}
  {% block content %}
      {% for post in posts %}
      <h2><a href="/blog/{{ post.id }}" style="color:#00f0ff">{{ post.title }}</a></h2>
      {% endfor %}
  {% endblock %}
<body>

</body>
</html>

archive.html修改
<!DOCTYPE html>
<html>
<body>
{% extends "base.html" %}
  {% block content %}
      <h2>{{ p.title }}</h2>
      <p>{{ p.timestamp }}</p>
      <p>{{ p.body }}</p>
  {% endblock %}
</body>
</html>

完工后,最终工程目录:
pycharm+django搭建简单blog_第10张图片

这样,输入127.0.0.1/blog会进入目录页,点具体目录链接接到具体文章页,如:127.0.0.1/blog/2

pycharm+django搭建简单blog_第11张图片

后面还可以加主页,404页,加各种酷炫的css样式表,哈哈
源代码下载
CSDN:  myweb
github: myweb
ps:吐槽一下csdn的上传gif功能,必须在批量传图的地方传gif才有效,而且要勾上无水印,用编辑区的工具传图gif不动!!

你可能感兴趣的:(django)