如何在模板中使用django-summernote

时间:2018-09-04 14:21:28

标签: python django summernote

我在项目上设置了django-summernote,一切都很好,它在admin上工作得很好,但是我想在模板上使用它。

注意: 在django-summernote文档中,他们仅解释了如果您有Forms.py文件但如何使用的方法,但我没有

我的主要urls.py:

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

我的应用(名称=核心)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'),
]

我的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__'

我的模板文件“ 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 %}

我的模板文件“ 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 %}

我的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 个答案:

答案 0 :(得分:0)

首先在模板中不要添加以下内容:

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

在模型的文档中,您必须继承summernote小部件。示例:

from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
class FormFromSomeModel(forms.ModelForm):
    class Meta:
        model = SomeModel
        widgets = {
            'foo': SummernoteWidget(),
            'bar': SummernoteInplaceWidget(),
        } 

答案 1 :(得分:0)

好的,我认为最好的方法是使用Forms.py