1

models:

def deliver_after_default():
    return timezone.now().date()


deliver_after = models.DateField(default=deliver_after_default,
    blank=True,
    help_text="Don't delivery email or physical card until after this "
    "date. Delivery on this date cannot be guaranteed."
)

I have Django autocreating a ModelFormf or this model. In my template:

      <input class="form-control" name="{{ order_form.deliver_after.html_name }}" value="{{ order_form.deliver_after.value }}" type="date" />

order_form.deliver_after.value gets rendered as 'Nov. 25, 2015'. Trying to submit that value in a form causes validation to fail:

{"deliver_after": ["Enter a valid date."]}

Am I missing something? Shouldn't Django be outputting initial values that can pass valdiation?

Seán Hayes
  • 4,060
  • 4
  • 33
  • 48

2 Answers2

0

I just realized I've rendering order_form.deliver_after.value directly, which is a date object. I probably need to use a Django DateInput widget to render the value.

Seán Hayes
  • 4,060
  • 4
  • 33
  • 48
0

This just bit me too. My first inclination was to do as suggested by angel cruijff in the comments above, but that only works on the initial form load when the field contains a date.

If the form fails validation on another field, the date field value will now be a string and the |date filter ends up returning nothing - that is to say it blanks the field.

To solve this I created the following template filter:

@register.filter()
def render_value_as_widget_would(bound_field):
    natural_value = bound_field.value()
    if hasattr(bound_field.field.widget, '_format_value'):
        return bound_field.field.widget._format_value(natural_value)
    return natural_value

Then in my template, after loading the custom filters module, I did something like {{ order_form.deliver_after|render_value_as_widget_would }} where you have {{ order_form.deliver_after.value }}.

meshantz
  • 1,566
  • 10
  • 17