Django结合Bootstrap 5的注册表单POST提交未获取到任何字段数据
问题根因
你提交的表单所有<input>标签未设置name属性,浏览器默认只会将带有name属性的表单字段内容封装到POST请求里发送到后端,因此Django接收到的request.POST是空对象,表单验证时就会提示所有字段为必填项。
修复步骤
- 给每个
<input>标签添加和Django表单字段对应的name属性,对应关系如下:- 用户名字段:
name="username" - 手机号字段:
name="phone_number" - 邮箱字段:
name="email" - 密码1字段:
name="password1" - 密码2字段:
name="password2"
- 用户名字段:
- 可选优化:将密码输入框的
type从text改为password,避免输入时明文显示,同时将邮箱输入框的type改为email可触发浏览器自带的邮箱格式校验。
修正后的HTML表单代码示例
<div class="card" id='signup_card'> <div class='card-header'> <h2 class='card-title'>Sign Up</h2> </div> <div class='card-body'> <form method='POST' action="" id='create_user_form' style="color: #fff;"> {% csrf_token %} <label for='usernameInput' class="form-label">{{form.username.label}}:</label> <input type="text" name="username" id='usernameInput' style="margin-bottom: 20px;"> <label for='phoneNumberInput' class="form-label">{{form.phone_number.label}}:</label> <input type="text" name="phone_number" id='phoneNumberInput' style="margin-bottom: 20px;"> <label for='emailInput' class="form-label">{{form.email.label}}:</label> <input type="email" name="email" id='emailInput' style="margin-bottom: 20px;"> <label for='password1Input' class="form-label">{{form.password1.label}}:</label> <input type="password" name="password1" id='password1Input' style="margin-bottom: 20px;"> <label for='password2Input' class="form-label">{{form.password2.label}}:</label> <input type="password" name="password2" id='password2Input' style="margin-bottom: 20px;"> <button class="btn btn-primary" type='submit'>Submit</button> </form> </div>
内容的提问来源于stack exchange,提问作者B3CTOR
相关产品推荐
相关产品推荐

