這是《Django Web開發指南》中的最後一個實例。若是說上一個實例Liveblog重點講的是Django和Ajax的協做,那麼咱們在Pastebin中,將學習到Django和高亮語法JS的協做,順便複習一下在Django中加入表單。javascript
1.建立項目和應用css
咱們先來建立本實例的項目,在dos命令提示符下轉到Scripts文件夾(如「c:\python32\Scripts」),而後運行以下命令:html
$ django-admin startproject pastebinproject
而後在dos命令提示符下繼續輸入以下命令,進入項目文件夾:java
cd pastebinproject
接下來開始建立應用,在dos命令提示符下輸入命令:python
$ python manage.py startapp pastebin
命令執行完後,項目根文件夾下會出現一個叫pastebin的文件夾,應用建立完畢。數據庫
2.創建模型 django
編輯pastebin/models.py文件,改爲下面這樣:瀏覽器
pastebin/models.py:服務器
import datetime from django.db import models from django.db.models import permalink class Paste(models.Model): """A single pastebin item""" SYNTAX_CHOICES = ( (0, "Plain"), (1, "Python"), (2, "HTML"), (3, "SQL"), (4, "Javascript"), (5, "CSS"), ) content = models.TextField() title = models.CharField(blank=True, max_length=30) syntax = models.IntegerField(max_length=30, choices=SYNTAX_CHOICES, default=0) poster = models.CharField(blank=True, max_length=30) timestamp = models.DateTimeField(auto_now_add=True, blank=True) class Meta: ordering = ('-timestamp',) def __str__(self): return "%s (%s)" % (self.title or "#%s" % self.id, self.get_syntax_display()) @permalink def get_absolute_url(self): return ('paste_detail', None, {'pk': self.id})
首先修改pastebinproject/settings.py這個文件,找到INSTALLED_APPS這段設置,把它改爲下面這個樣子:session
pastebinproject/settings.py:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pastebin', )
編輯settings.py的時候,建議順便修改一下語言和時區的設置,具體的方法請參考:《實戰Django:官方實例Part1》
而後在dos命令提示符下運行以下命令:
$ python manage.py makemigrations pastebin
繼續在dos命令提示符下運行命令:
$ python manage.py migrate
這樣,數據庫就建好了。
4.建立管理員帳號在dos命令提示符下運行以下命令:
$ python manage.py createsuperuser
而後依次輸入admin,你的郵箱,輸入兩次密碼,完成建立管理員的操做。
5.在管理界面註冊應用編輯pastebin/admin.py 文件,讓它變成下面這個樣子:
pastebin/admin.py:
from django.contrib import admin from pastebin.models import Paste class PasteAdmin(admin.ModelAdmin): list_display = ('__str__', 'title', 'poster', 'syntax', 'timestamp') list_filter = ('timestamp', 'syntax') admin.site.register(Paste, PasteAdmin)
6.啓動服務器
在dos命令提示符下運行以下命令:
$ python manage.py runserver
http://127.0.0.1:8000/admin/
而後輸入你剛纔建立的管理員帳號和密碼,登陸管理界面,你能夠先嚐試添加一些東西,或者,什麼都不作。
7.建立表單咱們但願訪問者能夠直接在頁面上粘貼他們的代碼,下面咱們來建立一個表單,實現這個功能。
在pastebin下建立forms.py文件,添加下面的內容:
pastebin/forms.py:
from django import forms from pastebin.models import Paste class PasteForm(forms.ModelForm): class Meta: model = Paste fields = ('title', 'poster', 'syntax', 'content')
咱們這裏用了一個ModelForm,它能夠直接繼承咱們的Paste模型,只要告訴它,咱們須要用到哪些字段就行。
8.編寫視圖接下來咱們開始編寫視圖,
編輯pastebin/views.py 文件,添加下面的內容:
pastebin/views.py:
from django.template import RequestContext from django.shortcuts import render_to_response from django.views import generic from pastebin.models import Paste from pastebin.forms import PasteForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class IndexView(generic.ListView): model = Paste template_name = 'pastebin/paste_list.html' class DetailView(generic.DetailView): model = Paste template_name = 'pastebin/paste_detail.html' def create_info(request): context = RequestContext(request) if request.method == 'POST': form = PasteForm(request.POST) if form.is_valid(): form.save(commit=True) success_url = reverse('pastebin:display_info') return HttpResponseRedirect(success_url) else: print (form.errors) else: form = PasteForm() return render_to_response('pastebin/paste_form.html', {'form': form}, context)
前兩個視圖咱們仍然使用通用視圖,通用視圖勝在簡單,只要指定一下模型和模板名稱就能夠了。
注意create_info這個視圖,在這裏,咱們們將request.POST數據(就是訪問者在表單中提交上來的數據)交給PasteForm來處理,PasteForm會作一個儲存動做,而後跳轉到success_url,還記得咱們在前面的實例中學過的reverse函數嗎?它能夠將它能夠將'pastebin:display_info'轉換成首頁的連接,你也能夠嘗試修改爲功提交表單後跳轉的連接。
9.編寫模板
首先建立模板文件夾,在pastebin文件夾下創建templates文件夾,而後在templates下再建一個pastebin文件夾。
隨後咱們在這個文件夾下建立base.html文件,這個base.html文件的正確路徑應該是:
pastebin/templates/pastebin/base.html
編輯base.html文件,加入以下內容:
pastebin/templates/pastebin/base.html:’'
<html> <head> <title>{% block title %}{% endblock %}</title> <style type="text/css"> body { padding: 0 2em; font-family: Microsoft Yahei,sans-serif; background: #fff; } h1 { background: #255074; padding: 1 0.8em; margin: 0; color:#fefefe; } h2 { background: #3776AB; padding: 8 1em; margin: 0; color:#E9D143; } h4 { background: #1E2933; padding: 1 1.5em; margin: 0; color:#fefefe;} p { background: #3776AB; padding: 8 2em; margin: 0; color:#fefefe; font-size:12px; } p a { text-decoration: none; color: #fefefe; } pre { padding: 20px; background: #ddd; } li { padding: 5 0em; background: #fff; } form { padding: 5 2em; font-size:12px; background: #fff; } </style> </head> <body> <h4>Pastebin</h4> <p><a href="{% url 'pastebin:create_info' %}">新增</a> • <a href="{% url 'pastebin:display_info' %}">列出所有</a></p> {% block content %}{% endblock %} </body> </html>
接下來咱們要從這個base.html模板擴展出三個模板,先建立paste_list.html文件,添加如下內容:
pastebin/templates/pastebin/paste_list.html:
{% extends "pastebin/base.html" %} {% block title %}最近粘帖{% endblock %} {% block content %} <h2>最近粘帖</h2> <ul> {% for object in object_list %} <li><a href="{% url 'pastebin:paste_detail' object.id %}">` object `</a></li> {% endfor %} </ul> {% endblock %}
建立paste_detail.html文件,添加如下內容:
pastebin/templates/pastebin/paste_detail.html:
{% extends "pastebin/base.html" %} {% load staticfiles %} {% block title %}` object `{% endblock %} {% block content %} <h2>` object `</h2> <p>語言: ` object`.`get_syntax_display `<br> 日期: {{ object.timestamp|date:"r" }}</p> <code><pre name="code" class="brush: {{ object.get_syntax_display|lower }}"> ` object`.`content `</pre></code> <script language="javascript" src="{% static 'js/shCore.js' %}"></script> <script language="javascript" src="{% static 'js/shBrushPlain.js' %}"></script>
<script language="javascript" src="{% static 'js/shBrushPython.js' %}"></script>
<script language="javascript" src="{% static 'js/shBrushXml.js' %}"></script> <script language="javascript" src="{% static 'js/shBrushJscript.js' %}"></script> <script language="javascript" src="{% static 'js/shBrushSql.js' %}"></script> <script language="javascript" src="{% static 'js/shBrushCss.js' %}"></script> <link type="text/css" rel="stylesheet" href="{% static 'css/shCore.css' %}"></link> <link type="text/css" rel="stylesheet" href="{% static 'css/shThemeDefault.css' %}"></link> <script type="text/javascript"> SyntaxHighlighter.config.clipboardSwf = "{% static 'js/clipboard.swf' %}"; SyntaxHighlighter.all(); </script> {% endblock %}
咱們在上面這個模板中加入了顯示代碼高亮的腳本,注意這一行:
<prename="code" class="brush: {{ object.get_syntax_display|lower }}">
` object`.`content `</pre>
」brush」後面的「{{ object.get_syntax_display|lower }}」實質上就是咱們在models.py中「SYNTAX_CHOICES」的一項內容,好比css、python等。咱們使用了一個叫Syntax Highlighter的代碼着色工具,應用起來很是簡單,分紅三步:
呆會咱們再詳細講Syntax Highliter相關的設置。
最後建立paste_form.html文件,添加如下內容:
pastebin/templates/pastebin/paste_form.html:
{% extends "pastebin/base.html" %} {% block title %}新增{% endblock %} {% block content %} <h2>隨心貼</h2> <form action="" method="POST"> <span class="form"> 標題: ` form`.`title `<br> 做者: ` form`.`poster `<br> 語言: ` form`.`syntax `<br> ` form`.`content `<br> <input type="submit" name="submit" value="粘貼" id="submit"> </span> </form> {% endblock %}
10.Syntax Highlighter
先下載Syntax Highlighter,下載地址:Synatax Highlighter 2.1..364.或者,你也能夠直接在本文的末尾下載實例的源代碼。
下載後,先解壓.而後在咱們的項目根文件夾下建立一個static文件夾,再在static下建立pastebin,在pastebin下分別建立css和js文件夾,其文件夾的結構象下面這樣:
pastebinproject/ manage.py pastebinproject/ pastebin/ static/ pastebin/ css/ js/
將Syntax Highlighter中的scripts下的文件複製到js文件夾下,將styles文件夾下的文件複製到css文件夾下。
注意:能夠只複製咱們在paste_detail用到的.js和.css文件。
作完上述工做後,咱們須要修改一下設置文件,編輯settings.py文件,在文件末尾加入以下內容:
pastebinproject/settings.py:
STATIC_PATH = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( STATIC_PATH, )
STATIC_PATH指明瞭static這個文件夾的絕對路徑,這裏的BASE_DIR就是咱們的項目根文件夾。
STATICFILES_DIRS旨在告訴Django,能夠從哪些文件夾中去搜索靜態文件。
設置完後,咱們能夠在瀏覽器地址欄中輸入以下內容:
若能看到文件的內容(而非錯誤提示),則表示靜態文件的設置生效了。
11.設計URL
在pastebin文件夾下建立一個叫url.py的文件,而後添加以下內容:
pastebin/urls.py :
from django.conf.urls import patterns, include, url from pastebin import views urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='display_info'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='paste_detail'), url(r'^add/$', views.create_info, name='create_info'), )
編輯pastebinproject/urls.py 文件,讓它變成下面這樣:
lpastebinproject/urls.py :
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^paste/', include('pastebin.urls', namespace="pastebin")), )
如今什麼都沒有,讓咱們點擊上方的「新增」連接來加入一些內容:
輸入完後點擊「粘貼」按鈕,會跳轉回首頁:
點擊「Pastebin的css(CSS)」這個連接,看一下效果:
看到了吧?咱們的代碼已經被着上了相應的顏色。你也能夠嘗試粘貼一些其它類型的代碼。
附:本實例源代碼下載地址:捨得學苑下載中心
【The End】