6. Django Support


Updated to support Django 1.5

6.1. Connecting

In your settings.py file, ignore the standard database settings (unless you also plan to use the ORM in your project), and instead call connect() somewhere in the settings module.


If you are not using another Database backend you may need to add a dummy database backend to settings.py eg:

    'default': {
        'ENGINE': 'django.db.backends.dummy'

6.2. Authentication

MongoEngine includes a Django authentication backend, which uses MongoDB. The User model is a MongoEngine Document, but implements most of the methods and attributes that the standard Django User model does - so the two are moderately compatible. Using this backend will allow you to store users in MongoDB but still use many of the Django authentication infrastructure (such as the login_required() decorator and the authenticate() function). To enable the MongoEngine auth backend, add the following to your settings.py file:


The auth module also contains a get_user() helper function, that takes a user’s id and returns a User object.

New in version 0.1.3.

6.3. Custom User model

Django 1.5 introduced Custom user Models which can be used as an alternative to the MongoEngine authentication backend.

The main advantage of this option is that other components relying on django.contrib.auth and supporting the new swappable user model are more likely to work. For example, you can use the createsuperuser management command as usual.

To enable the custom User model in Django, add 'mongoengine.django.mongo_auth' in your INSTALLED_APPS and set 'mongo_auth.MongoUser' as the custom user user model to use. In your settings.py file you will have:


AUTH_USER_MODEL = 'mongo_auth.MongoUser'

An additional MONGOENGINE_USER_DOCUMENT setting enables you to replace the User class with another class of your choice:

MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User'

The custom User must be a Document class, but otherwise has the same requirements as a standard custom user model, as specified in the Django Documentation. In particular, the custom class must define USERNAME_FIELD and REQUIRED_FIELDS attributes.

6.4. Sessions

Django allows the use of different backend stores for its sessions. MongoEngine provides a MongoDB-based session backend for Django, which allows you to use sessions in your Django application with just MongoDB. To enable the MongoEngine session backend, ensure that your settings module has 'django.contrib.sessions.middleware.SessionMiddleware' in the MIDDLEWARE_CLASSES field and 'django.contrib.sessions' in your INSTALLED_APPS. From there, all you need to do is add the following line into your settings module:

SESSION_ENGINE = 'mongoengine.django.sessions'
SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'

Django provides session cookie, which expires after `SESSION_COOKIE_AGE` seconds, but doesn’t delete cookie at sessions backend, so 'mongoengine.django.sessions' supports mongodb TTL.


SESSION_SERIALIZER is only necessary in Django 1.6 as the default serializer is based around JSON and doesn’t know how to convert bson.objectid.ObjectId instances to strings.

New in version 0.2.1.

6.5. Storage

With MongoEngine’s support for GridFS via the FileField, it is useful to have a Django file storage backend that wraps this. The new storage module is called GridFSStorage. Using it is very similar to using the default FileSystemStorage.:

from mongoengine.django.storage import GridFSStorage
fs = GridFSStorage()

filename = fs.save('hello.txt', 'Hello, World!')

All of the Django Storage API methods have been implemented except path(). If the filename provided already exists, an underscore and a number (before # the file extension, if one exists) will be appended to the filename until the generated filename doesn’t exist. The save() method will return the new filename.:

>>> fs.exists('hello.txt')
>>> fs.open('hello.txt').read()
'Hello, World!'
>>> fs.size('hello.txt')
>>> fs.url('hello.txt')
>>> fs.open('hello.txt').name
>>> fs.listdir()
([], [u'hello.txt'])

All files will be saved and retrieved in GridFS via the FileDocument document, allowing easy access to the files without the GridFSStorage backend.:

>>> from mongoengine.django.storage import FileDocument
>>> FileDocument.objects()
[<FileDocument: FileDocument object>]

New in version 0.4.

6.6. Shortcuts

Inspired by the Django shortcut get_object_or_404, the get_document_or_404() method returns a document or raises an Http404 exception if the document does not exist:

from mongoengine.django.shortcuts import get_document_or_404

admin_user = get_document_or_404(User, username='root')

The first argument may be a Document or QuerySet object. All other passed arguments and keyword arguments are used in the query:

foo_email = get_document_or_404(User.objects.only('email'), username='foo', is_active=True).email


Like with get(), a MultipleObjectsReturned will be raised if more than one object is found.

Also inspired by the Django shortcut get_list_or_404, the get_list_or_404() method returns a list of documents or raises an Http404 exception if the list is empty:

from mongoengine.django.shortcuts import get_list_or_404

active_users = get_list_or_404(User, is_active=True)

The first argument may be a Document or QuerySet object. All other passed arguments and keyword arguments are used to filter the query.

Read the Docs v: v0.9.0
On Read the Docs
Project Home

Free document hosting provided by Read the Docs.