如何从渲染中排除Django表单字段,但仍将其保留以进行验证? [英] How to exclude django form field from render but still keep it for validation?
问题描述
如果我有模型(提取):
If I have a model (extract):
class Coupon(models.Model):
image = models.ImageField(max_length=64, null=True, upload_to="couponimages")
(提取):
class InsertCoupon(forms.ModelForm):
image=forms.ImageField(
required=False, #note explicitly declared false
max_length=64,
widget=forms.FileInput()
)
class Meta:
model=Coupon,
exclude = ("image",)
然后我注意到图像字段在我做 {{form.as_table}}
。如果我从表单类中删除该字段的显式声明,则它不会呈现,但是我无法获得表单验证和将模型表单轻松插入数据库的好处。我想为此字段使用自己的小部件( FileInput
很丑陋)-我是否必须自己编写所有html代码,或者有没有办法使用 as_table
?
Then I notice that the image field is still rendered when I do {{ form.as_table }}
. If I remove the explicit declaration of the field from the form class, then it doesn't render, but I don't get the benefit of form validation and easy modelform insertion to the database. I want to use my own widget for this field (FileInput
is ugly) - do I have to hence code all the html myself, or is there a way to use as_table
?
推荐答案
这样一种更好的方法是只在模板中排除单个字段可能是:
So a better way to exclude just a single field in the template might be:
<table>
{% for field in form %}
{% if field != "image" %}
<tr><td>{{ field }}</td></tr>
{% endif %}
{% endfor %}
</table>
手动删除所有字段。
这篇关于如何从渲染中排除Django表单字段,但仍将其保留以进行验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!