python 使用Redactor Text Editor和Django上传文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用Redactor Text Editor和Django上传文件相关的知识,希望对你有一定的参考价值。
import os
from django.views.generic import FormView
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.core.files.storage import FileSystemStorage
from django.utils.encoding import force_str
from app.forms import ImageForm
class RedactorUploadView(FormView):
form_class = ImageForm
http_method_names = ('post',)
upload_to = 'redactor/'
@method_decorator(csrf_exempt)
@method_decorator(staff_member_required)
def dispatch(self, request, *args, **kwargs):
return super(RedactorUploadView, self).dispatch(request, *args,
**kwargs)
def form_invalid(self, form):
try:
error = form.errors.values()[-1][-1]
except:
error = 'Invalid file.'
data = {
'error': error,
}
return HttpResponse(json.dumps(data), content_type='application/json')
def form_valid(self, form):
upload_file = form.cleaned_data['file']
full_path = os.path.join(self.upload_to, upload_file.name)
storage = FileSystemStorage()
real_path = storage.save(full_path, upload_file)
file_name = force_str(upload_file.name)
# get url for file if he saved else None
file_url = storage.url(real_path)
data = {
'filelink': file_url,
'filename': file_name,
}
return HttpResponse(json.dumps(data), content_type='application/json')
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from app.views import RedactorUploadView
from app.forms import FileForm, ImageForm
urlpatterns = patterns(
'',
url('^redactor/upload/image/(?P<upload_to>.*)',
RedactorUploadView.as_view(form_class=ImageForm),
name='redactor_upload_image'),
url('^redactor/upload/file/(?P<upload_to>.*)',
RedactorUploadView.as_view(form_class=FileForm),
name='redactor_upload_file'),
)
urlpatterns += static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT,
)
/*jshint strict:true, browser:true, jquery:true */
$(function () {
'use strict';
$.Redactor.opts.langs.es = {
html: 'HTML',
image: 'Imagen',
link: 'Enlace',
// ....
};
// Enable redactor
$('textarea').redactor({
minHeight: 300,
toolbarFixedTopOffset: 63,
lang: 'es',
imageUpload: '/redactor/upload/image/',
fileUpload: '/redactor/upload/file/',
fileUploadErrorCallback: function(json) {
alert(json.error);
}
});
});
from django import forms
class ImageForm(forms.Form):
file = forms.ImageField()
class FileForm(forms.Form):
file = forms.FileField()
以上是关于python 使用Redactor Text Editor和Django上传文件的主要内容,如果未能解决你的问题,请参考以下文章
javascript Redactor和JQuery拼写检查器。
text F4:VARIANTE ED F4帮助
text 博客con BAPI FM ed esempi
如何使用python将ed25519算法实现到jwt中?
Sublime Text 3 编译Python3
Angular 5. 检查子组件中的父 *ngIf