Pyramid simpleform date and time format

155 views
Skip to first unread message

Cem Ikta

unread,
May 10, 2013, 9:02:41 AM5/10/13
to pylons-...@googlegroups.com
Hello,

I am using Pyramid Simpleform, Mako templates and SQLAlchemy and I have trouble with the date and time formats in Mako templates.

How can I format date and time with simpleform in mako templates?

when I use such as "form = Form(self.request, schema=PersonsForm, obj=person)" then in html form date format is "2013-05-01".

Any suggestions? or what is the best practices with date and time formats with simpleform + mako templates?

##############################
# sqlalchemy model
class Person(Base):
    ...
    person_date = Column(Date, nullable=False,  default=datetime.now())
    person_time = Column(Time, nullable=False,  default=datetime.now())
    ...

# view

# person form schema
class PersonsForm(Schema):
    filter_extra_fields = True
    allow_extra_fields = True

    ...   
    person_date = validators.DateConverter(month_style='mm/dd/yyyy', not_empty=True)
    person_time = validators.TimeConverter(use_datetime=True, use_seconds=False, not_empty=True)
    ...

@view_config(route_name="persons_new", renderer="persons/new.html")
def new(self):
    """new person """
   ...
  
   form = Form(self.request, schema=PersonsForm)
      
   if "form_submitted" in self.request.POST and form.validate():
       dbsession = DBSession()
       person = form.bind(Person())
       dbsession.add(person)
       self.request.session.flash("alert-success;New person is saved!")
       return HTTPFound(location = self.request.route_url("persons_index"))
      
   return dict(form=FormRenderer(form),
              action_url=self.request.route_url("persons_new"))
  
@view_config(route_name="persons_edit", renderer="persons/edit.html")
def edit(self):
    """persons edit """
    param_id = self.request.matchdict['id']
    dbsession = DBSession()
    person = dbsession.query(Person).filter_by(id=param_id).one()
   
    if person is None:
        self.request.session.flash("alert-error;Person not found!")
        return HTTPFound(location=self.request.route_url("persons_index"))       
   
    form = Form(self.request, schema=PersonsForm, obj=person)   
    if "form_submitted" in self.request.POST and form.validate():
        form.bind(person)
        dbsession.add(person)
        self.request.session.flash("alert-success;The person is saved!")
        return HTTPFound(location = self.request.route_url("persons_index"))
   
    action_url = self.request.route_url("persons_edit", id=param_id)
    return dict(form=FormRenderer(form),
                action_url=action_url)


# in date and time fields in mako template
<div class="${'control-group error' if form.errors_for('person_date') else 'control-group'}">
    <label class="control-label" for="location">Person date</label>
    <div class="controls">
        ${form.text("person_date", class_="input-medium",
            placeholder="mm/dd/yyyy")}
        <span class="help-inline">${validate_errors("person_date")}</span>
    </div>
</div>

<div class="${'control-group error' if form.errors_for('person_time') else 'control-group'}">
    <label class="control-label" for="location">Person time</label>
    <div class="controls">
        ${form.text("person_time", class_="input-medium",
            placeholder="hh:mm")}
        <span class="help-inline">${validate_errors("person_time")}</span>
    </div>
</div>
  

Dan

unread,
Oct 19, 2013, 7:16:45 AM10/19/13
to pylons-...@googlegroups.com
Did you have any luck determining a way to convert the format without adding too much extra code? It seems that the only way you can do this is to not rely on the wrappers that FormRender uses. The reason is because it will just print out the raw date which is "YYYY-MM-DD" and that isn't compatible with the DateConverter validator. Furthermore, you can't just pass form.text the value you want it to display because it will only use that value as a default. That means if you have a value from your object (which we do) your alternative value is overridden by the unformatted original. I am concluding that I can get the value from the form vai form.value(<date field name>), then I can pass this into a one-off field from webhelpers, but this bothers me as I would have to remember to use Webhelpers without the form renderer wrapper for date fields. I know it isn't a big deal, but it is making my OCD-like tendencies flake out.

Maybe there is a way to pass a date format string through kwargs, but if there is one then it isn't documented very well.

Chris Lambacher

unread,
Oct 19, 2013, 8:54:12 PM10/19/13
to pylons-...@googlegroups.com
Hi,

FormRenderer is specifically designed to be overridden so that you can create custom versions. Also not that yyyy-mm-dd is ISO format which is basically all you can use reliably with i18n if you are going to use the HTML 5 date field. I'd support a patch to the default renderer that added an optional constructor arg for the renderer that configured a format function for dates/times.

-Chris


--
You received this message because you are subscribed to the Google Groups "pylons-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pylons-discus...@googlegroups.com.
To post to this group, send email to pylons-...@googlegroups.com.
Visit this group at http://groups.google.com/group/pylons-discuss.

For more options, visit https://groups.google.com/groups/opt_out.



--
Christopher Lambacher
ch...@kateandchris.net
Reply all
Reply to author
Forward
0 new messages