如何将 Django 用户帐户创建限制为给定的用户名/地址/实际值?
我们通过本教程设置了 Django 用户帐户创建/登录,并且我们仅通过 {% if user.is_authenticated %}
和 if 之类的方式将内容限制为经过身份验证的用户request.user.is_authenticated
。一切都很好。但仍然没有什么可以阻止任何人访问该网站并注册帐户,提供任何用户名/电子邮件地址/密码值。
我们希望将用户帐户创建限制为特定的用户名/电子邮件/IP/任何实用价值。我们可以通过插入类似 if email in ['[电子邮件受保护]']:
某处?有什么东西可以通过电子邮件发送邀请链接吗?
我们找到有关权限和授权的文档< /a> 以及许多关于为用户类型定制功能的问题,但我们找不到任何关于限制帐户创建本身的问题,所以也许我们遗漏了一些东西。
我们可以开始创建不同类型的用户,但在弄清楚这个基本步骤之前,我们要小心不要尝试更高级的解决方案而超出自己的预期。我们是否以正确的方式处理这个问题?
We've set up Django user account creation / login through this tutorial, and we've restricted content to auth'd users only through the likes of {% if user.is_authenticated %}
and if request.user.is_authenticated
. All works great. But there's still nothing stopping anyone from going to the site and registering an account providing any values for username / email address / password.
We want to restrict user account creation to specific usernames / emails / IPs / any practical value. Could we check if a value is in some whitelist by inserting something like if email in ['[email protected]']:
somewhere? Something that emails out an invite link?
We've found the docs on Permissions and Authorization and many SO questions on customizing functionality for types of users, yet we couldn't find any on restricting account creation itself, so perhaps we're missing something.
We could start creating different types of users, but we're wary of getting ahead of ourselves by attempting a more advanced solution before figuring out this basic step. Are we approaching this in the right way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
美好的一天,可能有很多方法可以实现您的要求。一个简单的技巧可能是使用 验证器。
由于您遵循的教程没有详细介绍,因此您将必须执行额外的步骤。
我不知道你的项目结构,因此我假设你了解 django 的基础知识。
创建自定义验证器
在名为
validators.py
的文件中添加以下内容(参见 django EmailValidator) :根据需要更改 EMAIL_PATTERN。
创建自定义表单
在名为
forms.py
的文件中添加如下内容:创建自定义注册视图
在
views.py
中,您必须创建一个自定义模板。
编辑您的网址
我的简单演示是一种使用
allowlist
arg 实现对电子邮件验证的限制的方法。还有很多其他方法可以做到这一点。Good day, there could be many ways to achieve what you're asking. A simple trick could be to use validators.
As the tutorial you followed does not dive in details, you will have to make extra steps.
I don't know your project structure, therefore I assume you know django's basics.
Create a custom validator
In a file called
validators.py
add following (c.f django EmailValidator) :Change EMAIL_PATTERN as you wish.
Create a custom form
In a file called
forms.py
add something as follow :Create a custom signup view
In your
views.py
You will have to create a custom template.
Edit your urls
My modest demonstration is a way to achieve a restriction on email validation using
allowlist
arg. There is many other ways to do so.