Django导入富文本编译器

下载解压kindeditor文件夹到static文件夹下

HTML文件

添加文章

{% csrf_token %}

内容(TinyMCE编辑器,支持拖放/粘贴上传图片)

script文件ID指向textarea的ID



富文本的文章上传视图、图片上传视图

def add_article(request):

	if request.method=="POST":
		title=request.POST.get('title')
		article_content=request.POST.get('article_content')
		user=request.user

		from bs4 import BeautifulSoup
		bs=BeautifulSoup(article_content,"html.parser")
		desc=bs.text[0:150]+"..."

		# 过滤非法标签
		for tag in bs.find_all():
		
			print(tag.name)				
			##去除非法标签
			if tag.name in ["script", "link"]:
				tag.decompose()

		article_obj=models.Article.objects.create(user=user,title=title,desc=desc)
		models.ArticleDetail.objects.create(content=bs.prettify(),article=article_obj)

		return HttpResponse("添加成功")
	return render(request,"add_article.html")



from bbs import settings
import os,json
def upload(request):
	print(request.FILES)
	obj = request.FILES.get("upload_img")
	print("name",obj.name)

	path=os.path.join(settings.MEDIA_ROOT,"add_article_img",obj.name)
	with open(path,"wb") as f:
		for line in obj:
			f.write(line)

	res={
		"error":0,
		"url":"/media/add_article_img/"+obj.name
	}

	return HttpResponse(json.dumps(res))

配置url,实现外部访问图片

# media相关的路由设置
url(r'^media/(?P.*)$', serve, {"document_root": settings.MEDIA_ROOT})

settings

# Django用户上传的都叫media文件
MEDIA_URL = "/media/"
# media配置,用户上传的文件都默认放在这个文件夹下
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

你可能感兴趣的:(Django)