【问题标题】:How to use user profiles with MongoEngine (Django)?如何在 MongoEngine (Django) 中使用用户配置文件?
【发布时间】:2014-06-23 04:49:05
【问题描述】:

所以,我正在尝试使用 MongoDB 数据库和 Django(使用 MongoEngine)构建一个简单的站点,但我一直在尝试了解用户配置文件的工作方式。我可以很好地将 mongo_auth.MongoUser 文档保存到数据库中,但是当涉及到实际保存配置文件时,我没有做正确的事情。这是我尝试使用 MongoUser 设置的用户配置文件模型/文档:

from mongoengine.django.auth import User
from mongoengine import *

[...]

class UserProfile(Document):
    user = EmbeddedDocumentField('User')
    telephone = models.CharField(max_length=30,null=True,blank=True)
    address = models.CharField(max_length=100, null=True, blank=True)
    birthdate = models.DateField(null=True, blank=True)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(create_user_profile, sender=User)

在具有关系数据库的 Django 中,UserProfile 是 models.Model,而 user 字段是 OneToOne 关系,但我不知道如何将其与 MongoUser 映射,所以我猜到了以下几行:

class UserProfile(Document):
    user = EmbeddedDocumentField('User')

但是,显然,这是不对的,因为 Django 无法加载配置文件:

Unable to load the profile model, check AUTH_PROFILE_MODULE in your project settings

我认为我的 settings.py 配置正确,因为我可以很好地保存 MongoUser(没有配置文件),并且以下行告诉 Django 在哪里可以找到 UserProfile:

AUTH_PROFILE_MODULE = 'comptes.UserProfile'

我还是 Django 和 MongoDB 的新手,因此我们将不胜感激。

谢谢!

【问题讨论】:

    标签: python django mongodb authentication mongoengine


    【解决方案1】:

    您必须使用 mongoengine.fields.ReferenceField。像这样的

    class UserProfile(Document):
         user = ReferenceField('User')
    

    【讨论】:

    • 谢谢。一切都保存在数据库中,但 get_profile 函数仍然不起作用(相同的错误消息)。在 mongoengine\django\auth.py 文件中挖掘了一下之后,我发现当 UserProfile 是文档时,函数 models.get_model('comptes', 'UserProfile') 返回“None”。这正常吗?
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多