python实现表单中插入表情符号

效果:

点表情图,在表单中表示为[左晃晃]。

见过一个使用jquery来模拟新浪微博的表情插入。

使用Python2.7和Django1.6来实现。

看书好长时间,但是自己来写,发现真的没记住。

方法描述:

1、浏览器页面,使用js脚本把表情符号添加到Textarea;

2、Views里面使用正则把记录里的[]内容替换为图片,渲染到浏览器。

使用一个简单的Sqlite3数据表。

settings.py里设置sqlite3很简单,默认就好。

由于编码问题,项目使用英文路径,创建数据库不会出现问题。

models.py

class emotion(models.Model):
    text=models.CharField(max_length=100)

默认一个ID自动增长字段。

views.py

#coding:utf-8
#使用python 2.7.6 django 1.6实现
import re
from django.shortcuts import render,render_to_response
from myemotion.models import emotion

#define emotion picture
emotion_category=[u'正常']
emotion_pictures={u'[左晃晃]':u'images/zhh_thumb.gif',u'[右晃晃]':u'images/yhh_thumb.gif'}

#display form
def emotion_form(request):
    '''显示表情表单'''

    emotion_1 = emotion()

    #从表单取数据,存入数据表emotion
    if request.method == 'POST':
        emotion_1.text = request.POST.get('text','')
        emotion_1.save()
    #取所有记录
    query = emotion.objects.all()
    return render_to_response('emotion.html',{'emotion_category':emotion_category,'emotion_pictures':emotion_pictures, 'query':query})

只实现记录的保存,并渲染记录。

csrf这个直接注释掉了,没使用。

网页部分只列js代码,就2句:

{% for alt,url in emotion_pictures.items %}
<span style="white-space:pre">	</span><img src="{% static  url %}" onclick="addText(event,id);" id="{{alt}}" >
{% endfor %}
<!--增加表情到文本域 -->
function addText(event,id) {
    document.getElementById("textarea").value += id;
}

static指令失效,也是由于编码问题,要修改python的site.py把编码直接改到gbk。

这里使用了js的event事件。

显示记录,使用过滤器来把[]转换为图片。

{% for q in query %}
<span style="white-space:pre">	</span><ul>
<span style="white-space:pre">	</span><!-- 使用过滤器 -->
<span style="white-space:pre">		</span>{{ q.text|emotion_replace|safe }}
<span style="white-space:pre">	</span></ul>
{% endfor %}

使用safe,避免html标签被自动转义。

emotion_replace 是自定义过滤器。

<pre name="code" class="python">#coding:utf-8
import re
from django import template
from form1 import settings
#定义过滤器,替换文字为图像
#中文范围 : [\u4e00-\u9fa5]
register=template.Library()
#使用全局变量
emotion_pictures={u'[左晃晃]':'images/zhh_thumb.gif',u'[右晃晃]':'images/yhh_thumb.gif'}

#@register.filter
def emotion_replace(value):
    pattern = re.compile(ur'(\[[\u4e00-\u9fa5]+\])')
    #使用findall取得所有匹配结果
    match = re.findall(pattern,value)

    if match is not None:
        #循环结果列表
        for g in match:
            #[左晃晃]如果在字典中存在
            if emotion_pictures.get(g, '') != '':
                pic = '<img src = \''+ settings.STATIC_URL + emotion_pictures[g] + '\'></img>'
                #使用replace方法替换
                value = value.replace(g, pic)
    return value
register.filter(emotion_replace)

过滤器在一个文件中定义,放到文件夹中,和templates同级,叫templatetags。

emotion_replace.py

<pre name="code" class="python">#coding:utf-8
import re
from django import template
from form1 import settings
#定义过滤器,替换文字为图像
#中文范围 : [\u4e00-\u9fa5]
register=template.Library()
#使用全局变量
emotion_pictures={u'[左晃晃]':'images/zhh_thumb.gif',u'[右晃晃]':'images/yhh_thumb.gif'}

#@register.filter
def emotion_replace(value):
    pattern = re.compile(ur'(\[[\u4e00-\u9fa5]+\])')
    #使用findall取得所有匹配结果
    match = re.findall(pattern,value)

    if match is not None:
        #循环结果列表
        for g in match:
            #[左晃晃]如果在字典中存在
            if emotion_pictures.get(g, '') != '':
                pic = '<img src = \''+ settings.STATIC_URL + emotion_pictures[g] + '\'></img>'
                #使用replace方法替换
                value = value.replace(g, pic)
    return value
register.filter(emotion_replace)

最重要的是pattern = re.compile(ur‘(\[[\u4e00-\u9fa5]+\])‘)这句。匹配[左晃晃]。

