About Model-form Gotcha

If a field is listed in the model form, but not rendered in the frontend by accident, its value will be set to None by the form's save method.

For example, having this form:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "content", "post_type"]

The saving will lose the post_type value, because it isn't rendered in this template:

<form method="post" action=".">{% csrf_token %}
    {{ form.non_field_errors }}
    <div class="field-wrapper">
        {{ form.title.errors }}
        <label for="{{ form.title.id_for_label }}">Title:</label>
        {{ form.title }}
    </div>
    <div class="field-wrapper">
        {{ form.content.errors }}
        <label for="{{ form.content.id_for_label }}">Content:</label>
        {{ form.content }}
    </div>
    <button type="submit">Save</button>
</form>

However, if you skip the unwanted fields in the fields definition, their values will be preserved from previous setting.

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2