django-简单blog

壤驷喜
2023-12-01
创建项目 admin-django.py startproject mysite


创建应用 manage.py startproject blog


在settings中添加INSTALLED_APPS   'mysite.blog'


设计Model

from django.db import models

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


设计数据库


manage.py syncdb


设置admin应用

settings.py   INSTALLED_APPS   ‘django.contrib.admin'

manage.py syncdb


设置url

(r'^admin/',include(admin.site.urls))


admin加载Model

from django.db import models
from django.contrib import admin

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

    class Meta:
        odering=('-timestamp',)

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

admin.site.register(BlogPost,BlogPostAdmin)

建立blog主体

URLconf

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

在blog中新建urls.py

from django.conf.urls.defaults import *
from mysite.blog.views import archive

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

创建模板

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>mysite.example.com<h1>
{% block content %}
{% endblock %}
</body>
</html>

archive.html

{% extends 'base.html' %}
{% block content %}
{% for post in posts %}
<h2>{{post.title}}</h2>
<p>{{post.timestamp|date}}</p>
<p>{{post.body}}</p>
{% endfor %}
{% endblock %}

视图 views.py

from django.shortcuts import render_to_response
from mysite.blog.models import BlogPost

def archive(req):
    posts = BlogPost.objects.all()
    return render_to_response('archive.html',{'posts':posts})


启动服务器 manage.py runserver





 类似资料: