views:

1596

answers:

6

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?

+2  A: 

If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True

Says so here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

Looks like you are doing everything right. You could check the value of self.fields['end'].required.

stefanw
A: 

I have this same problem, I have a model field with blank set to false. The modelform will save blank but when I add the AdminSplitDateTime widget I get the "Enter a valid date/time." message. This must be a bug.

anteatersa
+4  A: 

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.

DataGreed
Nice tip. I used this idea to add a Meta.required_fields attribute:` `` def __init__(self, *args, **kwargs):`` super(ProfileForm, self).__init__(*args, **kwargs)`` `` for key in self.Meta.required_fields:`` self.fields[key].required = True`
andybak
+1  A: 

It's not an answer, but for anyone else who finds this via Google, one more bit of data: this is happening to me on a Model Form with a DateField. It has required set to False, the model has "null=True, blank=True" and the field in the form shows required=False if I look at it during the clean() method, but it's still saying I need a valid date format. I'm not using any special widget and I get the "Enter a valid date" message even when I explicitly set input_formats=['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', ''] on the form field.

EDIT: Don't know if it'll help anyone else, but I solved the problem I was having. Our form has some default text in the field (in this case, the word "to" to indicate the field is the end date; the field is called "end_time"). I was specifically looking for the word "to" in the form's clean() method (I'd also tried the clean_end_time() method, but it never got called) and setting the value of the clean_data variable to None as suggested in this Django ticket. However, none of that mattered as (I guess) the model's validation had already puked on the invalid date format of "to" without giving me a chance to intercept it.

Tom
A: 

This is a bug when using the widgets:

workaround: http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/1833247#1833247

or ticket 12303

Samuel Adam
A: 

This was a useful post and I think it is rather easy to see from the other comments as well that this post is well written and useful.

Supra Shoes