I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py
class CircuitForm(ModelForm): class Meta: model = Circuit exclude = ('lastPaged',) def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) self.fields['begin'].widget = widgets.AdminSplitDateTime() self.fields['end'].widget = widgets.AdminSplitDateTime()
In the actual Circuit model, the fields are defined like this:
begin = models.DateTimeField('Start Time', null=True, blank=True) end = models.DateTimeField('Stop Time', null=True, blank=True)
My views.py for this is here:
def addCircuitForm(request): if request.method == 'POST': form = CircuitForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/sla/all') form = CircuitForm() return render_to_response('sla/add.html', {'form': form})
What can I do so that the two fields aren't required?
You have to use self. fields[…]. required = True in the form's constructor to force required behaviour for those fields.
The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).
Writing validators A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can be useful for reusing validation logic between different types of fields. You can also use a class with a __call__() method for more complex or configurable validators.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class:
def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) for key in self.fields: self.fields[key].required = False
The redefined constructor won't harm any functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With