Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเพิ่มฟิลด์ Text Editor ใน Django


เว็บไซต์สอบออนไลน์มากมายใช้ Text Editor สำหรับกรอกข้อความ อัปโหลดรูป Quill Text Editor นิยมและมี Model Field สำหรับเก็บในฐานข้อมูลโดยตรง ไม่ต้องตั้งค่าเพิ่มเติม

ตัวอย่าง

สร้างโปรเจกต์และแอป ตั้งค่าพื้นฐาน รวม urls ของแอป สร้างโฟลเดอร์ media ระดับเดียวกับโปรเจกต์และแอป

ใน settings.py:

INSTALLED_APPS = [
    'myapp.apps.MyappConfig',
    'django_quill'
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

ติดตั้ง django_quill:

pip install django_quill

ใน urls.py ของแอป:

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name="home"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

สร้าง templates/home.html:

<!DOCTYPE html> <html>
<head>
    {{ form.media }}
    {% include 'django_quill/media.html' %}
    <title>TUT</title>
</head>
<body>
    <form role="form" method="POST">
        <legend>Form Title</legend>
        {% csrf_token %}
        {{ form }}
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</body> </html>

ใน views.py:

from django.shortcuts import render
from django import forms
from .models import another_model

class NewForm(forms.ModelForm):
    class Meta:
        model = another_model
        fields = "__all__"

def home(request):
    if request.method == "POST":
        form = NewForm(request.POST)
        if form.is_valid():
            form.save()
    form = NewForm()
    return render(request, 'home.html', {"form": form})

ใน models.py:

from django.db import models
from django_quill.fields import QuillField

class another_model(models.Model):
    name = models.CharField(max_length=200)
    place = models.CharField(max_length=100)
    animal = models.CharField(max_length=100)
    thing = models.CharField(max_length=100)
    content = QuillField(blank=True)

สร้างโมเดลและฟิลด์ Text Editor สำหรับเก็บข้อมูล

เอาต์พุต

วิธีเพิ่มฟิลด์ Text Editor ใน Django