新手学习Django,本文学习的文档是《Django Web开发指南》。好了我也是新手,没什么好说了,go!~

首先先确定环境,我是在linux(Ubuntu14.04 gnome)下。

自带python2.7.6

我是用mysql数据库,没有的请下载 sudo apt-get install mysql-server-5.5

接下来准备下载Django了,首先我是用sudo pip install Django==1.7.1(如果没有pip工具,请自行下载或则其他方式下载Django)。

下载完Django之后接着下载MySQL-python(貌似是python跟mysql进行交互的东西吧) pip install MySQL-python

#终端内进入python
>>>import django
>>>django.VERSION   #在python命令行中测试django是否成功安装

>>>import MySQLdb   #如果没有任何错误就是安装成功了

准备好了,接下来就是blog项目。

打开终端进入你要建立的项目下面

~tool/myproject $ django-admin.py startproject mysite  #建立一个Django的项目mysite

~tool/myproject $ cd mysite

~tool/myproject/mysite$ ls -l

总用量:24 (total:24)

-rwxr-xr-x 1 zrl zrl   249 12月 11 20:59 manage.py
drwxrwxr-x 2 zrl zrl  4096 12月 11 21:05 mysite

~tool/myproject/mysite$ ./manager.py runserver   #或者python manager.py runserver都可以

 

#如果出现下面的错误

You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.

 

#解决方法

python manage.py migrate   #它可以让我们在修改Model后可以在不影响现有数据的前提下重建表结构。

~/tool/microblog/mysite$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying sessions.0001_initial... OK

 

#最后在启动一下

~/tool/microblog/mysite$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
December 11, 2014 - 13:04:36
Django version 1.7.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

 

出现这个就成功啦~ Django快速学习搭建blog项目

接下来就是用manage.py创建这个blog app

~/tool/microblog/mysite$ ./manage.py startapp blog

~/tool/microblog/mysite$ ls -l blog/
总用量 20
-rw-r--r-- 1 zrl zrl   63 12月 12 17:55 admin.py
-rw-r--r-- 1 zrl zrl    0 12月 12 17:55 __init__.py
drwxrwxr-x 2 zrl zrl 4096 12月 12 17:55 migrations
-rw-r--r-- 1 zrl zrl   57 12月 12 17:55 models.py
-rw-r--r-- 1 zrl zrl   60 12月 12 17:55 tests.py
-rw-r--r-- 1 zrl zrl   63 12月 12 17:55 views.py

 

接着需要去setting.py文件中找到INSTALLED_APPS元组.把你的app以模块的形式添加到元组里,就像这样

INSTALLED_APPS=(

'blog',
)

 

然后去blog中,打开models.py 加入

class BlogPost(models.Model):
     title = models.CharField(max_length=150)
     body = models.TextField()
     timestamp = models.DateTimeField()

 

接着就是修改 settings.py文件,找到DATABASE

#连接一下数据库,我的是用mysql

 

DATABASES = {
      'default': {
          'ENGINE': 'django.db.backends.mysql',
          'NAME': 'djangodb',
          'HOST': 'localhost',
          'USER': 'root',
          'PASSWORD': 'password',
      }
  }

 

现在你可以告诉Django用你提供的连接信息去连接数据库并且设置应用程序所需的表。

命令很简单:./manage.py syncdb

~/tool/microblog/mysite$ ./manage.py syncdb
Operations to perform:
  Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying sessions.0001_initial... OK

You have installed Django's auth system, and don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'user'): username 账号
Email address: 123456789@163.com 邮箱
Password:            密码
Password (again):       再输入一次密码
Superuser created successfully.

上面这样就算成功了。。

打开blog中的models.py文件

  #添加以下的代码

from django.db import models
   from django.contrib import admin
  
   class BlogsPost(models.Model):
       title = models.CharField(max_length=150)
       body = models.TextField()
       timestamp = models.DateTimeField()
      
 admin.site.register(BlogsPost)

 

 
 继续重新输入./manage.py syncdb,如果出现

Operations to perform:
  Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
  No migrations to apply.
  Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
The following content types are stale and need to be deleted:

    blog | blogpost

Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.

    Type 'yes' to continue, or 'no' to cancel: yes

 

上面已经写了,要运行./manage.py makemigrations 然后再运行 ./manage.py migrate

然后继续 运行 ./manage.py syncdb

~/tool/microblog/mysite$ ./manage.py makemigrations
~/tool/microblog/mysite$ ./manage.py migrate
~/tool/microblog/mysite$ ./manage.py syncdb

接着就可以开启看看效果了

 Django快速学习搭建blog项目

貌似这效果看的不是很爽,我们来改改吧。打开blog下的models.py修改一下

  

from django.db import models
   from django.contrib import admin
  
   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)

 

从Django的角度看,一个页面具有三个典型的组件:

一个模板(template):模板负责把传递进来的信息显示出来。

一个视图(viw):视图负责从数据库获取需要显示的信息。

一个URL模式:它负责把收到的请求和你的试图函数匹配,有时候也会向视图传递一些参数。

打开mysite/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))

posts = BlogPost.objects.all() :获取数据库里面所拥有BlogPost对象

t = loader.get_template("archive.html"):加载模板

c = Context({'posts':posts}):模板的渲染的数据是有一个字典类的对象Context提供,这里的是一对键值对。

创建blog模板,在archive.html将for的块标签(block tag),{% .... %}添加进去

   {% for post in posts %}
       <h2>{{ post.title }}</h2>
       <p>{{ post.timestamp | date:"1,F jS"}}</p>
       <p>{{ post.body }}</p>
   {% endfor %}

 

创建一个URL模式,虽然可以在mysite/urls.py中创建所需的URL模式,不过这样会在项目和app之间制造混乱的耦合。

所以我们要将mysite/urls.py里有一行注释的示例几乎是我们所需要的代码。

url(r'^blog/', include('blog.urls')),

接着在blog下面创建一个urls.py,将一下代码写入

   from django.conf.urls import *
   from blog.views import archive
  
   urlpatterns = patterns('',
           url(r'^$',archive),
           )

来启动一下,看看效果如何 ./manage.py runserver

Django快速学习搭建blog项目

貌似看起来好搓。我们来稍微修改一下吧,看起来爽点。

接着在blog/templates下创建一个base.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>Just-so-so</h1>
        {% block content %}
        {% endblock %}
      </body>
</html>

 

再将blog/template下的archive.html的文件,引用base.html且和他的'content'块

{% extends "base.html" %}
  {% block content %}
      {% for post in posts %}
      <h2>{{  post.title }}</h2>
      <p>{{ post.timestamp | date:"1,F jS"}}</p>
      <p>{{ post.body }}</p>
      {% endfor %}
  {% endblock %}

 

再次刷新页面

Django快速学习搭建blog项目

终于完成了这个blog,虽然碰到了很多问题。但是学习到的东西还是很多的~