Django summernote 富文本

Summernote is a simple WYSIWYG editor.

 GITHUB:https://github.com/summernote/django-summernote

Django summernote 富文本_第1张图片

SETUP

  1. Install django-summernote to your python environment.

     pip install django-summernote

     

  2. Add django_summernote to INSTALLED_APP in settings.py.

    INSTALLED_APPS += ('django_summernote', )

     

  3. Add django_summernote.urls to urls.py.

     urlpatterns = [
         ...
         url(r'^summernote/', include('django_summernote.urls')),
         ...
     ]

     

  4. Be sure to set proper MEDIA_URL for attachments.

    • The following is an example test code:

      MEDIA_URL = '/media/'
      MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

       

    • When debug option is enabled(DEBUG=True), DO NOT forget to add urlpatterns as shown below:

       from django.conf import settings
       from django.conf.urls.static import static
       
       if settings.DEBUG:
           urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

       

    • Please, read the official document more in detail: https://docs.djangoproject.com/en/1.11/topics/files/

  5. Run database migration for preparing attachment model.

     python manage.py migrate
    

USAGE

Django admin site

Apply summernote to all TextField in model

In admin.py,

from django_summernote.admin import SummernoteModelAdmin
from .models import SomeModel

# Apply summernote to all TextField in model.
class SomeModelAdmin(SummernoteModelAdmin):  # instead of ModelAdmin
    summernote_fields = '__all__'

admin.site.register(SomeModel, SomeModelAdmin)

 

Apply summernote to not all TextField in model

Although Post model has several TextField, only content field will have SummernoteWidget.

In admin.py,

from django_summernote.admin import SummernoteModelAdmin
from .models import Post

class PostAdmin(SummernoteModelAdmin):
    summernote_fields = ('content',)

admin.site.register(Post, PostAdmin)

Form

In forms,

from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget

# Apply summernote to specific fields.
class SomeForm(forms.Form):
    foo = forms.CharField(widget=SummernoteWidget())  # instead of forms.Textarea

# If you don't like