\[ \] 表示转义,匹配[]

[\u4e00-\u9fa5]匹配任意Unicode字符

+匹配多个字符,要避免贪婪,可以加一个?()

把[..]匹配的返回为一个group使用findall方法,返回一个列表,不使用groups方法。使用replace方法,而不是用re去替换,简化了问题。

Python 2.7的编码问题真麻烦。

ur的顺序不能颠倒,表示unicode和raw字符串。

看起来,比jquery的实现,代码要少很多。这里也没做autotest。程序很简单,好不容易写出表情替换和显示。

python实现表单中插入表情符号

时间: 2024-08-01 00:29:54

python实现表单中插入表情符号的相关文章

Lotus表单中插入视图的解决方法 .

1)你可以在嵌入视图的表单的onload中写:for(i=0; i<document.all.length; i++) {  if(document.all[i].tagName=="H2")    {            document.all[i].innerHTML='<H2><FONT SIZE=3 COLOR="0000FF" FACE="宋体">谢谢,没有你要找到的记录...</FONT>

js 向form表单中插入数据

var newElement = document.createElement("input"); var nowtime=year+""+month+day+hour+minute+second; newElement.setAttribute("name","nowtime"); newElement.setAttribute("value",nowtime); newElement.style.vis

php 在同一个表单中添加和修改

大家写网站的时候可能都会遇到这种情况,就是写一个表单,这个表单是用来添加一篇文章的,我们屁颠屁颠的在后台接收数据,然后存入数据库.现在有个问题.当你要对该文章进行修改的时候,你是怎么处理的? 我的方法是在同一个表单中做文章,下面的例子是我用 Thinkphp框架写的代码,如果你不懂Thinkphp,没有关系,我只是想说说我的解决方案. 前台如果是这样的. <form method="POST" action="{:U('article/add')} > <i

php 在同一个表单中添加和修改数据 二

好吧,其实我这人不看重访问量的,但是今天一天的访问量比我去年发的一篇还要多. 我还是有点小小的惊讶的.作为一个做技术的屌丝.不,我不认为自己是屌丝,我觉得编程是一件高大山的职业.虽然很累,但是确实能让你每天的生活很充实. No matter whether you believe it or not,anyhow I believe it. 今天接着上一篇来说,我们只是简单的文章的上传和修改. 如果涉及到附件呢.在修改的时候如果需要更换附件的时候,这真的是一件很头痛的事情. 我不知道大家是怎样实

用PHP读取MyAQL表单中全部数据并将数据整理翻页

要注意的是我们的PHP是嵌入在html中的 <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <style type="text/css"> </style> </head> <body> <

ueditor在表单中的提交

最近一直在找一个比较好点的WEB文本编辑器,发现ueditor还是不错的,但是在表单提交数据后有一些问题,因为他不像以前的版本一样提供一个虚拟的文本框去提交数据,所以网上搜索的结果都不能用了,根据ueditor 1.4.3版本的提示可以使用editor.getContent()方法获得编辑器的内容,但是这个是用JS方法获取数据的,如何在表单提交时正常的将数据POST出去呢,想了办法,只能用一些原始的方法了,在表单中加一个隐藏表单项,在点击提交按钮里将编辑器中的数据用getContent()方法写

Python Flask-web表单

Flask-WTF扩展可以把处理web表单的过程变成一种愉悦的体验. 一.跨站请求伪造保护 默认情况下,Flask-WTF能够保护所有表单免受跨站请求伪造的攻击.恶意网站把请求发送到被攻击者已登录的网站时就会引起CSRF攻击. 为了实现CSRF保护,Flask-WTF需要程序设置一个密钥.Flask-WTF使用这个密钥生成加密令牌,再用令牌验证请求中表单数据的真伪.设置密钥的方法如下所示: app = Flask(__name__) app.config['SECRET_KEY']='hard

MySQL建表、插入语句等

不定时更新MySQL的一些基础语句以及出现过的问题 5.10 建表语句 CREATE TABLE `policy_landvalue` ( `id` int(20) NOT NULL AUTO_INCREMENT, `article_title` varchar(255) NOT NULL COMMENT '文章标题', `resource_url` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '来源网站URL:0.http://www.hz

struts2 jsp表单提交后保留表单中输入框中的值 下拉框select与input

原文地址:struts2 jsp表单提交后保留表单中输入框中的值 下拉框select与input jsp页面 1     function dosearch() {2         if ($("#textValue").val() == "") {3                 $("#errortip").html("<font color='#FF0000'>请输入查询内容</font>")