藉助富文本編輯器,網站的編輯人員可以像使用offfice同樣編寫出漂亮的、所見即所得的頁面。此處以tinymce爲例,其它富文本編輯器的使用也是相似的。 在虛擬環境中安裝包。 pip install django-tinymce==2.6.0 安裝完成後,可使用在Admin管理中,也能夠自定義表單使用。 示例 1)在test6/settings.py中爲INSTALLED_APPS添加編輯器應用。 INSTALLED_APPS = ( ... 'tinymce', ) 2)在test6/settings.py中添加編輯器配置。 TINYMCE_DEFAULT_CONFIG = { 'theme': 'advanced', 'width': 600, 'height': 400, } 3)在test6/urls.py中配置編輯器url。 urlpatterns = [ ... url(r'^tinymce/', include('tinymce.urls')), ] 接下來介紹在Admin頁面、自定義表單頁面的使用方式。
from django.db import models from tinymce.models import HTMLField class GoodsInfo(models.Model): gcontent=HTMLField()
python manage.py makemigrations
3)執行遷移。javascript
python manage.py migrate
4)在本示例中沒有定義其它的模型類,可是數據庫中有這些表,提示是否刪除,輸入no後回車,表示不刪除,由於其它的示例中須要使用這些表。html
5)遷移完成,新開終端,鏈接mysql,使用test2數據庫,查看錶以下:java
6)發現並無表GoodsInfo,解決辦法是刪除遷移表中關於booktest應用的數據。python
delete from django_migrations where app='booktest';
7)再次執行遷移。mysql
python manage.py migrate
成功完成遷移,記得不刪除no。redis
8)在booktest/admin.py中註冊模型類GoodsInfosql
from django.contrib import admin from booktest.models import * class GoodsInfoAdmin(admin.ModelAdmin): list_display = ['id'] admin.site.register(GoodsInfo,GoodsInfoAdmin)
9)運行服務器,進入admin後臺管理,點擊GoodsInfo的添加,效果以下圖數據庫
在編輯器中編輯內容後保存。django
def editor(request): return render(request, 'booktest/editor.html')
2)在booktest/urls.py中配置url。api
url(r'^editor/',views.editor),
3)在項目目錄下建立靜態文件目錄以下圖:
4)打開py_django虛擬環境的目錄,找到tinymce的目錄。
/home/python/.virtualenvs/py_django/lib/python3.5/site-packages/tinymce/static/tiny_mce
5)拷貝tiny_mce_src.js文件、langs文件夾以及themes文件夾拷貝到項目目錄下的static/js/目錄下。
6)在test6/settings.py中配置靜態文件查找路徑。
STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ]
7)在templates/booktest/目錄下建立editor.html模板。
<html> <head> <title>自定義使用tinymce</title> <script type="text/javascript" src='/static/js/tiny_mce.js'></script> <script type="text/javascript"> tinyMCE.init({ 'mode':'textareas', 'theme':'advanced', 'width':400, 'height':100 }); </script> </head> <body> <form method="post" action="#"> <textarea name='gcontent'>哈哈,這是啥呀</textarea> </form> </body> </html>
8)運行服務器,在瀏覽器中輸入以下網址:
http://127.0.0.1:8000/editor/
瀏覽效果以下圖:
經過富文本編輯器產生的字符串是包含html的。 在數據庫中查詢以下圖:
在模板中顯示字符串時,默認會進行html轉義,若是想正常顯示須要關閉轉義。
問:在模板中怎麼關閉轉義
from booktest.models import * ... def show(request): goods=GoodsInfo.objects.get(pk=1) context={'g':goods} return render(request,'booktest/show.html',context)
url(r'^show/', views.show),
<html> <head> <title>展現富文本編輯器內容</title> </head> <body> id:{{g.id}} <hr> {%autoescape off%} {{g.gcontent}} {%endautoescape%} <hr> {{g.gcontent|safe}} </body> </html>
4)運行服務器,在瀏覽器中輸入以下網址:
http://127.0.0.1:8000/show/
瀏覽效果以下圖:
全文檢索不一樣於特定字段的模糊查詢,使用全文檢索的效率更高,而且可以對於中文進行分詞處理。
pip install django-haystack
pip install whoosh
pip install jieba
INSTALLED_APPS = ( ... 'haystack', )
... HAYSTACK_CONNECTIONS = { 'default': { #使用whoosh引擎 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine', #索引文件路徑 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), } } #當添加、修改、刪除數據時,自動生成索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
url(r'^search/', include('haystack.urls')),
from haystack import indexes from booktest.models import GoodsInfo #指定對於某個類的某些數據創建索引 class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return GoodsInfo def index_queryset(self, using=None): return self.get_model().objects.all()
2)在templates目錄下建立"search/indexes/booktest/"目錄。
#指定索引的屬性 {{object.gcontent}}
/home/python/.virtualenvs/py_django/lib/python3.5/site-packages/haystack/backends/
import jieba from whoosh.analysis import Tokenizer, Token class ChineseTokenizer(Tokenizer): def __call__(self, value, positions=False, chars=False, keeporiginal=False, removestops=True, start_pos=0, start_char=0, mode='', **kwargs): t = Token(positions, chars, removestops=removestops, mode=mode, **kwargs) seglist = jieba.cut(value, cut_all=True) for w in seglist: t.original = t.text = w t.boost = 1.0 if positions: t.pos = start_pos + value.find(w) if chars: t.startchar = start_char + value.find(w) t.endchar = start_char + value.find(w) + len(w) yield t def ChineseAnalyzer(): return ChineseTokenizer()
注意:複製出來的文件名,末尾會有一個空格,記得要刪除這個空格。
whoosh_cn_backend.py
from .ChineseAnalyzer import ChineseAnalyzer
查找 analyzer=StemmingAnalyzer() 改成 analyzer=ChineseAnalyzer()
python manage.py rebuild_index
11)索引生成後目錄結構以下圖:
按照配置,在admin管理中添加數據後,會自動爲數據建立索引,能夠直接進行搜索,能夠先建立一些測試數據。
def query(request): return render(request,'booktest/query.html')
url(r'^query/', views.query),
參數q表示搜索內容,傳遞到模板中的數據爲query。
<html> <head> <title>全文檢索</title> </head> <body> <form method='get' action="/search/" target="_blank"> <input type="text" name="q"> <br> <input type="submit" value="查詢"> </form> </body> </html>
搜索結果進行分頁,視圖向模板中傳遞的上下文以下:
視圖接收的參數以下:
<html> <head> <title>全文檢索--結果頁</title> </head> <body> <h1>搜索 <b>{{query}}</b> 結果以下:</h1> <ul> {%for item in page%} <li>{{item.object.id}}--{{item.object.gcontent|safe}}</li> {%empty%} <li>啥也沒找到</li> {%endfor%} </ul> <hr> {%for pindex in page.paginator.page_range%} {%if pindex == page.number%} {{pindex}} {%else%} <a href="?q={{query}}&page={{pindex}}">{{pindex}}</a> {%endif%} {%endfor%} </body> </html>
http://127.0.0.1:8000/query/
在文本框中填寫要搜索的信息,點擊」搜索「按鈕。
搜索結果以下:
Django中內置了郵件發送功能,被定義在django.core.mail模塊中。發送郵件須要使用SMTP服務器,經常使用的免費服務器有:163、126、QQ,下面以163郵件爲例。
2)在新頁面中點擊「客戶端受權密碼」,勾選「開啓」,彈出新窗口填寫手機驗證碼。
3)填寫受權碼。
4)提示開啓成功。
5)打開test6/settings.py文件,點擊下圖配置。
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 25 #發送郵件的郵箱 EMAIL_HOST_USER = 'itcast88@163.com' #在郵箱中設置的客戶端受權密碼 EMAIL_HOST_PASSWORD = 'python808' #收件人看到的發件人 EMAIL_FROM = 'python<itcast88@163.com>'
6)在booktest/views.py文件中新建視圖send。
from django.conf import settings from django.core.mail import send_mail from django.http import HttpResponse ... def send(request): msg='<a href="http://www.itcast.cn/subject/pythonzly/index.shtml" target="_blank">點擊激活</a>' send_mail('註冊激活','',settings.EMAIL_FROM, ['itcast88@163.com'], html_message=msg) return HttpResponse('ok')
7)在booktest/urls.py文件中配置。
url(r'^send/$',views.send),
8)啓動服務器,在瀏覽器中輸入以下網址:
http://127.0.0.1:8000/send/
郵件發送成功後,在郵箱中查看郵件以下圖:
情景:用戶發起request,並等待response返回。在本些views中,可能須要執行一段耗時的程序,那麼用戶就會等待很長時間,形成很差的用戶體驗,好比發送郵件、手機驗證碼等。
使用celery後,狀況就不同了。解決:將耗時的程序放到celery中執行。
celery名詞:
安裝包:
celery==3.1.25 django-celery==3.1.17
import time ... def sayhello(request): print('hello ...') time.sleep(2) print('world ...') return HttpResponse("hello world")
url(r'^sayhello$',views.sayhello),
http://127.0.0.1:8000/sayhello/
INSTALLED_APPS = ( ... 'djcelery', }
import djcelery djcelery.setup_loader() BROKER_URL = 'redis://127.0.0.1:6379/2'
import time from celery import task @task def sayhello(): print('hello ...') time.sleep(2) print('world ...')
from booktest import tasks ... def sayhello(request): # print('hello ...') # time.sleep(2) # print('world ...') tasks.sayhello.delay() return HttpResponse("hello world")
python manage.py migrate
生成表以下:
10)啓動Redis,若是已經啓動則不須要啓動。
sudo service redis start
11)啓動worker。
python manage.py celery worker --loglevel=info
啓動成功後提示以下圖:
11)打開新終端,進入虛擬環境,啓動服務器,刷新瀏覽器。 在舊終端中兩個輸出間仍有時間間隔。
運行完成後以下圖,注意兩個終端中的時間,服務器的響應是當即返回的。
12)打開booktest/task.py文件,修改成發送郵件的代碼,就能夠實現無阻塞發送郵件。
from django.conf import settings from django.core.mail import send_mail from celery import task @task def sayhello(): msg='<a href="http://www.itcast.cn/subject/pythonzly/index.shtml" target="_blank">點擊激活</a>' send_mail('註冊激活','',settings.EMAIL_FROM, ['itcast88@163.com'], html_message=msg)