Web2py: Customizing Auth Forms

2019-07-24 02:20发布

问题:

I'm trying to customize the look-and-feel of our login, register, forgot username, and reset password forms. My preferred solution would be to use HTML forms directly, which may require creating new functions and views. At this point, I don't need custom fields.

Not exactly sure how to get this done (particularly what to do with the data submitted from the forms). Does anyone have experience getting this done, that can share their approach?


UPDATE - Solved this using Anthony's Suggestion. Login implementation shown below:

<form class="form-horizontal" method="post" style="margin-top:30px;">
  <div class="form-group">
    <label for="auth_user_username" class="col-sm-2 control-label">Username</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="auth_user_username" name="username" placeholder="Enter username">
    </div>
  </div>
  <div class="form-group">
    <label for="auth_user_password" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="auth_user_password" name="password" placeholder="Enter password">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <div class="checkbox">
        <label>
          <input id="auth_user_remember_me" name="remember_me" type="checkbox"> Remember me
        </label>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Login</button>
    </div>
  </div>
{{=form.custom.end}}

回答1:

You should still use the standard Auth forms on the server side -- then just customize how the fields are displayed in the view. There are various ways to customize forms (same principles apply to Auth forms as any other SQLFORM).

The simplest approach is to write a formstyle function (e.g., call it auth_formstyle), and then do:

auth.settings.formstyle = auth_formstyle

Alternatively, you can follow the approach described here to customize the forms using HTML in the views. You can also write completely custom HTML -- in that case, just be sure that the form input names match the field names used on the server, and also replace the closing </form> tag with {{=form.custom.end}} (that includes the hidden fields web2py needs for form processing and CSRF protection).

If you continue using a single user action and view for all forms, you can use logic in the view to display different forms depending on the specific Auth action:

def user():
    return dict(form=auth())

In the /default/user.html view:

{{if request.args(0) == 'login':}}
[custom login form markup]
{{elif request.args(0) == 'register':}}
[custom register form markup]
...
{{pass}}


标签: web2py