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?
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.
I think the best way to achieve that is to create a widget that renders nothing:
class NoInput(forms.Widget):
    input_type = "hidden"
    template_name = ""
    def render(self, name, value, attrs=None, renderer=None):
        return ""
class YourForm(forms.Form):
    control = forms.CharField(required=False, widget=NoInput)
This way you can still use {{form}} in your template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With