如何排除django表单字段,但仍然保留它作为验证?

时间:2022-06-01 02:44:11

If I have a model (extract):

如果我有一个模型(摘录):

class Coupon(models.Model):
    image = models.ImageField(max_length=64, null=True, upload_to="couponimages")

And a form (extract):

和一个表单(提取):

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",)

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?

然后我注意到,当我做{{form >时,图像字段仍然呈现。as_table } }。如果我从form类中删除了字段的显式声明,那么它就不会呈现,但是我没有得到表单验证和将modelform插入到数据库的好处。我想要使用我自己的小部件来进行这个字段(FileInput是丑陋的)——我必须自己编写所有的html代码,还是有一个使用as_table的方法?

2 个解决方案

#1


1  

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>

Beats manually writing out all the fields.

胜过手工写出所有字段。

#2


0  

You can render form manualy like this:

你可以像这样呈现形式:

in views.py

在views.py

return render(request, 'template.html', {'form': form})

in template.html

在template.html

<form action="/your-name/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.field1 }}
    {{ form.field2 }}
          .
          .
          .
    <input type="submit" value="Submit" />
</form>

also take a look to Working with forms.

还可以看看如何使用表单。

#1


1  

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>

Beats manually writing out all the fields.

胜过手工写出所有字段。

#2


0  

You can render form manualy like this:

你可以像这样呈现形式:

in views.py

在views.py

return render(request, 'template.html', {'form': form})

in template.html

在template.html

<form action="/your-name/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.field1 }}
    {{ form.field2 }}
          .
          .
          .
    <input type="submit" value="Submit" />
</form>

also take a look to Working with forms.

还可以看看如何使用表单。