简体   繁体   中英

How can I upload an image on an textfield from django admin panel like we do in wordpress

Is there any way I can uplaod an image in django textfield from admin panel like we do on wordpress where we get to choose to upload image. I have used ckeditor as my textfield editor which lets me insert links and make text bolds, there is an upload image option available but it ask me for image url instead of asking me to browse an image file from my system. Below is a portion of my models.py code:

from tinymce.models import HTMLField
from ckeditor.fields import RichTextField
from django.db import models
from datetime import datetime
from django.template.defaultfilters import slugify
from unidecode import unidecode
from django.template import defaultfilters




class Category(models.Model):
    name = models.CharField(max_length=128,unique=True)
    slug = models.SlugField(unique=True, null=True, blank=True)


    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

class Heading(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=5000)
    content = RichTextField()
    image= models.ImageField(null=True,blank=True)
    date = models.DateField(default=datetime.now())
    time = models.TimeField(default=datetime.now())
    slug = models.SlugField(unique=True, null=True, blank=True)

    def save(self, *args, **kwargs):
        self.slug = defaultfilters.slugify(unidecode(self.title))
        super(Heading, self).save(*args, **kwargs)



    def __str__(self):
        return self.title

Below are some images to show what I am getting right now: 发短信的管理员小组

我得到的选择

You can use RichTextUploadingField of django-ckeditor. you need to import it first in your models.py

from ckeditor.fields import RichTextUploadingField

now in your model you can do like this

content = RichTextUploadingField()

By default RichTextUploadingField allows you to upload any file. you can also restrict this field to only upload images by adding this line to your settings.py

CKEDITOR_ALLOW_NONIMAGE_FILES = False

Uploading images like WordPress does is not a straight-forward process, although trivial to implement.

When you upload an image in WordPress, in the background WordPress saves the image on the server (using AJAX) and then fetches its link and displays it in the text-editor.

Because text-editors don't support file upload, you'll need to implement this yourself.

But why bother when django-ckeditor app supports file upload. See docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM