【发布时间】:2019-02-10 00:54:40
【问题描述】:
我有一个问题here 我希望使用不带表单的 django-summernote,但这似乎是不可能的,所以我决定使用表单,当我阅读有关“使用基于类的视图处理表单”的文档时here 它说:
这些通用视图会自动创建一个 ModelForm
我认为正因为如此,我的字段在我的模板上显示了两次(在管理员中效果很好),因为我制作了一个 ModelForm 和通用视图 (CreateView) 制作了另一个!
我想知道如何解决这个问题
我的 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')
我的主要 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'),
]
我的意见.py:
class GameCreate(LoginRequiredMixin, CreateView):
model = Game
template_name = 'core/game_new.html'
form_class = GameForm
redirect_field_name = 'home'
class GameUpdate(LoginRequiredMixin, UpdateView):
model = Game
template_name = 'core/game_edit.html'
fields = '__all__'
我的forms.py:
from django import forms
from django_summernote.widgets import SummernoteWidget
from core.models import Game
class GameForm(forms.ModelForm):
class Meta:
model = Game
fields = '__all__'
widgets = {
'game_story': SummernoteWidget(),
}
我的模板文件“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 }}
{{ form|safe }}
<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 %}
注意: 为了解释这里的问题,“游戏模型”的每个字段都在我的模板中显示了两次。
【问题讨论】:
-
尝试将
game_new.html中的{{ form|crispy }} {{ form|safe }}更改为{{ form|crispy|safe }} -
嗨@Ykh,在您重播之前,我删除了 {{ form|safe }},一切正常,现在我添加了这个`{{ form|crispy|safe }}`,这也有效,你能解释一下'{{ form|safe }}'是什么用你的解决方案回答,所以我可以接受答案
-
|safe用于将 html 代码转换为 html,我认为不需要。{{ form|crispy }}适用于form。如果一个对象有多个模板标签,请写为@987654337 @ -
@Yky 请回答以下问题,以便我接受答案
标签: python django django-forms django-templates django-views