[Solved]-Django Save Incomplete Progress on Form


before Saving:

for field in form.fields:
    form.fields[field].required = False




The issue is that you have multiple Forms.

Partial. Incomplete. Complete. Ready for this. Ready for that.

Indeed, you have a Form-per-stage of a workflow.

Nothing wrong with this at all.

  1. Figure out where in the workflow you are.

  2. Populate and present the form for the next stage.

Forms can inherit from each other to save repeating validation methods.



Place the following into your form __init__

for field in form.fields:
    form.fields[field].required = False

For example:

class MySexyForm(Form):
    def __init__(self, *args, **kwargs):
        super(MySexyForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].required = False

Then call:

form = MySexyForm(...)

However you’ll need to make sure your clean() method can handle any missing attributes by conditionally checking if they exist in cleaned_data. For example, if another form field validation relies on customer_id but your partial form have not specified one, then customer_id would not be in cleaned_data.

If this is for a model form, you could check if the value was in cleaned_data, and fallback onto instance.field if it was missing, for example;

def clean(self):
    inst = self.instance
    customer_id_new = self.cleaned_data.get('customer_id', None)
    customer_id_old = getattr(self.instance, 'customer_id') if inst else None
    customer_id = customer_id_new if customer_id_new else customer_id_old

Remember that the value new value will almost certainly not be in the same format as the old value, for example customer_id could actually be a RelatedField on the model instance but an pk int on the form data. Again, you’ll need to handle these type differences within your clean.

This is one area where Django Forms really are lacking sadly.

Leave a comment