I Had created a detailed form in Django having some mandatory fields .I want to save page as Draft option without exception if mandatory fields are not set that time. How can I do it?
First set required=False for the fields that don't have to be set if you save as a draft. Then, to your form, add a field like 'save_as_draft' which is a boolean. Now you need a method to validate these fields depending on the state of save_as_draft field (whether user checked this field or not). You can use such a method:
def is_provided(self, field):
value = self.cleaned_data.get(field, None)
if value == None or value == '':
self._errors[field] = ErrorList([u'This field is required.'])
if field in self.cleaned_data:
del self.cleaned_data[field]
Add this method to your form and use it in form's clean method to validate your fields. This would look like this:
def clean(self):
draft = self.cleaned_data.get('save_as_draft', False)
if not draft:
# User doesn't save a draft so we need to check if required fields are provided
req_fields = ['field1', 'field2', 'field3']
for f in req_field:
self.is_provided(f)
return self.cleaned_data
If user prefer save_as_draft button instead of checkbox, then you would need to modify your view and pass some parameter to your form's constructor depending on whether user clicked save_as_draft button or just save button. In Form constructor save this state aa self.save_as_draft and use this in Form.clean method to check if you are saving draft or not.
Greetings, Lukasz