Using same template for add and edit using Django Model Form

If we want to use a customized form corresponding to a ModelForm, we have to do something like this
<form action="" method="post">
<input name="{{form.field_a.html_name}}" type="text" />
<input type="submit" value="Submit" />
</form>
This will work fine for adding data. But it's very common that we want to use this same form for updating data. In that case we have to populate the fields of the form with the existing data. We may want to do something like this
<form action="" method="post">
<input name="{{form.field_a.html_name}}" type="text" value="{{form.field_a.value}}" />
<input type="submit" value="Submit" />
</form>
But this may create some problem. If the field is optional and contains no data, in our generated html form, the value of that field will be "None".
Surely, this is not expected. To prevent this to happen, we may do the following
<form action="" method="post">
<input name="{{form.field_a.html_name}}" type="text" value="{{form.field_a.value|default_if_none:''}}" />
<input type="submit" value="Submit" />
</form>

Comments

Popular posts from this blog

Run tasks in background in Spring

Conditional field inclusion in Jackson and Spring Boot

How to configure Wildfly 10 to use MySQL