Django Save Incomplete Progress on Form

后端 未结 3 1619
北海茫月
北海茫月 2021-01-11 20:38

I have a django webapp with multiple users logging in and fill in a form.

Some users may start filling in a form and lack some required data (e.g., a grant #) need

相关标签:
3条回答
  • 2021-01-11 21:01

    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(...)
    form.save()
    

    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.

    0 讨论(0)
  • 2021-01-11 21:07

    before Saving:

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

    then:

    form.save()
    
    0 讨论(0)
  • 2021-01-11 21:14

    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.

    0 讨论(0)
提交回复
热议问题