Django-使用mongoengine DB进行身份验证

BugFixer

我想使用mongoengine db在Django项目中处理身份验证。

我尝试了一些有关此问题的示例,这些问题在旧问题中得到了回答,但没有运行。我正在使用Django 1.6和mongoengine。一切都已安装,运行,并且我可以创建文档并将其保存到我的Mongoengine数据库中。

我正在追踪http://mongoengine-odm.readthedocs.org/en/latest/django.html

而且我得到以下错误:

当我跑步时:

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', '[email protected]', 'johnpassword')

我得到这个:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/REBORN/reb_env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 273, in __get__
    self.model._meta.object_name, self.model._meta.swapped
AttributeError: Manager isn't available; User has been swapped for 'mongo_auth.MongoUser'
>>> 

我真的不明白两件事:

-是否必须创建并定义将存储用户的数据库,否则将自动创建用户?

-经理是什么?我还没有定义任何经理内容

在开始时,我认为寄存器已保存在数据库中。调用了“ mongo_auth.MongoUser”,但没有将其保存在任何地方。

这是模型:

# Create your models here.
from mongoengine import *

class Profile(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

class auth_user(Document):
    username = StringField(max_length=50)
    email = StringField(max_length=50)
    password = StringField(max_length=50)

settings.py已按照手册所述正确配置。

编辑@cestDiego:

我的设置完全相同,我注意到了Db后端,因为它创建了一个我不感兴趣的数据库,因为我使用mongo ...无论如何,我现在使用的是mongoengine.django.auth import用户,但是当我尝试时创建一个用户,它返回我:

>>> user = User.objects.create_user('john', '[email protected]', 'johnpassword')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'create_user'

也许我们正在自定义auth,这就是为什么不起作用,不知道的原因。你也有这个问题吗?

第二编辑:

我正在阅读,配置正确的设置后,我们必须使用Django的auth,就像我们所做的一样。

然后必须从django.contrib.auth导入import authenticate并使用Django文档中提供的authenticate,希望对您有所帮助。

from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from game.models import *
from mongoengine import *
from models import User
from django.contrib.auth import authenticate

def login(request):
        user = authenticate(username='john', password='secret')
        if user is not None:
            # the password verified for the user
            if user.is_active:
                print("User is valid, active and authenticated")
            else:
                print("The password is valid, but the account has been disabled!")
        else:
            # the authentication system was unable to verify the username and password
            print("The username and password were incorrect.")
BugFixer

我解决问题

在Django 1.6中...

我的settings.py看起来像这样:

"""
Django settings for prova project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^%r&tw5_steltu_ih&n6lvht0gs(0p#0p5z0br@+#l1o(iz_t6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sessions',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
)

ROOT_URLCONF = 'prova.urls'

WSGI_APPLICATION = 'prova.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy'
    }
}
AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

和我的views.py看起来像:

from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from game.models import *  
from mongoengine import *
#from django.contrib.auth import authenticate
from mongoengine.django.auth import User

def login(request):
    connect('reborn')
    from django.contrib.auth import login
    from mongoengine.django.auth import User
    from mongoengine.queryset import DoesNotExist
    from django.contrib import messages
    try:
        user = User.objects.get(username='bob')#request.POST['username'])
        if user.check_password('bobpass'):#request.POST['password']):
            user.backend = 'mongoengine.django.auth.MongoEngineBackend'
            print login(request, user)
            request.session.set_expiry(60 * 60 * 1) # 1 hour timeout
            print "return"
            return HttpResponse("LOGUEJAT")#redirect('index')
        else:
            print "malament"
            messages.add_message(request,messages.ERROR,u"Incorrect login name or password !")
    except DoesNotExist:
        messages.add_message(request,messages.ERROR,u"Incorrect login name or password !")
    return render(request, 'login.html', {})

def logout(request):#NOT TESTED
    from django.contrib.auth import logout
    logout(request)
    return redirect('login')

def createuser(request): 
    connect('reborn')
    User.create_user('boba','bobpass','[email protected]')
    return HttpResponse("SAVED")

现在,将用户对象保存在数据库中,如下所示:

{
    "_id" : ObjectId("53465fa60f04c6552ab77475"),
    "_cls" : "User",
    "username" : "boba",
    "email" : "[email protected]",
    "password" : "pbkdf2_sha256$12000$ZYbCHP1K1kDE$Y4LnGTdKhh1irJVktWo1QZX6AlEFn+1daTEvQAMMehA=",
    "is_staff" : false,
    "is_active" : true,
    "is_superuser" : false,
    "last_login" : ISODate("2014-04-10T09:08:54.551Z"),
    "date_joined" : ISODate("2014-04-10T09:08:54.550Z"),
    "user_permissions" : [ ]
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Django-使用mongoengine数据库进行身份验证

来自分类Dev

使用Django REST Framework进行身份验证会返回405

来自分类Dev

在php中使用django密码进行身份验证

来自分类Dev

使用ldap配置文件在django admin中进行身份验证

来自分类Dev

使用django-all-access向LinkedIn进行身份验证

来自分类Dev

使用Django和Twilio通过SMS进行一次性用户身份验证

来自分类Dev

Django使用登录的Windows域用户进行身份验证

来自分类Dev

在Django Rest Framework中使用令牌身份验证进行身份验证时,不会更新last_login字段

来自分类Dev

如何使用密钥对连接的应用程序进行身份验证?Django,Python

来自分类Dev

使用Django REST进行LDAP身份验证

来自分类Dev

使用Django REST Framework作为Django的身份验证后端

来自分类Dev

使用哈希密码而不是原始密码在django中对功能进行身份验证

来自分类Dev

使用GraphQL和Django进行身份验证

来自分类Dev

如何在graphene-django GraphQLTestCase中使用django-grahql-jwt进行身份验证?

来自分类Dev

使用Django身份验证进行Flutter到Flutter的Web迁移

来自分类Dev

我无法使用django通过我的api进行身份验证

来自分类Dev

如何通过django-microsoft-auth使用Azure AD在Django中进行身份验证

来自分类Dev

使用Firebase进行身份验证,使用MongoDB for DB

来自分类Dev

使用Django REST Framework进行身份验证会返回405

来自分类Dev

使用ldap配置文件在django admin中进行身份验证

来自分类Dev

django身份验证可以与django rest框架基本身份验证结合使用吗?

来自分类Dev

无法使用django rest框架进行身份验证(request.user = AnonymousUser)

来自分类Dev

无法使用Django和ldap进行身份验证

来自分类Dev

如何使用 Postman 对 Django REST Framework 进行身份验证

来自分类Dev

Django 使用 Google 和 VK 进行身份验证?

来自分类Dev

在 Python Django 中使用一个帐户进行多用户身份验证?

来自分类Dev

使用 Django 和 Angular 进行 Windows 身份验证?

来自分类Dev

使用 Django 进行 LDAP 身份验证

来自分类Dev

无法使用 MongoEngine 进行身份验证。PyMongo 有效。如何让 MongoEngine 进行身份验证?

Related 相关文章

  1. 1

    Django-使用mongoengine数据库进行身份验证

  2. 2

    使用Django REST Framework进行身份验证会返回405

  3. 3

    在php中使用django密码进行身份验证

  4. 4

    使用ldap配置文件在django admin中进行身份验证

  5. 5

    使用django-all-access向LinkedIn进行身份验证

  6. 6

    使用Django和Twilio通过SMS进行一次性用户身份验证

  7. 7

    Django使用登录的Windows域用户进行身份验证

  8. 8

    在Django Rest Framework中使用令牌身份验证进行身份验证时,不会更新last_login字段

  9. 9

    如何使用密钥对连接的应用程序进行身份验证?Django,Python

  10. 10

    使用Django REST进行LDAP身份验证

  11. 11

    使用Django REST Framework作为Django的身份验证后端

  12. 12

    使用哈希密码而不是原始密码在django中对功能进行身份验证

  13. 13

    使用GraphQL和Django进行身份验证

  14. 14

    如何在graphene-django GraphQLTestCase中使用django-grahql-jwt进行身份验证?

  15. 15

    使用Django身份验证进行Flutter到Flutter的Web迁移

  16. 16

    我无法使用django通过我的api进行身份验证

  17. 17

    如何通过django-microsoft-auth使用Azure AD在Django中进行身份验证

  18. 18

    使用Firebase进行身份验证,使用MongoDB for DB

  19. 19

    使用Django REST Framework进行身份验证会返回405

  20. 20

    使用ldap配置文件在django admin中进行身份验证

  21. 21

    django身份验证可以与django rest框架基本身份验证结合使用吗?

  22. 22

    无法使用django rest框架进行身份验证(request.user = AnonymousUser)

  23. 23

    无法使用Django和ldap进行身份验证

  24. 24

    如何使用 Postman 对 Django REST Framework 进行身份验证

  25. 25

    Django 使用 Google 和 VK 进行身份验证?

  26. 26

    在 Python Django 中使用一个帐户进行多用户身份验证?

  27. 27

    使用 Django 和 Angular 进行 Windows 身份验证?

  28. 28

    使用 Django 进行 LDAP 身份验证

  29. 29

    无法使用 MongoEngine 进行身份验证。PyMongo 有效。如何让 MongoEngine 进行身份验证?

热门标签

归档