Django UpdateView 不加载带有样式的表单

Django UpdateView not loading forms with styles

我使用 Django 的 UpdateView class 创建了一个表单,但是,当表单加载时,文本框和文本区域似乎没有样式(看起来像 form.as_p 样式)。这是我所做的一个例子。

Views.py

class UpdatePostView(UpdateView):
    template_name = 'Post/UpdatePost.html'
    model = Post
    fields = ['Title', 'Body']
    success_url = reverse_lazy('BlogApp:main')
  
    def form_valid(self, form):
        form.instance.Title = form.cleaned_data['Title']
        form.instance.Body = form.cleaned_data['Body']
        form.instance.save()
        
        return super().form_valid(form)

这是我在 UpdatePost.html 中加载表单的方式:

<form id="UpdatePostForm" method="POST">
    {% csrf_token %}
    <div class="form-group">
        <label for="PostTitle">{{form.Title.label}}</label>
        {{form.Title}}         
    </div>
    
    <div class="form-group">
        <label for="PostBody">{{form.Body.label}}</label>
        {{form.Body}}
    </div>

    <input class="btn btn-primary" type="submit" for="UpdatePostForm" value="Update"> 
    </div>
</form>

因为默认情况下 form.body 和 form.title 呈现 html 输入,您可以像这样从 UpdateView 覆盖 class 属性:

def get_form(self, *args, **kwargs):
        form = super(UpdatePostView, self).get_form(*args, **kwargs)
        form.fields["Title"].widget.attrs["class"] = "form-group"
        form.fields["Body"].widget.attrs["class"] = "form-group"
        return form

如果您使用 Bootstrap,您还可以使用 django-crispy-forms(Bootstrap 4 https://github.com/django-crispy-forms/django-crispy-forms ,version for Bootstrap 5 - https://github.com/django-crispy-forms/crispy-bootstrap5 的版本)。干活(不要重复自己)是有帮助的。 然后它会是这样的(我对 Bootstrap 5 使用 crispy-forms):

pip install crispy-bootstrap5

INSTALLED_APPS = (
    ...
    "crispy_forms",
    "crispy_bootstrap5",
    ...
)

CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"

CRISPY_TEMPLATE_PACK = "bootstrap5"
class UpdatePostView(UpdateView):
    template_name = 'Post/UpdatePost.html'
    model = Post
    fields = ['Title', 'Body']
    success_url = reverse_lazy('BlogApp:main')
  
    def form_valid(self, form):
        form.instance.Title = form.cleaned_data['Title']
        form.instance.Body = form.cleaned_data['Body']
        form.instance.save()
        
        return super().form_valid(form)

模板

{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block content %}

<h1 class="text-center">Update Post</h1>
<br />
        <form method="POST" enctype="multipart/form-data">
          {% csrf_token %} 
          {{form|crispy }}
            <button class="btn btn-outline-primary">
              Update 
            </button>
         </form>
{% endblock content %}