1:django-admin.py startproject mysit #mysite是名字
2:manage.py startapp blog
3:在settings.py的INSTALLED_APPS中添加,'mysite.blog'
4:在setitings.py中设置数据库:
DATABASES = {
'default': {
'ENGINE': 'sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'mysite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
5:models.py
from django.db import models
from django.contrib import admin
#class BlogPost(models.Model):
# title=models.CharField(max_length=150)
# body=models.TextField()
# timestamp=models.DateTimeField()
class BlogPost(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(BlogPost,BlogPostAdmin)
6:manage.py syncdb同步数据库
7:urls.py
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
注释去掉
8:接下来是视图views.py
# Create your views here.
from django.template import loader,Context
from django.http import HttpResponse
from mysite.blog.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))
archive.html内容如下:
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<h2>{{post.title}}</h2>
<p>{{post.timestamp}}<p>
<p>{{post.body}}<p>
{% endfor%}
{% endblock %}
base.html如下:
<html>
<style type="text/css">
body{ color: #efd; background:#453; padding: 0 5em; margin:0 }
h1{ padding:2em lem; background: #675 }
h2{ color: #bf8; border-top: lpx dotted #fff; margin-top:2em }
p{ margin: lem 0 }
</style>
<body>
<h1>mysite.example.com</h1>
{% block content %}
{% endblock %}
</body>
</html>
两个页面都放在templates文件夹下面
最后urls.py如下:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
#(r'^admin/', include(django.contrib.admin.urls)),
url(r'^blog/',include('mysite.blog.urls')),
)
blog目录下urls.py如下:
from django.conf.urls.defaults import *
from mysite.blog.views import archive
urlpatterns=patterns('',
url(r'^$',archive),
)
//这个archive对应视图里定义的archive
然后就可以跑起来了