from mysite.blog.models import BlogPost
node2:/app/mysite/blog#cat models.py
from django.db import models
from django.contrib import admin
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length = 150)
body = models.TextField()
timestamp = models.DateTimeField()
class Meta:
ordering =('-timestamp',)
class BlogPostAdmin(admin.ModelAdmin):
list_display = ('title','timestamp')
admin.site.register(BlogPost,BlogPostAdmin)
BlogPost 继承了class BlogPost(models.Model)类,
我们就获得了Django对象关系映射的全部里拉。
node2:/usr/local/lib/python2.7/site-packages/django#ls
apps contrib dispatch __init__.py __main__.pyc shortcuts.pyc test views
bin core forms __init__.pyc middleware template urls
conf db http __main__.py shortcuts.py templatetags utils
node2:/usr/local/lib/python2.7/site-packages/django#
node2:/app/mysite/blog#cat view.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# from django.shortcuts import render, render_to_response
from .models import *
# Create your views here.
from django.http import HttpResponse
from django.template import loader
def index(req):
# get all blogpost objects
blog_list = BlogPost.objects.all()
print blog_list
template = loader.get_template('index.html')
context = {
'blog_list':blog_list
}
return HttpResponse(template.render(context, req))
node2:/app/mysite/blog#
def index(req): 第5行每个Django视图函数都将django.http.HttpRequest对象作为它的第一个参数。
blog_list = BlogPost.objects.all() 当我们把BlogPost类作为django.model.Model的一个子类时,
我们就获得了Django对象关系映射的全部里拉。
template = loader.get_template('index.html')
这里我们只需告诉Django模板的名字就能创建模板对象template
因为我们把它保存在app下的templates目录里,Django无需更多指示就能找到它。
node2:/app/mysite/blog/templates#cat index.html
{% extends "base.html" %}
{% block content %}
{% for post in blog_list %}
<h2>{{ post.title }}</h2>
<p>{{ post.timestamp | date:"1,F jS"}}</p>
<p>{{ post.body }}</p>
{% endfor %}
{% endblock %}