Django 통합 부 텍스트 편집기 summernote 의 실현 절차

Django 의 부 텍스트 편집기 하면 ckeditor 와 tinyMCE 를 생각 하 실 겁 니 다.사실은 부 텍스트 편집기 도 똑 같이 우수 합 니 다.바로 summernote 입 니 다.개인 적 으로 기능 적 으로 ckeditor 못 지 않 고 tinyMCE 보다 강하 다 고 생각 합 니 다.Summernote 간단 하고 유연 하 게 볼 수 있 는 HTML 부 텍스트 편집기 입 니 다.jQuery 와 Bootstrap 구축 을 바탕 으로 이미지 업 로드 를 지원 하고 맞 춤 형 옵션 을 많이 제공 합 니 다.
전시 효 과 는 다음 과 같다.

첫 번 째 설치 django-summernote
먼저 pip 를 통 해 django-summernote 를 설치 하고 Django 프로젝트 가 있 는 가상 환경 에 설치 하 는 것 을 권장 합 니 다.사진 을 올 리 려 면 pillow 라 는 갤러리 를 설치 해 야 합 니 다.

pip install django-summernote
pip install pillow #        
이어서 INSTALLED 에 가입APPS 안 으로 들 어가 면 다음 과 같다.

INSTALLED_APPS = [
    ...
    'django_summernote', #      
]
그리고 djangosummernote.urls 프로젝트 에 가입 한 urls.py

from django.urls import include
# ...
urlpatterns = [
    ...
    path('summernote/', include('django_summernote.urls')),
    ...
]
사진 을 올 리 려 면 settings.py 에 MEDIA 관련 옵션 을 설정 해 야 합 니 다.다음 과 같 습 니 다.Django 버 전이 3.x 라면 X 를 설정 해 야 합 니 다.FRAME_OPTIONS 옵션.

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

# Django 3.X          
X_FRAME_OPTIONS = 'SAMEORIGIN'
로 컬 개발 테스트 환경 debug=True 를 사용 하려 면 django 자체 static 정적 파일 서버 를 사용 해 야 올 린 그림 을 정확하게 표시 할 수 있 습 니 다.항목 의 urls.py 를 수정 하고 다음 코드 를 추가 합 니 다.

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)
두 번 째 단 계 는 django-summernote 를 사용 합 니 다.
Django 자체 관리 배경 admin 에서 django-summernote 를 사용 할 수도 있 고,자신의 폼 에서 django-summernote 를 사용 할 수도 있 습 니 다.
admin 에서 사용

from django_summernote.admin import SummernoteModelAdmin
from .models import Post

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

admin.site.register(Post, PostAdmin)
전시 효 과 는 다음 과 같다.

폼 에서 사용
일반 폼 을 사용 하려 면 부 텍스트 디 스 플레이 필드 의 widget 만 설정 하면 됩 니 다.다음 과 같 습 니 다.

from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget

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

#       django-crispy-forms,    
class PostForm(forms.Form):
    content = forms.CharField(widget=SummernoteInplaceWidget())
ModelForm 을 사용 하면 widget 을 다음 과 같이 설정 할 수 있 습 니 다.

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        widgets = {
            'content': SummernoteWidget(),
        }
메모:폼 을 통 해 제출 한 내용 은 모두 html 라벨 이 있 습 니 다.텍스트 를 정확하게 표시 하려 면 safe 템 플 릿 라벨 을 사용 해 야 합 니 다.
{{ content|safe }}
SummernoteWidget 은 사용자 가 제출 한 데이터 에 대해 어떠한 전의 도 하지 않 기 때문에 외부 사용자 가 폼 을 통 해 악성 스 크 립 트 를 주입 할 위험 이 있 습 니 다.작은 편집 은 사용 하 는 것 을 권장 하지 않 습 니 다.폼 에 django-summernote 를 사용 하 는 것 이 더 좋 은 방법 은 SummernoteTextFormField 와 SummernoteTextField 를 사용 하 는 것 입 니 다.모든 유해 한 탭 을 바 꿀 수 있 습 니 다.사용 방식 은 다음 과 같다.
3 단계 테스트 효과
Djangos-summernote 는 사진 뿐만 아니 라 동 영상 도 삽입 할 수 있 습 니 다.직접 테스트 성공!

네 번 째 단계 일반 설정
일반적인 설정 옵션 은 다음 과 같 습 니 다.대부분의 항목 의 수 요 를 만족 시 킬 수 있 고 복사 해서 사용 할 수 있 습 니 다.

SUMMERNOTE_CONFIG = {
    'iframe': True,
    #         Bootstrap/jQuery  
    # 'iframe': False,
    'summernote': {
        # As an example, using Summernote Air-mode
        'airMode': False,
        
        #      size
        'width': '100%',
        'height': '450',

        #     
        'lang': None,

        #      
        # https://summernote.org/deep-dive/#custom-toolbar-popover
        'toolbar': [
            ['style', ['style',]],
            ['font', ['bold', 'underline', 'clear']],
            ['fontname', ['fontname']],
            ['fontsize', ['fontsize']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['table', ['table']],
            ['insert', ['link', 'picture', 'video']],
            ['view', ['redo', 'undo', 'fullscreen', 'codeview',]],
        ],
    },

    #            .
    'attachment_require_authentication': True,

    # Set `upload_to` function for attachments.
    # 'attachment_upload_to': my_custom_upload_to_func(),

    # Set custom storage class for attachments.
    # 'attachment_storage_class': 'my.custom.storage.class.name',
    
    # You can completely disable the attachment feature.
    'disable_attachment': False,
    
    # Set to `True` to return attachment paths in absolute URIs.
    'attachment_absolute_uri': False,
    
    # test_func in summernote upload view. (Allow upload images only when user passes the test)
    # https://docs.djangoproject.com/en/2.2/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin
    # ```
    # def example_test_func(request):
    #     return request.user.groups.filter(name='group_name').exists()
    # ```
    # 'test_func_upload_view': example_test_func,
    
    #    
    'lazy': True,
}
이상 은 Django 통합 부 텍스트 편집기 summernote 의 실현 절차 에 대한 상세 한 내용 입 니 다.Django 통합 부 텍스트 편집기 summernote 에 관 한 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기