Django-C006-第三方

 此文章完成度【100%】留着以后忘记的回顾。多写多练多思考,我会努力写出有意思的demo,如果知识点有错误、误导,欢迎大家在评论处写下你的感想或者纠错。 

【Django version】: 2.1

【pymysql version】:0.9.3

【python version】: 3.7

【Pillow version】:6.0.0

 

第三方


    常用的第三方Django模块【‘富文本编辑器’, ‘全文检索’,‘发送邮件’, ‘celery’】

部署: 

  当项目开发完成后,需要将代码放到服务器上, 这个过程称为部署,服务器上需要有一个运行代码的环境,这个环境一般使用uWSGI+Nginx 

创建项目

1.创建项目名称为test6,应用名为school

2.检查版本File>Settings>Project:test6>Project Interpreter

3.在test6下urls.py文件配置url到项目中,在项目下urls.py文件中配置index的url

test6/urls.py
from
django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^', include('school.urls')) ]
school/urls.py
from django.urls import re_path
from school import views

urlpatterns = [
    re_path(r'^index$', views.index),
]

4.在应用下的views.py中添加index视图

from django.shortcuts import render

def index(request):
    return render(request, 'school/index.html')

5.在templates文件夹下创建school文件夹,并且创建一个index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>congratulations</h1>
</body>
</html>

 6.在test6下的settings文件中,配置mysql数据库

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'school',
        'USER': 'root',
        'PASSWORD': 'toor',
        'HOST': 'localhost',
        'PORT': 3306
    }
}

7.在test6下__init__.py文件中导入pymysql

import pymysql
pymysql.install_as_MySQLdb()

8.启动服务,访问127.0.0.1:8000

python manage.py runserver

 

 

富文本编辑器


借助富文本编辑器,网站的编辑人员能够像使用office一样编写出漂亮的、所汲汲所得的页面,此处以tinymce为例,其他富文本编辑器使用也是类似

安装django-tinymce

或者使用命令安装:pip install django-tinymce==2.6.0

安装完成后,可以使用在Admin管理中,也可以自定义表单使用

首先:在test6下的settings文件中,注册应用tinymce

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'school.apps.SchoolConfig',
    'tinymce',
]

其次:在test6下的settings文件中添加编辑器配置

# 富文本编辑器配置
TINYMCE_DEFAULT_CONFIG = {
    'theme': 'advanced',
    'width': 600,
    'height': 400,
}

在其次:在test6下的urls文件中,配置编辑器的url

from django.contrib import admin
from django.urls import path, re_path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^', include('school.urls'))
    re_path(r'^tinymce/', include('tinymce.urls'))
]

准备的差不多了,试验一下在Admin中使用

首先:在应用下的models文件中定义模型的属性为HTMLField()类型

from django.db import models
from tinymce.models import HTMLField

class GoodsInfo(models.Model):
    good_content = HTMLField()

其次:生成迁移文件,执行迁移

python manage.py makemigrations
python manage.py migrate

结果尬了, 没有迁移成功,这时候应该试一下,删除迁移表中关于school应用的数据

delete from django_migrations where app='school';

在其次:重新执行迁移

python manage.py migrate

 

其次:再应用下的admin文件中,注册模型类GoodsInfo

from django.contrib import admin
from school.models import GoodsInfo


@admin.register(GoodsInfo)
class GoodsInfoAdmin(admin.ModelAdmin):
    list_display = ['id']

其次:运行服务器,进入admin后台管理,点击GoodsInfo的添加

 

 

 如果:爆出这个错误

显然可以看出是这里出了错误:Exception Location :C:\Users\Circle\Desktop\circle\test6\venv\lib\site-packages\django\forms\boundfield.py in as_widget, line 93

错误信息是render() got an unexpected keyword argument 'renderer' 

大概翻译一下是:render()获得一个意外的关键字参数“renderer”

意外,有可能是不需要的吧,所以我就进入Exception Location指出的路径中的boundfield.py文件下注释了93行,记得保存哈

更意外的是获得了页面,可以访问了

在form表单中自定义使用

首先:在应用下的views文件中定义视图editor,用于显示编辑器

def editor(request):
    return render(request, 'school/editor.html')

其次:在应用下的urls文件中定义url

from django.urls import re_path
from school import views

urlpatterns = [
    re_path(r'^$', views.index),
    re_path(r'^editor$', views.editor),
]

再其次:项目下创建静态文件目录

找到tinymce的目录:C:\Users\Circle\Desktop\circle\test6\venv\Lib\site-packages\tinymce\static\tiny_mce,复制tiny_mce_src.js文件、langs文件夹、themes文件夹到静态目录下的js中

其次:在test6下的settings文件中配置静态文件查找路径

STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static'),
]

其次:在templates下的school目录下创建editor.html模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑器</title>
    {% load static %}
    <script type="text/javascript" src="{% static 'js/tiny_mce_src.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>

访问127.0.0.1:8000/editor

通过编辑器写入的字符串中是包含html标签的,查看数据库,(如果你还没添加过数据,你可以通过admin中添加并且保存到数据库)

 

在模板中显示字符串时,默认会进行html转义,如果想正常显示需要关闭转义。

 如果需要关闭转义可以通过:

  • 方式一:过滤器safe

  • 方式二:标签autoescape off

那么现在我们就将数据库中保存的数据,显示在网页上看一看

首先:在应用下的views文件中定义show视图

from school.models import GoodsInfo

