python - 如何编辑 Django 表单错误消息的 CSS?

标签 python django file-upload django-forms

我的 Django 应用程序上有一个表单,它应该允许用户仅上传 csv 文件,并且每当用户上传具有不同扩展名的文件时,我想呈现一条错误消息。目前,我检查上传文件的扩展名,如果扩展名不是 .csv,则我在 ValidationErrors

中添加错误

问题是我找不到编辑该错误的 CSS 的方法。现在它被显示为列表的元素,但我想将它放在 h1 标签中。这是我的代码:

表单.py

from django import forms
from .models import CSVUpload
import time

class CsvForm(forms.ModelForm):

    csv_file = forms.FileField(widget=forms.FileInput(
        attrs= {
            'class': 'form-group',
        }
    ))

    class Meta:
        model = CSVUpload
        fields = ('csv_file', )

    def save(self):
        csvfile = super(CsvForm, self).save()
        return csvfile


    def clean_csv_file(self):
       uploaded_csv_file = self.cleaned_data['csv_file']
       if uploaded_csv_file:
         filename = uploaded_csv_file.name
         if filename.endswith('.csv'):
             return uploaded_csv_file 
         else:
             raise forms.ValidationError("File must be csv")
       else:
        return uploaded_csv_file

模板


{% extends "fileconverter/base.html" %}

{% block content  %}

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.csv_file }}
    {{ form.csv_file.errors }}

    <button type="submit" class="uploadbutton">Convert CSV</button>
</form>

{% endblock %}

有人可以帮助我了解如何解决这个问题吗?感谢您提供的任何帮助

最佳答案

您可以使用 custom errorlist class 来更改此设置.

但正如其他人所说,这几乎肯定是错误的做法。表单不是标题,因此这在语义上是不正确的。相反,使用 CSS 按照您想要的方式设置错误样式,包括将自定义 error_css_class 添加到表单,如 Alex 演示的那样。

关于python - 如何编辑 Django 表单错误消息的 CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56931072/

相关文章:

python - 如何打印文件中特定长度的行(Python)

python - dynamodb boto put_item 类型为 Map "M"

json - 如何将文件和 JSON 数据与 Curl 一起发布?

file-upload - Yii2中的文件上传问题

python - 运行 Tensorflow 时 GPU 利用率低

python - Pandas read_gbq 无法正常工作?

mysql - 列未知时在 SQL 数据库中存储数据的正确方法

javascript - 如何将输入按钮链接到文件选择窗口?

python - 无法使用Python-docx获取Word中ContentControl中的文本

python - 如何在 django rest 框架中保存嵌套关系?