Django的 - 验证与mongoengine DB [英] Django - Auth with mongoengine DB

查看:359
本文介绍了Django的 - 验证与mongoengine DB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要处理我的Django项目认证与我mongoengine分贝。

我想这个东西老问题,回答了几个例子,但它并没有运行。我使用的Django 1.6和mongoengine。一切都安装,运行,我可以创建和保存文档到我的Mongoengine DB。

我在下面的 http://mongoengine-odm.readthedocs.org/ EN /最新/ django.html

和我得到以下错误:

当我运行:

 >>>从django.contrib.auth.models导入用户
>>>用户= User.objects.create_user('约翰','lennon@thebeatles.com','johnpassword')

我得到这样的:

 回溯(最后最近一次调用):
  文件<&控制台GT;,1号线,上述<&模块GT;
  文件/REBORN/reb_env/local/lib/python2.7/site-packages/django/db/models/manager.py,273线,在__get__
    self.model._meta.object_name,self.model._meta.swapped
AttributeError的:管理器不可用;用户已被换成mongo_auth.MongoUser
>>>

我真不明白两件事:

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

- 什么是管理?我还没有定义的任何东西经理

在beggining我认为寄存器保存在一个数据库。 callledmongo_auth.MongoUser,但它并没有将其保存在没有​​出路的。

下面是型号:

 #创建您的模型在这里。
从mongoengine进口*类配置文件(文档):
    电子邮件= StringField(必填= TRUE)
    FIRST_NAME = StringField(MAX_LENGTH = 50)
    姓氏= StringField(MAX_LENGTH = 50)AUTH_USER类(文):
    用户名= StringField(MAX_LENGTH = 50)
    电子邮件= StringField(MAX_LENGTH = 50)
    密码= StringField(MAX_LENGTH = 50)

在settings.py被正确配置为手动说。

编辑@cestDiego:

我的设置是完全一样的,我注意到有关DB后端,因为它创造了我,因为我用蒙戈...反正我是从mongoengine.django.auth导入用户尤斯现在但我不感兴趣的数据库当我尝试创建一个用户返回我:

 >>>用户= User.objects.create_user('约翰','lennon@thebeatles.com','johnpassword')
回溯(最近通话最后一个):
  文件<&控制台GT;,1号线,上述<&模块GT;
AttributeError异常:查询集'对象有没有属性'create_user

也许我们正在自定义身份验证,这就是为什么不行,不知道。你有这样的问题呢?

第二编辑:

我读,我们必须使用Django的权威性,后配置正确的设置,因为这两个我们已经做了。

然后必须从django.contrib.auth进口身份验证导入和使用身份验证,因为它是在Django文档提供,希望对帮助;ð

 从django.shortcuts进口呈现
#在这里创建你的意见。
从django.http进口的Htt presponse
从game.models导入*
从mongoengine进口*
从模型导入用户
从django.contrib.auth进口身份验证高清登录(要求):
        用户身份验证=(用户名='约翰',密码='秘密')
        如果用户不无:
            #密码验证,该用户
            如果user.is_active:
                打印(用户是有效的,积极的和认证)
            其他:
                打印(密码是有效的,但该帐户已禁用!)
        其他:
            #认证系统无法验证用户名和密码
            打印(用户名和密码是不正确的。)


解决方案

我解决问题