def show(request):
    goods = GoodsInfo.objects.get(id=1)
    content = {'goods': goods}
    return render(request, 'school/show.html', content)

其次:在应用下的urls文件中添加url

re_path(r'^show$', views.show),

其次:在templates下的school目录中添加show.html模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>显示</title>
</head>
<body>
    id:{{goods.id}}
    <hr>
    没有关闭转义的:{{goods.good_content}}
    <hr>
    {%autoescape off%}
    过滤器关闭转义的:{{goods.good_content}}
    {%endautoescape%}
    <hr>
    标签关闭转义的:{{goods.good_content|safe}}
</body>
</html>

访问127.0.0.1:8000/show

 

 

全文检索


 

 全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理。

  • haystack:全文检索的框架,支持whoosh、solr、Xapian、Elasticsearc四种全文检索引擎,点击查看官方网站

  • whoosh:纯Python编写的全文搜索引擎,虽然性能比不上sphinx、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的崩溃,对于小型的站点,whoosh已经足够使用,点击查看whoosh文档

  • jieba:一款免费的中文分词包,如果觉得不好用可以使用一些收费产品。

依次安装需要的包

pip install django-haystack
pip install whoosh
pip install jieba

修改test6/settings.py文件,安装应用haystack

INSTALLED_APPS = (
    ...
    'haystack',
)

在test6/settings.py文件中配置搜索引擎,如果报错,请先不用管,后续文件创建完成后,会消除报错

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'

在test6/urls.py中添加搜索的配置

re_path(r'^search/', include('haystack.urls')),

创建引擎及索引

在school目录下创建search_indexes.py文件。

from haystack import indexes
from school.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()

在templates目录下创建"search/indexes/booktest/"目录,在目录中创建"goodsinfo_text.txt"文件。

#指定索引的属性
{{object.gcontent}}

找到虚拟环境py_django下的haystack目录,如果你没有虚拟环境的话。就去pip安装下的目录里找。一般会安装到Python下,在目录中创建ChineseAnalyzer.py文件。

C:\Users\Circle\Desktop\circle\test6\venv\Lib\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_backend.py文件,改为如下名称:

whoosh_cn_backend.py

打开复制出来的whoosh_cn_backend.py文件,引入中文分析类,内部采用jieba分词

from .ChineseAnalyzer import ChineseAnalyzer

更改词语分析类

查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()

初始化索引数据

python manage.py rebuild_index

按提示输入y后回车,生成索引

(venv) C:\Users\Circle\Desktop\circle\test6>python manage.py rebuild_index
WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y

Removing all documents from your index because you said so.
All documents removed.
Indexing 1 goods infos

(venv) C:\Users\Circle\Desktop\circle\test6>

索引生成后目录结构

按照配置,在admin管理中添加数据后,会自动为数据创建索引,可以直接进行搜索,可以先创建一些测试数据

在应用下的views.py中定义视图query

def query(request):
    return render(request, 'school/query.html')

在应用下的urls.py文件中配置url

re_path(r'^query$', views.query),

在templates下的school目录中创建模板query.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全文检索</title>
</head>
<body>
    <form method='get' action="/search/" target="_blank">
        <input type="text" name="q">
        <br>
        <input type="submit" value="查询">
    </form>
</body>
</html>

自定义搜索结果模板:在templates/search/目录下创建search.html

搜索结果进行分页,视图向模板中传递的上下文如下:

  • query:搜索关键字

  • page:当前页的page对象

  • paginator:分页paginator对象

视图接收的参数如下:

  • 参数q表示搜索内容,传递到模板中的数据为query

  • 参数page表示当前页码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>结果页</title>
</head>
<<body>
    <h1>搜索&nbsp;<b>{{query}}</b>&nbsp;结果如下:</h1>
    <ul>
        {%for item in page%}
            <li>{{item.object.id}}--{{item.object.good_content|safe}}</li>
        {%empty%}
            <li>啥也没找到</li>
        {%endfor%}
    </ul>
    <hr>
    {%for pindex in page.paginator.page_range%}
        {%if pindex == page.number%}
            {{pindex}}&nbsp;&nbsp;
        {%else%}
            <a href="?q={{query}}&amp;page={{pindex}}">{{pindex}}</a>&nbsp;&nbsp;
        {%endif%}
    {%endfor%}
</body>
</html>

先访问http://127.0.0.1:8000/admin/school/goodsinfo/add/ 添加数据,然后再访问127.0.0.1:8000/query

保存一次是一条

 

 

 

 

发送邮件


 

Django中内置了邮件发送功能,被定义在django.core.mail模块中。发送邮件需要使用SMTP服务器,常用的免费服务器有:163126QQ,下面以163邮件为例。

注册163邮箱,登录后设置

在新页面中点击“客户端授权密码”,勾选“开启”,弹出新窗口填写手机验证码

打开test6/settings.py文件

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
#发送邮件的邮箱
EMAIL_HOST_USER = '输入你的邮箱@163.com'
#在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = '输入你的授权码'
#收件人看到的发件人
EMAIL_FROM = 'python<写个名字@163.com>'

在应用下的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.baidu.com" target="_blank">点击激活</a>' send_mail('注册激活', '', settings.EMAIL_FROM, ['circle_2018@163.com'], html_message=msg) return HttpResponse('ok')

在应用下urls.py文件中配置url

re_path(r'^send$', views.send),

访问http://127.0.0.1:8000/send

登录接收邮箱查看

 

 

 

 

 

 

转载于:https://www.cnblogs.com/Hannibal-2018/p/11122387.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值