Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django required field in model form

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?

like image 353
Ryan Avatar asked Jul 15 '09 23:07

Ryan


People also ask

How do you make a model field required in Django?

You have to use self. fields[…]. required = True in the form's constructor to force required behaviour for those fields.

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

How can you validate Django model fields?

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.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.


1 Answers

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.

like image 122
DataGreed Avatar answered Sep 20 '22 18:09

DataGreed