Bug*_*xer 9 python authentication django django-models mongoengine
我想用我的mongoengine db处理我的Django项目中的身份验证.
我尝试了一些关于这些问题的例子,这些问题在旧问题中得到了回答,我正在使用Django 1.6和mongoengine.一切都已安装,运行,我可以创建文档并将其保存到Mongoengine DB.
我正在关注http://mongoengine-odm.readthedocs.org/en/latest/django.html
我收到以下错误:
当我跑:
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
Run Code Online (Sandbox Code Playgroud)
我明白了:
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'
>>>
Run Code Online (Sandbox Code Playgroud)
我真的不明白两件事:
- 我是否必须创建和定义用户将被存储的数据库,或者它们将自动创建?
- 什么是经理?我没有定义任何经理的东西
在开始时我认为寄存器保存在数据库中.称为'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)
Run Code Online (Sandbox Code Playgroud)
如手册所述,settings.py已正确配置.
编辑@cestDiego:
我的设置完全相同,我注意到Db后端,因为它创建了一个我不感兴趣的数据库因为我使用mongo ...无论如何我正在使用mongoengine.django.auth导入用户现在但是当我尝试创建一个用户,它返回给我:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
也许我们正在定制auth,这就是为什么不工作,不知道.你也有这个问题吗?
第二次编辑:
我正在阅读,我们必须使用Djangos auth,配置正确的设置后,我们都做了.
然后必须导入来自django.contrib.auth导入身份验证并使用在Django docs中提供的authenticate,希望有所帮助; 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.")
Run Code Online (Sandbox Code Playgroud)
嘿,我和你一样.我可以弄清楚你在settings.py中有这些
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'
Run Code Online (Sandbox Code Playgroud)
这在已安装的应用程序中
'mongoengine.django.mongo_auth'
Run Code Online (Sandbox Code Playgroud)
这意味着现在您正在使用Mongoengine身份验证方法,您使用的第一行导入了DJANGO身份验证方法,因此存在问题.您不是在mongodb中创建任何数据库,而是在Django的ORM中使用backend.dummy设置的虚拟数据库.
我不知道如何使用mongoengine的auth方法,如果你搞清楚,请向我解释一下;)我希望我澄清一下我们在这里面临的问题.这只是一个更深刻阅读文档的问题.
编辑:(答案后1分钟)我在你链接到的文档中找到了这个:
MongoEngine包含一个使用MongoDB的Django身份验证后端.> User模型是MongoEngine文档,但实现了标准Django User模型所做的大多数>方法和属性 - 因此> 2是适度兼容的.
所以这意味着在你的情况下,交换
from django.contrib.auth import User
Run Code Online (Sandbox Code Playgroud)
至
from mongoengine.django.auth import User
Run Code Online (Sandbox Code Playgroud)
我解决了这个问题
在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/'
Run Code Online (Sandbox Code Playgroud)
和我的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','bobsaget@fullhouse.gov')
return HttpResponse("SAVED")
Run Code Online (Sandbox Code Playgroud)
现在用户对象保存在DB中,如:
{
"_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" : [ ]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11546 次 |
| 最近记录: |