首先创建一个project:
django-admin startproject webblog
然后进入webblog目录,修改settings.py:
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'webblog.db'
使用下面的命令创建一个app:
manage.py startapp blog
进入blog目录,修改models.py:
class Reporter(models.Model):
full_name = models.CharField(maxlength=70)
def __str__(self):
return self.full_name
class Admin:
pass
class Article(models.Model):
pub_date = models.DateTimeField()
headline = models.CharField(maxlength=200)
article = models.TextField()
reporter = models.ForeignKey(Reporter)
def __str__(self):
return self.headline
class Admin:
pass
修改view.py:
from webblog.blog.models import *
from django.shortcuts import render_to_response
from django.template import Context, loader
from django.http import HttpResponse
def index(request):
article_list = Article.objects.all()
return render_to_response('htmls/index.html', {'article_list': article_list})
返回去修改setting.py,把新创建的app和模板加进去:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"d:/webblog/",
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'webblog.blog',
'django.contrib.admin',
)
在weblog目录下,执行:
manage.py syncdb
在webblog目录下创建htmls目录,进入该目录,创建index.html:
{% extends "base.html" %}
{% block title %}Articles{% endblock %}
{% block content %}
<h1>Articles</h1>
{% for article in article_list %}
<p>Headline : {{ article.headline }}</p>
<p>By {{ article.reporter.full_name }}</p>
<p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %}
{% endblock %}
创建base.html:
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
修改url.py,将访问地址加入进去:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^$','blog.views.index'),
(r'^admin/', include('django.contrib.admin.urls')),
)
现在,整个博客系统已经配置完毕,我们可以使用
manage.py runserver
来启动服务器了,在地址栏里输入:
就可以访问博客了~
当然,一开始进去的时候什么资料都没有,我们需要在管理界面里输入一些数据来显示,地址为
用户名和密码为你在syncdb时设置的,进去后加入一条记录即可~~~
至此,一个简单的博客系统已经开发完成,相信不比RoR的十分钟写个博客系统要复杂多少。
欢迎大家和我讨论Django技术~