简体   繁体   English

自定义身份验证方法还是其他某种方法? Django的

[英]Custom authenticate method or maybe some other way to do the same? Django

this is a begginers question. 这是一个初学者的问题。 I have a database in mysql with tables to store users with a username and a password, simple as that. 我在mysql中有一个带有表的数据库,用于存储带有用户名和密码的用户,就这么简单。 I dont want to use the authentications backends and tables that django installs the first time you run 'SyncDb'. 我不想使用django首次运行“ SyncDb”时安装的身份验证后端和表。 So my question is: how do i tell django to use the database that i created instead of looking for active Users in the pre defined databases. 所以我的问题是:我如何告诉Django使用我创建的数据库,而不是在预定义的数据库中查找活动用户。 I´m using this code but of course this is looking for users in the already mention 'auth_user' table. 我正在使用此代码,但是当然这是在已经提到的“ auth_user”表中寻找用户。

class LoginView(FormView):
    form_class = LoginForm
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'login.html'
    success_url = 'index'

    def form_valid(self, form):
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user = authenticate(username=username, 
                            password=password)
        if user is not None:
            if user.is_active:
                login(self.request, user)
                return HttpResponseRedirect(self.get_success_url())
        else:        
            return self.form_invalid(form)

    def form_invalid(self):
        return HttpResponseRedirect(reverse('app_name:login'))

    def get_success_url(self):
        if self.success_url:
            redirect_to = self.success_url
        else:
            redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')

        netloc = urlparse.urlparse(redirect_to)[1]
        if not redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
        elif netloc and netloc != self.request.get_host():
            redirect_to = settings.LOGIN_REDIRECT_URL
        return redirect_to

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        if form.is_valid():
            return self.form_valid(form)
        else:                
            return self.form_invalid()

So that´s my begginers question. 这就是我的初学者的问题。 Thank you very much 非常感谢你

PS: my form_invalid() is not working...(error: passing 2 parameters instead of 1) any suggestions please tell me. PS:我的form_invalid()无法正常工作...(错误:传递2个参数而不是1个参数)任何建议请告诉我。 Again, thank you very much 再次非常感谢

We had to figure this out for our project and the initial confusion comes from the fact that you basically need to handle two issues in Django to make this happen: 我们必须为我们的项目弄清楚这一点,最初的困惑来自以下事实:您基本上需要在Django中处理两个问题才能实现:

1) Make sure that that app is routed to the correct database 1a) Make sure that other database can actually be written by Django 1)确保该应用已路由到正确的数据库1a)确保其他数据库实际上可以由Django编写

2) Create an "app" module to use to overwrite the default user model 2)创建一个“应用”模块以覆盖默认的用户模型

Luckily this is pretty much straightforward once the problem is clearly defined. 幸运的是,一旦明确定义了问题,这非常简单。

https://docs.djangoproject.com/en/dev/topics/db/multi-db/ https://docs.djangoproject.com/en/dev/topics/db/multi-db/

The first section "Defining your databases" will show you how to add additional databases to your project. 第一部分“定义数据库”将向您展示如何向项目中添加其他数据库。 Make sure you have credentials for Django to use to access, so depending on your access structure, that may include an additional step or not. 确保您具有用于访问的Django凭据,因此取决于您的访问结构,该凭据可能包含附加步骤,也可能不包含附加步骤。

After that the section "Automatic database routing" will explain the general idea behind db routers. 之后,“自动数据库路由”部分将解释db路由器背后的一般思想。 However, I recommend you check out this excellent discussion and leverage that code to make your database routing easier: http://justcramer.com/2010/12/30/database-routers-in-django/ . 但是,我建议您检查一下这个精彩的讨论,并利用该代码简化数据库路由: http : //justcramer.com/2010/12/30/database-routers-in-django/ This way you can just make your project use this router and define a lib in your settings.py (DATABASE_CONFIG) to tell each application where to route after setting DATABASE_ROUTERS to the code at the link. 这样,您就可以使您的项目使用此路由器,并在settings.py(DATABASE_CONFIG)中定义一个lib,以在将DATABASE_ROUTERS设置为链接中的代码后告诉每个应用程序将路由到何处。 Make your default router the one with all the django stuff, then define your legacy db whenever necessary. 使您的默认路由器成为具有所有django内容的路由器,然后在必要时定义旧版数据库。

Lastly, for the user model check out the docs on "Customizing authentication in Django" (I can't post the link because this is my first answer and I do not have enough reputation). 最后,对于用户模型,请查看“在Django中自定义身份验证”文档(我无法发布链接,因为这是我的第一个答案,并且我的信誉不高)。 You will need to write a custom model (and potentially admin forms and custom authentication for permissions based on your implementation) and include it through your project settings.py with AUTH_USER_MODEL. 您将需要编写一个自定义模型(以及可能的管理表单和基于您的实现的权限的自定义身份验证),并将其包含在您的项目settings.py中,并带有AUTH_USER_MODEL。 The key section on that page is "Substituting a custom User model". 该页面上的关键部分是“替换自定义用户模型”。 If it is as simple as just matching a password to a user it should be mostly painless, however, be careful how your passwords are hashed. 如果只是简单地将密码与用户匹配就简单,那么应该很容易,但是请注意如何对密码进行哈希处理。 PASSWORD_HASHERS in your settings.py tells django the hashers to use on passwords when saving them (and the preferred order). 您settings.py中的PASSWORD_HASHERS告诉django哈希器在保存密码(以及首选顺序)时使用密码。 If you want to keep a certain hashing scheme you need to move that to the top of the list, otherwise, Django will port it to the first listed and thus preferred scheme when it needs to do a PW access. 如果要保留某种哈希方案,则需要将其移动到列表的顶部,否则,Django将在需要进行PW访问时将其移植到第一个列出的首选方案。 This is actually a great feature as it will auto-migrate passwords to stronger schemes, but may be something to be mindful of if you need to integrate with other systems. 这实际上是一个很棒的功能,因为它将自动将密码迁移到更强大的方案中,但是如果您需要与其他系统集成,则可能需要牢记。

As a general pointer (and this is in no way intended as a RTM) the Django documents are very good and will typically answer your questions (and if not the source is quite readable and I've had to solve a few things that way). 作为通用指针(决不是RTM),Django文档非常好,并且通常会回答您的问题(如果不是,则源代码可读性强,我不得不以这种方式解决一些问题) 。 However, as you might notice, until you realize the issue you are trying to fix, and what Django calls it, it can be a little confusing to fit the pieces together. 但是,您可能会注意到,在意识到要解决的问题以及Django所说的问题之前,将各个部分组合在一起可能会有些混乱。 It will be worth your time if you plan to do anything at all with Django to get a good read of the primary documentation, possibly twice, to help make the pieces fit. 如果您打算对Django进行任何操作以使主要文档有一个很好的阅读,这可能值得您花费时间,可能要两次,以帮助使这些文档变得合适。 Hopefully this answers your question and gives you a sense of where to go, as you can see this scenario can get a little broad so let me know if a more specific question gives you issues, otherwise these are the key points I recall implementing and during a code review as I wrote this. 希望这可以回答您的问题,并让您对应该去的方向有所了解,因为您可以看到这种情况可能会有所扩展,因此,请让我知道是否有更具体的问题给您带来问题,否则,这些就是我记得在实施和实施过程中要注意的重点我撰写本文时进行了代码审查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM