Chitrank Dixit
Chitrank Dixit

Reputation: 4051

flask-wtf DateField gets failed in validation even after choosing the date

Hello Flask Developers,

I am using DateField to specify my Date of my Posts. Now I am taking appropriate specifiers for my model, forms , views and jinja2 template system but still date is not able to validate. I am picking the right date from the date picket but the message comes at the bottom of the datepicker as 'This field is required' but there is no sense to see this message as I have already picked the date. Here is my code that would let you know the problem.

my model

class Post(Base, modelx.EventX):
    poster = ndb.StringProperty(indexed= True, required=True)
    postbody = ndb.StringProperty(indexed=True, required=True)
    start_date = ndb.DateProperty(indexed= True, required=True)

my forms

class CreatePost(wtf.Form):
    poster = wtf.TextField('Post', validators=[validators.Required()])
    postbody= wtf.TextAreaField('postbody', validators=[validators.Required()])
    sdate= wtf.html5.DateField('Date', default='',validators=[validators.Required()], format='%m/%d/%Y')

my views

@app.route('/poster/',methods=['POST','GET'])
def post_it():
  form = CreatePost(request.form)
  if form.validate_on_submit() and request.method=='POST':
    posting = model.Post(
        poster = form.poster.data,
        postbody = form.postbody.data,
        sdate= form.sdate.data
      )
    try:
      posting.put()
      flash("Poster has been populated")
      return (redirect(url_for('post_it')))
    except CapabilityDisabledError:
      flash('Error Occured while posting')
      return redirect(url_for('post_it'))
  return render_template('poster.html', form=form)

my poster.html

{% extends 'base.html' %}
{% import 'macro/error.html' as forms %}
{% block title %} Post Something | Eventus {% endblock %}
{% block style_block %}
  <link href="{{ url_for('static', filename='font-awesome/css/font-awesome.css') }}" rel="stylesheet" />
  <link href="{{ url_for('static', filename='bootstrap/css/social-buttons.css') }}" rel="stylesheet" />
  <style type="text/css">
    .background {
       background-color: #F3F3F3;
      }
    p.error {
        color: red;
    }
  </style>
{% endblock %}
{% block content %}

    <form action="{{ url_for('post_it') }}" class="navbar-form form-inline" method="post" id="new_postform">
    {{ form.csrf_token }}
        <fieldset>
          {{ form.hidden_tag() }}


            {% from "macro/_formhelpers.html" import render_field %}
            <div class="control-group">
                <p>{{ form.poster.label }}</p>
                  <div class="controls">

                        <p>
                        {{ form.poster(id='post',class='form-control required ',placeholder="My Post", autocomplete=True , size=3,**{'data-bind': 'value: bodyte'})}}</p>
                        {% if form.poster.errors %}
                        <ul class="errors">
                            {% for error in form.confirm.errors %}
                            <li>{{ error }}</li>
                            {% endfor %}
                        </ul>
                        {% endif %}
                    </div>


            </div>
            <div class="control-group">
                <p>{{ form.postbody.label }}<p>
                  <div class="controls">


                        <p>{{ form.postbody(id='postbody',class='form-control required ',placeholder="Post Description", autocomplete=True , size=3,**{'data-bind': 'value: bodyte'})}}</p>

                    </div>


            </div>
            <div class="control-group">
            <div class="controls">
                        {{ form.sdate.label }}
                        {{ form.sdate(id="est", class="required", formatString="MM/DD/YYYY") }}
                        {% if form.sdate.errors %}
                        <ul class="errors">
                            {% for error in form.sdate.errors %}
                            <li>{{ error }}</li>
                            {% endfor %}
                        </ul>
                        {% endif %}
            </div>
        </div>
            <div class="control-group">
                    <div class="controls">
                        <br><input type="submit" id="postit"  name="postit" value"poster" class="btn btn-primary" /><br><br>

                    </div>
            </div>
          </fieldset>
    </form>
    <div class="controls">
 <!-- <p>Post: <input data-bind="value: bodyte" class="form-control" name="posts" /></p> -->
                    </div>
                    <p>BodyText: <strong data-bind="text: bodytext" /></strong></p>


{% block tail_script %}
<script src="{{ url_for('static', filename='bootstrap/js/jquery.validate.js') }}"></script>
<script src="{{ url_for('static', filename='bootstrap/js/additional-methods.js') }}"></script>
<script type="text/javascript">
 $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
 // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
    this.bodyte = ko.observable();
    this.bodytext = ko.computed(function(){
        return this.bodyte();

    }, this);

}

// Activates knockout.js
ko.applyBindings(new AppViewModel());


$(document).ready(function () {



$('#new_postform').validate({
    rules: {
        post: {
            minlength: 2,
            required: true
        }

    },
    highlight: function (element) {
        $(element).parent().css('border-color','red');
        $(element).text('Please type some post').closest('.control-group').removeClass('success').addClass('error');

    },
    success: function (element) {
        element.text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
    }
});
});


</script>

{% endblock %}


{% endblock %}

Please let me know where My Post and Post body gets validated fine but my Date named 'sdate' does not get validated, Please let me know If I need to add any attribute for form.sdate(...) field.

Please let me know where I am commiting mistake that is preventing my date to validate event after selecting date from the datepicker right.

Upvotes: 1

Views: 2606

Answers (2)

Achim Munene
Achim Munene

Reputation: 536

I have been experiencing the same problem with my DateFields so what i actually did was to not use the DateField but to use a StringField instead and convert the date string into a datetime object in the validate method of the form

class Example(FlaskForm):
      name = StringField('name', validators=[DataRequired()])
      dob = StringField('dob')

def validate(self):
    today = datetime.datetime.strptime(str(self.dob.data), '%d-%m-%y').date()
    self.dob.data = today
    return True

You can keep your templates the same way and use your datepicker too..

hope it works for you..

Upvotes: 1

Satish Viswanathan
Satish Viswanathan

Reputation: 47

Since Jinja ultimately renders HTML, wherever there is a problem, I generally use the html tags directly with out any problems. Maybe you can try that out. In any case what have you come out with as a workaround or solution?

Upvotes: 0

Related Questions