用例來源Django官網的實例。
新建工程和應用
django-admin startproject my_project
python manage.py startapp news
建立數據庫表
from django.db import models
# Create your models here.
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
def __str__(self): # __unicode__ on Python 2
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self): # __unicode__ on Python 2
return self.headline
添加 admin 接口
from django.contrib import admin
# Register your models here.
from .models import Article
class newsAdmin(admin.ModelAdmin):
list_display = ('headline' , 'pub_date' )
admin.site.register(Article,newsAdmin)
#admin.site.register(models.Article)
使用用例內部的urls
django模版是不提供用例內部的urls文件的,所以需要新建。
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/$', views.all_archive),
url(r'^articles/([0-9]{4})/$', views.year_archive),
#url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
#url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]
工程裏的urls.py 增加:
url(r'^articles/', include('news.urls')),
這時鏈接示範爲:http://127.0.0.1:9999/articles/articles/2016/
設計視圖文件
這裏比官網多定義了一個示範頁面。
http://127.0.0.1:9999/articles/articles/
http://127.0.0.1:9999/articles/articles/2016/
這個python文件還用到了模版html文件。所以需要配置工程的settings.py--》TEMPLATES-》DIR
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from .models import Article
def all_archive(request):
return HttpResponse('<h1> a_list </h1>')
def year_archive(request, year):
a_list = Article.objects.filter(pub_date__year=year)
context = {'year': year, 'article_list': a_list}
return render(request, 'year_archive.html', context)
html 模版
my_project/templates/year_archive.html
{% extends "base.html" %}
{% block title %}Articles for {{ year }}{% endblock %}
{% block content %}
<h1>Articles for {{ year }}</h1>
{% for article in article_list %}
<p>{{ article.headline }}</p>
<p>By {{ article.reporter.full_name }}</p>
<p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %}
{% endblock %}
my_project/templates/base.html
{% load staticfiles %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<img src="{% static "images/sitelogo.png" %}" alt="Logo" />
{% block content %}{% endblock %}
</body>
</html>
測試:
python manage.py runserver 0.0.0.0:9999