python - 为什么使用 ModelForm 的 CreateView 显示模型字段两次
问题描述
我在这里有一个问题, 我希望在没有表单的情况下使用 django-summernote,但这似乎是不可能的,所以我决定使用表单,当我在这里阅读有关“使用基于类的视图处理表单”的文档时, 它说:
这些通用视图将自动创建一个 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 %}
注意: 为了解释这里的问题,“游戏模型”的每个字段都在我的模板中显示了两次。
截图问题
解决方案
|safe
用于将 html 代码转换为 html,我认为不需要。{{ form|crispy }}
适合表单。如果您有一个对象的多个模板标签,请写为{{ object|tag1|tag2 }}
推荐阅读
- python - numpy中的3d矩阵乘法
- xcode - 为 iOS Simulator-i386 构建 Nativescript,但尝试链接为 iOS Simulator-x86_64 构建的文件
- javascript - 日志中的 ValidationError 项
- javascript - Javascript:填充表格的行/单元格,新数据不会覆盖现有的单元格数据
- javascript - 推送后JavaScript数组为空
- python - 如何获取文本中的文本
使用 Selenium 和 Python 的 iframe 包含的标签?
- python - GitPython - 从所有分支中提取
- c - 删除链表中指向的节点
- json - 使用 '\' 将哈希表转换为 JSON
- ios - 带有两个图像的标签栏项目