杰瑞科技汇

Python admin集成Ueditor如何实现?

Of course! Integrating UEditor, a powerful WYSIWYG editor from Baidu, into a Django admin interface is a common requirement. Here’s a comprehensive, step-by-step guide on how to do it.

Python admin集成Ueditor如何实现?-图1
(图片来源网络,侵删)

We'll use the popular django-ueditor package, which makes the integration process very straightforward.

Overview of the Steps

  1. Install django-ueditor: Add the package to your project.
  2. Add to INSTALLED_APPS: Tell Django to include the UEditor app.
  3. Include UEditor URLs: Add the necessary URL patterns for the editor's resources.
  4. Create a Model: Define a model that will store the rich text content.
  5. Create a Form: Create a custom form with a UeditorWidget for the model field.
  6. Create a ModelAdmin: Link the form to your model in the admin.
  7. Static Files: Ensure Django can find UEditor's CSS and JS files.
  8. Run Migrations & Test: Apply database changes and see the result in the admin.

Step-by-Step Guide

Step 1: Install the Package

First, you need to install the django-ueditor library. You can do this using pip:

pip install django-ueditor

Step 2: Add to INSTALLED_APPS

Open your project's settings.py file and add 'ueditor' to the INSTALLED_APPS list.

# settings.py
INSTALLED_APPS = [
    # ... other apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Add your apps here
    'myapp', # Your app containing the model
    # Add the UEditor app
    'ueditor',
]

Step 3: Include UEditor URLs

In your project's main urls.py file (the one that includes admin.site.urls), add the URLs from ueditor.urls.

Python admin集成Ueditor如何实现?-图2
(图片来源网络,侵删)
# your_project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    # Add this line to include UEditor's URLs
    path('ueditor/', include('ueditor.urls')),
]

This is crucial because the editor itself needs to load its own JavaScript and CSS files, and this URL provides them.

Step 4: Create a Model

Let's create a simple model in one of your apps (e.g., myapp) that will use the UEditor. We'll use a TextField to store the HTML content.

# myapp/models.py
from django.db import models
class BlogPost(models.Model):= models.CharField(max_length=200)
    # This field will store the rich text content
    content = models.TextField()
    def __str__(self):
        return self.title

Step 5: Create a Custom Form with UeditorWidget

This is the key step. We need to create a form that tells the admin interface to use the UEditor widget for our content field.

# myapp/forms.py
from django import forms
from ueditor.widgets import UeditorWidget
from .models import BlogPost
class BlogPostForm(forms.ModelForm):
    # Use the UeditorWidget for the content field
    content = forms.CharField(widget=UeditorWidget())
    class Meta:
        model = BlogPost
        fields = ['title', 'content']

Step 6: Create a ModelAdmin

Now, in your app's admin.py, you'll create a ModelAdmin class. You need to do two things:

Python admin集成Ueditor如何实现?-图3
(图片来源网络,侵删)
  1. Use the custom form you just created.
  2. Set content as a raw_id_fields or exclude it from raw_id_fields. This is a necessary workaround for a known issue with how Django admin handles rich text editors in inlines.
# myapp/admin.py
from django.contrib import admin
from .models import BlogPost
from .forms import BlogPostForm
@admin.register(BlogPost)
class BlogPostAdmin(admin.ModelAdmin):
    # Use the custom form
    form = BlogPostForm
    # List the fields to display in the admin list view
    list_display = ('title',)
    # IMPORTANT: This is a workaround for a Django admin issue.
    # You must exclude the field with the UEditor widget from raw_id_fields.
    # If you don't use raw_id_fields, you can just leave this as an empty list.
    raw_id_fields = []

Step 7: Handle Static Files (The Modern Way)

The django-ueditor package includes its own static files. Django's development server automatically serves these, but in a production environment, you need to collect them.

  1. In settings.py, make sure django.contrib.staticfiles is in INSTALLED_APPS (it usually is by default).

  2. Run the collectstatic command:

    python manage.py collectstatic

    This command will find all static files from your apps (including ueditor) and copy them into a single location defined by your STATIC_ROOT setting.

Step 8: Run Migrations and Test

  1. Create and apply migrations for your new model:

    python manage.py makemigrations myapp
    python manage.py migrate
  2. Run the development server:

    python manage.py runserver
  3. Open your browser and navigate to the admin interface: http://127.0.0.1:8000/admin/.

  4. You should see your BlogPost model. Click "Add" next to it.

  5. You will now see the UEditor interface in place of a standard <textarea> for the content field! You can write text, format it, insert images, and more.

Customization (Optional)

The UeditorWidget accepts several arguments to customize the editor's appearance and functionality.

# myapp/forms.py
from django import forms
from ueditor.widgets import UeditorWidget
from .models import BlogPost
class BlogPostForm(forms.ModelForm):
    # Customize the UEditor
    content = forms.CharField(
        widget=UeditorWidget(
            # Path to the UEditor configuration file (optional)
            # js_path='/static/ueditor/ueditor.config.js',
            # Path to the UEditor JavaScript file
            # ueditor_path='/static/ueditor/ueditor.all.min.js',
            # Initial CSS for the editor
            css_path='/static/ueditor/themes/default/css/ueditor.css',
            # Additional options to pass to the UEditor instance
            UEDITOR_CONFIG={
                'initialFrameHeight': 400,  # Set editor height
                'toolbars': 'full',        # or 'simple', or define your own toolbar
                'autoFloatEnabled': False,
                'imageUrl': '/ueditor/upload/', # Image upload endpoint
                'imagePath': '/ueditor/upload/', # Image save path
            }
        )
    )
    class Meta:
        model = BlogPost
        fields = ['title', 'content']

For a full list of configuration options, refer to the official UEditor documentation.

Troubleshooting

  • Editor doesn't load (shows a blank box or errors in the console):

    • Check your browser's developer console (F12) for JavaScript errors. Common issues are 404 errors for ueditor.config.js or ueditor.all.min.js.
    • Ensure you have correctly included the UEditor URLs in your main urls.py.
    • If using a production server, make sure you've run collectstatic.
  • Image/Attachment Upload not working:

    • The default upload URL is /ueditor/upload/. Make sure this URL is not blocked by any middleware (like CSRF protection, though UEditor handles this).
    • The directory specified in imagePath (e.g., /ueditor/upload/) must be writable by your web server. In development, this is usually not an issue, but in production, you'll need to set correct file permissions. You should configure this to point to a media directory.
分享:
扫描分享到社交APP
上一篇
下一篇