为什么CreateView与ModelForm两次显示模型字段

时间:2018-09-05 00:46:34

标签: python django django-forms django-templates django-views

我有一个问题here 我当时想使用不带表单的django-summernote,但似乎不可能,因此我决定使用表单,并且当我阅读有关“使用基于类的视图进行表单处理”的文档时here 它说:

  

这些通用视图将自动创建一个ModelForm

我认为正因为如此,我的字段在模板上显示了两次(在管理中效果很好),因为我制作了ModelForm,而通用视图(CreateView)制作了另一个!

我想知道如何解决这个问题

我的Models.py:

<FlatList
    ...
   onEndReached={() => {console.log('list ended');}}
/>

我的主要urls.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')),
]

我的views.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'),
]

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

我的模板文件“ game_new.html”:

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_edit.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 %}

注意: 这里在我的模板中两次显示了“游戏模型”的每个字段。

屏幕截图the problem

1 个答案:

答案 0 :(得分:0)

|safe用于将html代码转换为html,我认为这是不必要的。{{ form|crispy }}适用于表单。如果一个对象具有多个模板标签,则写为{{ object|tag1|tag2 }}

相关问题