我使用第三方应用程序 django-registration 作为我的 django 项目的注册系统。 我创建了registration_form.htlm:
<form method="post">
{% csrf_token %}
<h1 class="h3 mb-3 fw-normal">Sign up</h1>
<div class="form-floating">
<input
class="form-control"
id="floatingInput"
placeholder="name"
name="username"
/>
<label for="floatingInput">User</label>
</div>
<div class="form-floating">
<input class="form-control" placeholder="Email" name="email" />
<label for="floatingPassword">Email</label>
</div>
<div class="form-floating">
<input
type="password"
class="form-control"
id="floatingPassword"
placeholder="Password"
name="password1"
/>
<label for="floatingPassword">Password</label>
</div>
<div class="form-floating">
<input
type="password"
class="form-control"
id="floatingPassword"
placeholder="Password"
name="password2"
/>
<label for="floatingPassword">Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" /> Remember me
</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">
Sign Up
</button>
</form>
正如您在上面看到的,我必须指定电子邮件,否则表格不起作用。那么有什么技巧可以让电子邮件填写成为可选的,这意味着如果用户不提供电子邮件,表单仍然可以成功提交。
要使注册表中的电子邮件字段可选,您可以修改 Django 注册表和视图来处理这种情况。
您将需要创建一个继承自 django-registration 提供的原始表单的自定义注册表单。您可以覆盖字段的必填属性以使电子邮件字段成为可选字段。
class CustomRegistrationForm(RegistrationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['email'].required = False