在Django的1.6 ...

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

 
Django的设置PROVA项目。有关此文件的详细信息,请参阅
https://docs.djangoproject.com/en/1.6/topics/settings/对于设置及其值的完整列表,请参阅
https://docs.djangoproject.com/en/1.6/ref/settings/
#建立这样的项目中的路径:os.path.join(BASE_DIR,...)
进口OS
BASE_DIR = os.path.dirname(os.path.dirname(__ FILE__))
#快速启动开发设置 - 不适合生产
#见https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/#安全警告:保持秘密生产中使用的密钥!
SECRET_KEY ='^%R&放大器; tw5_steltu_ih&安培; n6lvht0gs(0P#0p5z0br @ +#L1O(iz_t6#安全警告:不要与调试运行在生产中打开!
DEBUG = TRUETEMPLATE_DEBUG = TRUEALLOWED_HOSTS = []
#应用程序定义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.urlsWSGI_APPLICATION ='prova.wsgi.application
#数据库
#https://docs.djangoproject.com/en/1.6/ref/settings/#databases数据库= {
    默认:{
        '发动机':'django.db.backends.dummy
    }
}
AUTHENTICATION_BACKENDS =(
    mongoengine.django.auth.MongoEngineBackend',

SESSION_ENGINE ='mongoengine.django.sessions
SESSION_SERIALIZER ='mongoengine.django.sessions.BSONSerializer
#国际化
#https://docs.djangoproject.com/en/1.6/topics/i18n/LANGUAGE_ code =EN-USTIME_ZONE ='UTC'USE_I18N = TRUEUSE_L10N = TRUEUSE_TZ = TRUE
#静态文件(CSS,JavaScript,图片)
#https://docs.djangoproject.com/en/1.6/howto/static-files/STATIC_URL ='/静态/

和我的views.py看起来像:

 从django.shortcuts进口呈现
#在这里创建你的意见。
从django.http进口的Htt presponse
从game.models导入*
从mongoengine进口*
#from django.contrib.auth进口身份验证
从mongoengine.django.auth导入用户高清登录(要求):
    连接('重生')
    从django.contrib.auth导入登录
    从mongoengine.django.auth导入用户
    从mongoengine.queryset进口DoesNotExist
    从进口django.contrib中的消息
    尝试:
        用户= User.objects.get(用户名='鲍勃')#request.POST ['用户名'])
        如果user.check_password('bobpass'):#request.POST ['密码']):
            user.backend ='mongoengine.django.auth.MongoEngineBackend
            打印登录(请求用户)
            request.session.set_expiry(60 * 60 * 1)#1小时超时
            打印回归
            返回的Htt presponse(LOGUEJAT)#重定向(索引)
        其他:
            打印malament
            messages.add_message(要求,messages.ERROR,U不正确的登录名或密码!)
    除了DoesNotExist:
        messages.add_message(要求,messages.ERROR,U不正确的登录名或密码!)
    返回渲染(要求,'login.html的',{})高清注销(要求):#未测试
    从django.contrib.auth进口注销
    注销(要求)
    返回重定向(登录)高清CREATEUSER(要求):
    连接('重生')
    User.create_user('波巴','bobpass','bobsaget@fullhouse.gov')
    返回的Htt presponse(拯救)

现在的用户对象保存在数据库,如:

  {
    _id:的ObjectId(53465fa60f04c6552ab77475),
    _cls:用户,
    用户名:波霸
    电子邮件:bobsaget@fullhouse.gov
    密码:pbkdf2_sha256 $ 12000 $ ZYbCHP1K1kDE $ Y4LnGTdKhh1irJVktWo1QZX6AlEFn + 1daTEvQAMMehA =,
    is_staff:假的,
    IS_ACTIVE:真实,
    is_superuser:假的,
    LAST_LOGIN:ISODate(2014-04-10T09:08:54.551Z),
    date_joined:ISODate(2014-04-10T09:08:54.550Z),
    user_permissions:[]
}

I want to handle authentications in my Django project with my mongoengine db.

I tried a few examples about this stuff answered in old questions but it didn't run. I'm using Django 1.6 and mongoengine. Everything is installed, running and I can create and save documents to my Mongoengine DB.

I'm following http://mongoengine-odm.readthedocs.org/en/latest/django.html

And i get the following error:

When i run:

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

I get this:

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'
>>> 

I really don't understand 2 things:

-Do I must create and define the database where the users will be stored or they will be created automatically?

-What is Manager? I haven't defined any manager stuff

At the beggining i thought that the register was saved in a db. callled 'mongo_auth.MongoUser' but it didn't save it in nowhere.

Here is the models:

# 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)

The settings.py is properly configured as the manual says.

EDIT @cestDiego:

My settings are exactly the same, I've noticed about the Db backend because it creates me a database which am not interested because I use mongo...Anyway I'm ussing from mongoengine.django.auth import User now but when I try to create an User it returns me :

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

Maybe we are customizing the auth and that's why not work, no idea. Do you have this problem too ?

SECOND EDIT:

I was reading and we have to use Djangos auth, after configure the right settings, as both we have done.

Then must import the from django.contrib.auth import authenticate and use authenticate as it is provided in Django docs, hope to help ;D.

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.")

解决方案

I solve the problem

In Django 1.6...

My settings.py looks like this:

"""
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/'

and my views.py looks like:

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','bobsaget@fullhouse.gov')
    return HttpResponse("SAVED")

now the user object is saved in DB like:

{
    "_id" : ObjectId("53465fa60f04c6552ab77475"),
    "_cls" : "User",
    "username" : "boba",
    "email" : "bobsaget@fullhouse.gov",
    "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" : [ ]
}

这篇关于Django的 - 验证与mongoengine DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