django-quill-editor

repository·master·Indexed 42 days ago

https://github.com/leehanyeong/django-quill-editor

A Django integration for the Quill.js WYSIWYG editor (version 0.1.40) that provides rich-text editing capabilities for Django Forms and the Django Admin site. It includes the QuillField for models, QuillFormField for forms, and specialized DRF fields (QuillHtmlField and QuillPlainField) for API serialization. Features include a `convert_to_quill` management command for migrating existing text data and customizable toolbar configurations via `QUILL_CONFIGS` in Django settings.

Tokens
3.8K
Snippets
19
Records
21
Agent score
51%

What's inside django-quill-editor

  1. Security Warning: XSS Risk

    master

    ⚠️ Warning

    Content entered via django-quill-editor is marked as safe by Django using mark_safe. This makes the application vulnerable to Cross-Site Scripting (XSS) attacks if the content is not properly sanitized.

    Recommendation: Only allow authorized administrators to use this editor in production environments.

  2. Render a QuillFormField in a template

    master

    To display the Quill editor in a template, ensure your view passes a form instance containing a QuillFormField to the template context. In the template, render the specific field using the form instance variable.

    # views.py
    from django.shortcuts import render
    from .forms import QuillFieldForm
    
    def form_view(request):
        return render(request, 'form_view.html', {'form': QuillFieldForm()})
    
    # form_view.html
    <form action="" method="POST">
        {% csrf_token %}
        {{ form.content }}
    </form>
  3. Run the Live Demo locally

    master

    You can run the 'playground' application included in the repository to see a live demo. A Python virtual environment is required.

    1. Clone the repository.
    2. Navigate to the playground directory.
    3. Install requirements from requirements.txt.
    4. Run migrations and start the server.
    # Clone repository
    git clone git@github.com:LeeHanYeong/django-quill-editor.git
    
    # Go to the playground package
    cd django-quill-editor/playground
    
    # Install requirements
    pip install -r requirements.txt
    
    # Run migrate and runserver
    python manage.py migrate
    python manage.py runserver
  4. Integrate django-quill-editor with Django REST Framework (DRF)

    master

    To use QuillField data within Django REST Framework serializers, use the specialized fields provided by django_quill.drf.fields. These fields allow you to expose either the HTML representation or the plain text representation of the Quill content in your API responses.

    Available DRF fields:

    • QuillHtmlField: Returns the HTML content of the QuillField.
    • QuillPlainField: Returns the plain text content of the QuillField.

    When using QuillPlainField to represent the same data as the main field, use the source argument to point to the original QuillField attribute.

    from rest_framework import serializers
    from django_quill.drf.fields import QuillHtmlField, QuillPlainField
    from posts.models import QuillPost
    
    class QuillPostSerializer(serializers.ModelSerializer):
        # Exposes the HTML version
        content = QuillHtmlField()
        # Exposes the plain text version by mapping to the 'content' source
        content_plain = QuillPlainField(source='content')
    
        class Meta:
            model = QuillPost
            fields = "__all__"
  5. Register a Model with QuillField in Django Admin

    master

    Once you have added a QuillField to your model, register that model in your app's admin.py file using the @admin.register decorator. The Quill editor interface will automatically be available in the Django admin interface for that model.

    from django.contrib import admin
    from .models import QuillPost
    
    @admin.register(QuillPost)
    class QuillPostAdmin(admin.ModelAdmin):
        pass
  6. Render QuillField in a Django Template

    master

    To display the Quill editor in a template, treat it like a normal Django form field. Render the field using {{ form.field_name }} within a standard HTML <form> tag. The QuillField will automatically provide the necessary components for the editor.

    <!-- form_view.html -->
    <form action="" method="POST">{% csrf_token %}
        {{ form.content }}
    </form>
  7. Migrate TextField or CharField to QuillField

    master

    To convert an existing Django TextField or CharField to a QuillField, you must transform the existing database content into a Quill-compatible format before updating the model definition. Follow these steps in order:

    1. Convert existing data: Run the provided Django management command to transform the field contents in the database. WARNING: This command permanently modifies the data in that field. Use with caution.
    2. Update the Model: Change the field type in your models.py from models.TextField (or CharField) to QuillField.
    3. Generate Migrations: Run python manage.py makemigrations to create the migration file for the field alteration.
    4. Apply Migrations: Run python manage.py migrate to apply the changes to your database schema.
    # 1. Convert data (Replace with your app, model, and field names)
    python manage.py convert_to_quill posts NonQuillPost content
    
    # 2. Update models.py
    from django_quill.fields import QuillField
    
    class NonQuillPost(models.Model):
        content = QuillField()
    
    # 3. & 4. Apply schema changes
    python manage.py makemigrations
    python manage.py migrate
  8. Include Quill editor media in templates

    master

    To render the Quill editor, you must include its required CSS and JS files in the <head> of your HTML template. You can do this in one of two ways:

    1. Using Form Media (Recommended): If you are using a Django Form that contains a QuillFormField, add {{ form.media }} to your <head> tag. This automatically handles the necessary assets for that specific form.
    2. Using Template Include: If you want to include the assets globally or without a specific form instance, use the {% include %} tag with the django_quill/media.html path.
    <!-- Option 1: Using form.media -->
    <head>
        {{ form.media }}
    </head>
    
    <!-- Option 2: Using include tag -->
    <head>
        {% include 'django_quill/media.html' %}
    </head>
  9. Configure Quill toolbar and module settings

    master

    You can customize the Quill editor's appearance and functionality (such as themes, syntax highlighting, and toolbar buttons) by adding a QUILL_CONFIGS dictionary to your Django settings.py file.

    Use the key 'default' within QUILL_CONFIGS to define the configuration applied to your editors. The structure follows the Quill.js module configuration pattern, where theme defines the visual style and modules allows you to configure specific features like syntax or the toolbar layout.

    For a complete list of available toolbar options and module settings, refer to the official Quill.js documentation.

    QUILL_CONFIGS = {
        'default':{
            'theme': 'snow',
            'modules': {
                'syntax': True,
                'toolbar': [
                    [
                        {'font': []},
                        {'header': []},
                        {'align': []},
                        'bold', 'italic', 'underline', 'strike', 'blockquote',
                        {'color': []},
                        {'background': []},
                    ],
                    ['code-block', 'link'],
                    ['clean'],
                ]
            }
        }
    }