且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django 中用于身份验证的多种用户类型

更新时间:2023-11-30 23:50:28

我认为最简单的方法是在你的项目中有 3 个应用程序:你的***应用程序,一个专业"应用程序和客户端"应用程序.在***应用程序中,您真正需要做的就是为用户提供一个登录表单和 2 个链接,一个用于注册为专业人士,另一个用于注册为客户.

I think the easiest way for you to do what you are talking about is going to be to have 3 apps in your project: your top level app, a "professional" app and a "client" app. At the top level app, all you really need to do is give the users a login form, and 2 links, one for registering as a Professional and one for registering as a Client.

在这种情况下,我相信您使用 Django 的内置权限系统将是最简单的,并将每种类型的用户分配到相应的组(例如专业人士和客户).您可以在视图上使用装饰器以确保只有特定组的成员才能访问该视图(因为每个组有 2 个单独的应用程序,您可以为每个视图中的所有视图添加装饰器,或者您可以导入 Django 的授权功能进入您的 urls.py 并在那里检查它,尽管这超出了本答案的范围).

In this case, I believe it will be easiest for you to use Django's built in Permissions system, and assign each type of user to a corresponding group (eg. professionals and clients). You can use a decorator on your views to ensure that only members of a particular group can access that view (since you have 2 separate apps for each group, you can add a decorator to all views in each of them, or you can import Django's authorization functions into your urls.py and check it there, although that is beyond the scope of this answer).

注册很容易,使用您的 urls.py 文件将想要注册的用户转发到正确的应用程序.一旦你这样做了,你应该能够在每个应用程序上使用 django-allauth 注册,允许你创建 2 种不同类型的用户.确保在注册时,您将他们分配给正确的群组成员资格.

Registration is easy enough, use your urls.py file to forward the user that wants to register to the correct app. Once you do that, you should be able to use django-allauth registration on each app, allowing you to create 2 different kinds of users. Make sure when the register, you assign them to the correct group membership.

至于登录重定向,一旦您收到 POST 数据,我会检查登录的用户类型,并使用它来将用户转发到与 Professional 或 Client 应用程序一起使用的正确 URL.您可以查看以下链接,了解登录后重定向用户的想法.

As for the login redirection, once you receive the POST data, I would check for which type of user logged in, and use that to forward the user to the correct URL that goes with the Professional or Client app. You can see the below link for an idea of redirecting a user after login.

Django - 登录后,将用户重定向到他的自定义页面 -->mysite.com/用户名