gpt4 book ai didi

python - 表单中的 Django ClearableInputField 不会以 HTML 形式呈现

转载 作者:行者123 更新时间:2023-12-01 03:53:44 25 4
gpt4 key购买 nike

我正在开发一个具有照片上传功能的网络应用程序。我创建了一个 ModelForm 来收集最少的用户信息和一张照片,当我在 HTML 中将其渲染为 {{ form.as_p }} 时,允许用户上传图像的字段显示得很好。问题是,表格看起来不太好。

我需要能够手动渲染表单以使其看起来更好。我已经为此编写了 HTML,除了 ImageFileField 之外,一切看起来都正确。仅渲染标签,而不渲染上传按钮、清除文件的复选框等。

我需要做什么才能从 ModelForm 获取 ImageFileField 以在我的自定义 HTML 中正确呈现? 我已经上下查看了 Django 文档,也查看了此处,并且可以'找不到其他遇到此问题的人。非常感谢!

Manually rendered HTML for ModelForm

forms.py 片段

class PostForm(forms.ModelForm):

class Meta:
model = Items
fields = ('title', 'description', 'image_file')

new_item.html 代码段

<form enctype="multipart/form-data" method="post" action="" class="post-form">

{% csrf_token %}

{{ form.non_field_errors }}

<div class="fieldWrapper">
{{ form.title.errors }}
<label for="{{ form.title.id_for_label }}">Title:</label><br>
{{ form.title }}
</div><br>

<div class="fieldWrapper">
{{ form.description.errors }}
<label for="{{ form.description.id_for_label }}">Description: </label><br>
{{ form.description }}
</div><br>

<div class="fieldWrapper">
{{ form.image_field.errors }}
<label for="{{ form.image_field.id_for_label }}">Image (optional):</label><br>
{{ form.image_field }}
</div>

<button type="submit" class="save btn btn-default">Save</button>

</form>

models.py 片段

class Items(models.Model):

title = models.CharField(max_length=1000, null=False)
description = models.TextField(max_length=1000, null=False)
image_file = models.ImageField(max_length=1000,
blank=True,
default='',
null=True,
upload_to='item_photos')

最佳答案

默认情况下,django ModelForm 使用 django.forms.ImageField 而不是 ClearableInputField 作为 django.db.ImageFieldhttps://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#field-types 所示

我相信你的意思实际上是 ClearableFileInput

ClearableFileInput¶ class ClearableFileInput File upload input: , with an additional checkbox input to clear the field’s value, if the field is not required and has initial data.

如何利用它是通过更改类元中的小部件

class PostForm(forms.ModelForm):

class Meta:
model = Items
fields = ('title', 'description', 'image_file')
widgets = {
'name': ClearableFileInput(),
}

关于python - 表单中的 Django ClearableInputField 不会以 HTML 形式呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37846992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com