Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude django form field from render but still keep it for validation?

Tags:

forms

django

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?

like image 497
Escher Avatar asked Dec 19 '22 18:12

Escher


2 Answers

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.

like image 165
Escher Avatar answered Dec 24 '22 01:12

Escher


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.

like image 31
Hubert Dryja Avatar answered Dec 24 '22 00:12

Hubert Dryja