第一步:定义表存图片路径
models.py
class AdminIMG(models.Model):
filename = models.CharField(max_length=200, blank=True, null=True)
img = models.ImageField(upload_to = './admin')
- H:\blog>python manage.py makemigrations
- Migrations for 'XYZblog':
- XYZblog\migrations\0002_auto_20170923_2018.py
- - Create model AdminIMG
- H:\blog>python manage.py migrate
- Operations to perform:
- Apply all migrations: XYZblog, admin, auth, contenttypes, sessions
- Running migrations:
- Applying XYZblog.0002_auto_20170923_2018... OK
第二步:定义视图,让图片直接显示在编辑框内
views.py
from .models import AdminIMG
def uploadIMG(request):
img = request.FILES.get('img')
adminIMG = AdminIMG()
adminIMG.filename = img.name
adminIMG.img = img
adminIMG.save()
return HttpResponse(
"<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('/media/%s').closest('.mce-window').find('.mce-primary').click();</script>" % adminIMG.img)
第三步:定义上传的目录
settings.py
- MEDIA_ROOT = os.path.join(BASE_DIR, 'static/upload/img')
第四步:定义url
urls.py
from django.views.static import serve
from blog.settings import MEDIA_ROOT
urlpatterns = [
url(r'uploadIMG/',views.uploadIMG,name='uploadIMG'),
url(r'^media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT, }),
......
]
第五步:编辑\static\js\tinymce\textareas.js
- tinymce.init({
- selector: 'textarea',
- theme : "modern",
- plugins: ["image"],
- image_advtab: true,
- paste_data_images:true,
- file_browser_callback: function(field_name, url, type, win) {
- if(type=='image') $('#my_form input').click();
- },
- });
- $( document ).ready(function() {
- h ='<iframe id="form_target" name="form_target" style="display:none"></iframe><form id="my_form" action="/temporary/uploadIMG/" target="form_target" method="post" enctype="multipart/form-data" style="width:0px;height:0;overflow:hidden"><input name="img" type="file" onchange="$(\'#my_form\').submit();this.value=\'\';"></form>';
- $('body').append(h);
- function getCookie(name) {
- var cookieValue = null;
- if (document.cookie && document.cookie != '') {
- var cookies = document.cookie.split(';');
- for (var i = 0; i < cookies.length; i++) {
- var cookie = jQuery.trim(cookies[i]);
- // Does this cookie string begin with the name we want?
- if (cookie.substring(0, name.length + 1) == (name + '=')) {
- cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
- break;
- }
- }
- }
- return cookieValue;
- }
- var csrftoken = getCookie('csrftoken');
- console.log(csrftoken);
- $('#my_form').append('<input type="hidden" name="csrfmiddlewaretoken" value='+csrftoken+' />');
- });