Permalink
Browse files

updates for django 1.9

  • Loading branch information...
1 parent 42168d9 commit 4b110ecdcb13968b3d70d1ad3aaaf0272a406d97 @last-partizan last-partizan committed Jan 27, 2016
View
@@ -0,0 +1,6 @@
+===========
+2016-01-27
+===========
+
+* Support for django 1.9, minimum django version: 1.7
+* Moved `django_mongoengine.mongo_auth.MongoUser` to `django_mongoengine.mongo_auth.models.MongoUser`
@@ -1,11 +1,8 @@
import os
import itertools
-import gridfs
-import datetime
-
-from django.utils.datastructures import SortedDict
+from collections import OrderedDict
-from django.forms.forms import BaseForm, get_declared_fields, NON_FIELD_ERRORS, pretty_name
+from django.forms.forms import BaseForm, NON_FIELD_ERRORS, pretty_name
from django.forms.widgets import media_property
from django.core.exceptions import FieldError
from django.core.validators import EMPTY_VALUES
@@ -17,7 +14,9 @@
from mongoengine.fields import ObjectIdField, ListField, ReferenceField, FileField, ImageField
from mongoengine.base import ValidationError
from mongoengine.connection import _get_db
+import gridfs
+from .utils import get_declared_fields
from .field_generator import MongoFormFieldGenerator
from .document_options import DocumentMetaWrapper
@@ -145,7 +144,7 @@ def fields_for_document(document, fields=None, exclude=None, widgets=None,
formfield_callback=None,
field_generator=MongoFormFieldGenerator):
"""
- Returns a ``SortedDict`` containing form fields for the given model.
+ Returns a ``OrderedDict`` containing form fields for the given model.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned fields.
@@ -188,9 +187,9 @@ def fields_for_document(document, fields=None, exclude=None, widgets=None,
else:
ignored.append(f.name)
- field_dict = SortedDict(field_list)
+ field_dict = OrderedDict(field_list)
if fields:
- field_dict = SortedDict(
+ field_dict = OrderedDict(
[(f, field_dict.get(f)) for f in fields
if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored)]
)
@@ -666,4 +665,4 @@ def embeddedformset_factory(document, parent_document, form=EmbeddedDocumentForm
}
FormSet = inlineformset_factory(document, **kwargs)
FormSet.parent_document = parent_document
- return FormSet
+ return FormSet
@@ -1,16 +1,56 @@
import new
+from collections import OrderedDict
+
+from django.forms.fields import Field
+from django.utils import six
from document_options import DocumentMetaWrapper
+
def patch_document(function, instance):
setattr(instance, function.__name__, new.instancemethod(function, instance, instance.__class__))
+
def init_document_options(document):
if not hasattr(document, '_meta') or not isinstance(document._meta, DocumentMetaWrapper):
document._admin_opts = DocumentMetaWrapper(document)
if not isinstance(document._admin_opts, DocumentMetaWrapper):
document._admin_opts = document._meta
return document
+
def get_document_options(document):
return DocumentMetaWrapper(document)
+
+
+def get_declared_fields(bases, attrs, with_base_fields=True):
+ """
+ Create a list of form field instances from the passed in 'attrs', plus any
+ similar fields on the base classes (in 'bases'). This is used by both the
+ Form and ModelForm metaclasses.
+
+ If 'with_base_fields' is True, all fields from the bases are used.
+ Otherwise, only fields in the 'declared_fields' attribute on the bases are
+ used. The distinction is useful in ModelForm subclassing.
+ Also integrates any additional media definitions.
+ """
+
+ fields = [
+ (field_name, attrs.pop(field_name))
+ for field_name, obj in list(six.iteritems(attrs)) if isinstance(obj, Field)
+ ]
+ fields.sort(key=lambda x: x[1].creation_counter)
+
+ # If this class is subclassing another Form, add that Form's fields.
+ # Note that we loop over the bases in *reverse*. This is necessary in
+ # order to preserve the correct order of fields.
+ if with_base_fields:
+ for base in bases[::-1]:
+ if hasattr(base, 'base_fields'):
+ fields = list(six.iteritems(base.base_fields)) + fields
+ else:
+ for base in bases[::-1]:
+ if hasattr(base, 'declared_fields'):
+ fields = list(six.iteritems(base.declared_fields)) + fields
+
+ return OrderedDict(fields)
@@ -1,13 +1,6 @@
-from django_mongoengine.mongo_admin.options import *
-from django_mongoengine.mongo_admin.sites import site
+default_app_config = "django_mongoengine.mongo_admin.apps.MongoAdminConfig"
-from django.conf import settings
+from .options import DocumentAdmin
+from .sites import site
-if getattr(settings, 'DJANGO_MONGOENGINE_OVERRIDE_ADMIN', False):
- import django.contrib.admin
- # copy already registered model admins
- # without that the already registered models
- # don't show up in the new admin
- site._registry = django.contrib.admin.site._registry
-
- django.contrib.admin.site = site
+__all__ = ['DocumentAdmin', 'site']
@@ -0,0 +1,18 @@
+from django.apps import AppConfig
+from django.conf import settings
+
+from django_mongoengine.mongo_admin.sites import site
+
+class MongoAdminConfig(AppConfig):
+ name = "django_mongoengine.mongo_admin"
+ verbose_name = "Mongo Admin"
+
+ def ready(self):
+ if getattr(settings, 'DJANGO_MONGOENGINE_OVERRIDE_ADMIN', False):
+ import django.contrib.admin
+ # copy already registered model admins
+ # without that the already registered models
+ # don't show up in the new admin
+ site._registry = django.contrib.admin.site._registry
+
+ django.contrib.admin.site = site
@@ -1,16 +1,16 @@
from functools import update_wrapper
+from collections import OrderedDict
from django import forms, template
from django.forms.formsets import all_valid
from django.forms.models import modelformset_factory
-from django.contrib.contenttypes.models import ContentType
from django.contrib.admin import widgets, helpers
from django.contrib.admin.utils import unquote, flatten_fieldsets, model_format_dict
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
-from django.db import models, router
+from django.db import models#, router
try:
from django.db.models.related import RelatedObject
except ImportError:
@@ -21,7 +21,6 @@
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.utils.decorators import method_decorator
-from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe
from django.utils.functional import curry
@@ -649,7 +648,7 @@ def get_actions(self, request):
# want *any* actions enabled on this page.
from django.contrib.admin.views.main import IS_POPUP_VAR
if self.actions is None or IS_POPUP_VAR in request.GET:
- return SortedDict()
+ return OrderedDict()
actions = []
@@ -670,12 +669,12 @@ def get_actions(self, request):
# get_action might have returned None, so filter any of those out.
actions = filter(None, actions)
- # Convert the actions into a SortedDict keyed by name
+ # Convert the actions into a OrderedDict keyed by name
# and sorted by description.
- actions = SortedDict([
+ actions = OrderedDict(sorted([
(name, (func, name, desc))
for func, name, desc in actions
- ])
+ ], key=lambda (nn, (f, n, d)): d))
return actions
@@ -1348,7 +1347,7 @@ def delete_view(self, request, object_id, extra_context=None):
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
- using = router.db_for_write(self.model)
+ #using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
@@ -1398,6 +1397,7 @@ def delete_view(self, request, object_id, extra_context=None):
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
+ from django.contrib.contenttypes.models import ContentType
model = self.model
opts = model._meta
app_label = opts.app_label
@@ -2,9 +2,7 @@
from django import http, template
from django.contrib.admin import ModelAdmin
-from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth import REDIRECT_FIELD_NAME
-from django.contrib.contenttypes import views as contenttype_views
from django.views.decorators.csrf import csrf_protect
from django.db.models.base import ModelBase
from django.core.exceptions import ImproperlyConfigured
@@ -19,7 +17,8 @@
from mongoengine.base import TopLevelDocumentMetaclass
-from django_mongoengine.mongo_admin import actions, DocumentAdmin
+from django_mongoengine.mongo_admin.options import DocumentAdmin
+from django_mongoengine.mongo_admin import actions
LOGIN_FORM_KEY = 'this_is_the_login_form'
@@ -210,6 +209,7 @@ def inner(request, *args, **kwargs):
def get_urls(self):
from django.conf.urls import patterns, url, include
+ from django.contrib.contenttypes import views as contenttype_views
if settings.DEBUG:
self.check_dependencies()
@@ -333,6 +333,7 @@ def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
+ from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth.views import login
context = {
'title': _('Log in'),
@@ -19,7 +19,7 @@
def validate(cls, model):
if issubclass(model, models.Model):
- ModelAdmin.validate(model)
+ ModelAdmin.check(model)
else:
_validate(cls, model)
@@ -1,128 +0,0 @@
-import django
-from django.conf import settings
-from django.contrib.auth.hashers import make_password
-from django.contrib.auth.models import UserManager
-from django.db.models import CharField, Model
-try:
- from django.utils.module_loading import import_module
-except ImportError:
- """Handle older versions of Django"""
- from django.utils.importlib import import_module
-from django.utils.translation import ugettext_lazy as _
-
-from bson.objectid import ObjectId
-
-__all__ = (
- 'get_user_document',
-)
-
-
-MONGOENGINE_USER_DOCUMENT = getattr(
- settings, 'MONGOENGINE_USER_DOCUMENT', 'django_mongoengine.mongo_auth.models.User')
-
-
-def get_user_document():
- """Get the user document class used for authentication.
-
- This is the class defined in settings.MONGOENGINE_USER_DOCUMENT, which
- defaults to `mongoengine.django.auth.User`.
-
- """
-
- name = MONGOENGINE_USER_DOCUMENT
- dot = name.rindex('.')
- module = import_module(name[:dot])
- return getattr(module, name[dot + 1:])
-
-
-class MongoUserManager(UserManager):
- """A User manager wich allows the use of MongoEngine documents in Django.
-
- To use the manager, you must tell django.contrib.auth to use MongoUser as
- the user model. In you settings.py, you need:
-
- INSTALLED_APPS = (
- ...
- 'django.contrib.auth',
- 'django_mongoengine.mongo_auth',
- ...
- )
- AUTH_USER_MODEL = 'mongo_auth.MongoUser'
-
- Django will use the model object to access the custom Manager, which will
- replace the original queryset with MongoEngine querysets.
-
- By default, mongoengine.django.auth.User will be used to store users. You
- can specify another document class in MONGOENGINE_USER_DOCUMENT in your
- settings.py.
-
- The User Document class has the same requirements as a standard custom user
- model: https://docs.djangoproject.com/en/dev/topics/auth/customizing/
-
- In particular, the User Document class must define USERNAME_FIELD and
- REQUIRED_FIELDS.
-
- `AUTH_USER_MODEL` has been added in Django 1.5.
-
- """
-
- def contribute_to_class(self, model, name):
- super(MongoUserManager, self).contribute_to_class(model, name)
- self.dj_model = self.model
- self.model = get_user_document()
-
- self.dj_model.USERNAME_FIELD = self.model.USERNAME_FIELD
- username = CharField(_('username'), max_length=30, unique=True)
- username.contribute_to_class(self.dj_model, self.dj_model.USERNAME_FIELD)
-
- self.dj_model.REQUIRED_FIELDS = self.model.REQUIRED_FIELDS
- for name in self.dj_model.REQUIRED_FIELDS:
- field = CharField(_(name), max_length=30)
- field.contribute_to_class(self.dj_model, name)
-
-
- def get(self, *args, **kwargs):
- try:
- m = (self.get_query_set
- if hasattr(self, 'get_query_set')
- else self.get_queryset)
- return m().get(*args, **kwargs)
- except self.model.DoesNotExist:
- # ModelBackend expects this exception
- raise self.dj_model.DoesNotExist
-
- @property
- def db(self):
- raise NotImplementedError
-
- def get_empty_query_set(self):
- return self.model.objects.none()
-
- def get_queryset(self):
- return self.model.objects
-
- if django.VERSION < (1, 6):
- get_query_set = get_queryset
-
-
-class MongoUser(Model):
- """"Dummy user model for Django.
-
- MongoUser is used to replace Django's UserManager with MongoUserManager.
- The actual user document class is django_mongoengine.auth.models.User or any
- other document class specified in MONGOENGINE_USER_DOCUMENT.
-
- To get the user document class, use `get_user_document()`.
-
- """
-
- objects = MongoUserManager()
-
- class Meta:
- app_label = 'mongo_auth'
-
- def set_password(self, password):
- """Doesn't do anything, but works around the issue with Django 1.6."""
- make_password(password)
-
-MongoUser._meta.pk.to_python = ObjectId
Oops, something went wrong.

0 comments on commit 4b110ec

Please sign in to comment.