How to use django-summernote in templates

2019-08-21 08:19发布

I have setup django-summernote on my project and everything is great, it works very good on admin , but i want to use it on my templates.

Note : in django-summernote documentation they only explain how to use it if you have forms.py file but I dont

my main urls.py :

urlpatterns = [
    path('games/', include('core.urls', namespace='core')),
    path('summernote/', include('django_summernote.urls')),
]

my app(name=core) urls.py :

from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
    path('new/', views.GameCreate.as_view(), name='game_new'),
    path('<int:pk>/edit/', views.GameUpdate.as_view(), name='game_edit'),
]

my views.py :

class GameCreate(LoginRequiredMixin, CreateView):

    model = Game
    template_name = 'core/game_new.html'
    fields = '__all__'
    redirect_field_name = 'home'

class GameUpdate(LoginRequiredMixin, UpdateView):
    model = Game
    template_name = 'core/game_edit.html'
    fields = '__all__'

my template file "game_new.html" :

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Add New Game {% endblock %}

{% block main %}
<section class="main-section">
    <div class="container">
        <h1>New Game</h1>
        <form action="" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ form|crispy }}
            <input type='submit' value="Save" />
        </form>
    </div>
</section>
{% endblock %}

my template file "game_edit.html":

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %} Game Info {% endblock %}

{% block main %}
<section class="main-section"></section>
    <div class="container">
        <h1>Edit Game Info</h1>
        <form action="" method="post">
            {% csrf_token %}
            {{ form|crispy }}
            <input type="submit" value="Update" />
        </form>
    </div>
</section>
{% endblock %}

my Models.py :

from django.db import models
from django.urls import reverse

# Create your models here.

class Game(models.Model):
    name = models.CharField(max_length=140)
    developer = models.CharField(max_length=140)
    game_trailer = models.CharField(max_length=300, default="No Trailer")
    game_story = models.TextField(default='No Story')

2条回答
地球回转人心会变
2楼-- · 2019-08-21 08:57

okay I think the best way is to use forms.py

查看更多
等我变得足够好
3楼-- · 2019-08-21 09:01

Firstly in your template dont forgate to add this:

{{ form.media }} <<<------ To load all js and css attached

In the document your models you must herit summernote widget. Example:

from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class FormFromSomeModel(forms.ModelForm):
    class Meta:
        model = SomeModel
        widgets = {
            'foo': SummernoteWidget(),
            'bar': SummernoteInplaceWidget(),
        } 
查看更多
登录 后发表回答