def is_model_registered(app_label, model_name): try: apps.get_registered_model(app_label, model_name) except LookupError: return False else: return True
def is_model_registered(app_label, model_name): """ Checks whether a given model is registered. This is used to only register Oscar models if they aren't overridden by a forked app. """ try: apps.get_registered_model(app_label, model_name) except LookupError: return False else: return True
def is_model_registered(app_label, model_name): """ Checks whether the given model is registered or not. It is usefull to prevent Machina models for being registered if they are overridden by local apps. """ try: apps.get_registered_model(app_label, model_name) except LookupError: return False else: return True
def get_model(app_label, model_name): """ Fetches a Django model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry not being ready yet. Raises LookupError if model isn't found. """ try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If this function is called while `apps.populate()` is # loading models, ensure that the module that defines the # target model has been imported and try looking the model up # in the app registry. This effectively emulates # `from path.to.app.models import Model` where we use # `Model = get_model('app', 'Model')` instead. app_config = apps.get_app_config(app_label) # `app_config.import_models()` cannot be used here because it # would interfere with `apps.populate()`. import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) # In order to account for case-insensitivity of model_name, # look up the model through a private API of the app registry. return apps.get_registered_model(app_label, model_name) else: # This must be a different case (e.g. the model really doesn't # exist). We just re-raise the exception. raise
def get_user_model_safe(): """ Fetches the user model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry not being ready yet. Raises LookupError if model isn't found. Based on: https://github.com/django-oscar/django-oscar/blob/1.0/oscar/core/loading.py#L310-L340 Ongoing Django issue: https://code.djangoproject.com/ticket/22872 """ user_app, user_model = settings.AUTH_USER_MODEL.split('.') try: return apps.get_model(user_app, user_model) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If this function is called while `apps.populate()` is # loading models, ensure that the module that defines the # target model has been imported and try looking the model up # in the app registry. This effectively emulates # `from path.to.app.models import Model` where we use # `Model = get_model('app', 'Model')` instead. app_config = apps.get_app_config(user_app) # `app_config.import_models()` cannot be used here because it # would interfere with `apps.populate()`. import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) # In order to account for case-insensitivity of model_name, # look up the model through a private API of the app registry. return apps.get_registered_model(user_app, user_model) else: # This must be a different case (e.g. the model really doesn't # exist). We just re-raise the exception. raise
def get_obj_model_class(table_name): """ 动态创建存储桶对应的对象模型类 RuntimeWarning: Model 'xxxxx_' was already registered. Reloading models is not advised as it can lead to inconsistencies most notably with related models. 如上述警告所述, Django 不建议重复创建Model 的定义.可以直接通过get_obj_model_class创建,无视警告. 这里先通过 get_registered_model 获取已经注册的 Model, 如果获取不到, 再生成新的模型类. :param table_name: 数据库表名,模型类对应的数据库表名 :return: Model class """ model_name = 'ObjModel' + table_name app_leble = BucketFileBase.Meta.app_label try: cls = apps.get_registered_model(app_label=app_leble, model_name=model_name) return cls except LookupError: pass meta = BucketFileBase.Meta meta.abstract = False meta.db_table = table_name # 数据库表名 return type(model_name, (BucketFileBase, ), { 'Meta': meta, '__module__': BucketFileBase.__module__ })
def add(self, function, *models_or_names): """ The function passed to this method should accept n arguments, where n=len(models_or_names). When all the models are ready, the function will be called with the models as arguments, in the order they appear in this argument list. """ # Eagerly parse all model strings so we can fail immediately # if any are plainly invalid. model_keys = [self.model_key(m) if not isinstance(m, tuple) else m for m in models_or_names] # If this function depends on more than one model, recursively call add # for each, partially applying the given function on each iteration. model_key, more_models = model_keys[0], model_keys[1:] if more_models: inner_function = function function = lambda model: self.add(partial(inner_function, model), *more_models) # If the model is already loaded, pass it to the function immediately. # Otherwise, delay execution until the class is prepared. try: model_class = apps.get_registered_model(*model_key) except LookupError: self.pending_operations.setdefault(model_key, []).append(function) else: function(model_class)
def get_model(app_label, name): if django.VERSION < (1, 7): from django.db import models model = models.get_model(app_label, name) else: from django.apps import apps model = apps.get_registered_model(app_label, name) return model
def get_model_meta(model_str: str) -> Union[None, Options]: """ Get model meta class """ try: app, model = model_str.split(".") Model = apps.get_registered_model(app, model) return Model._meta except (ValueError, LookupError): return None
def get_model(app_label, model_name): try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: app_config = apps.get_app_config(app_label) import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) return apps.get_registered_model(app_label, model_name) else: raise
def get_search_lookups(field_prop): if field_prop.FieldType != 5: return [] else: return DynamicModelSerializer( apps.get_registered_model('common', field_prop.Name).objects.all(), many=True, value_field=field_prop.LookupKey, label_field=field_prop.LookupValue, model=field_prop.Name ).data if field_prop.Name is not None and field_prop.LookupKey is not None and field_prop.LookupValue is not None else None
def get_model(app_label, model_name): """ Fetches a Django model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry not being ready yet. Raises LookupError if model isn't found. """ return apps.get_registered_model(app_label, model_name)
def __init__(self, **kwargs): super(ModelLink, self).__init__(**kwargs) if 'model' not in self.kwargs: raise ImproperlyConfigured('Please provide a model path') self.model = apps.get_registered_model(*self.kwargs['model'].split('.', 1)) if not hasattr(self.model, 'get_absolute_url'): raise ImproperlyConfigured( '{0} does not implement `get_absolute_url`'.format( self.model.__name__))
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): if isinstance(sender, six.string_types): try: app_label, model_name = sender.split(".") except ValueError: raise ValueError( "Specified sender must either be a model or a " "model name of the 'app_label.ModelName' form." ) try: sender = apps.get_registered_model(app_label, model_name) except LookupError: ref = (app_label, model_name) refs = self.unresolved_references.setdefault(ref, []) refs.append((receiver, weak, dispatch_uid)) return super(ModelSignal, self).connect(receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid)
def register_model_lookup(field, related_model): if isinstance(related_model, str): app_label, model_name = related_model.split('.') try: field.related_model = apps.get_registered_model(app_label, model_name) except LookupError: def resolve(**kwargs): clz = kwargs['sender'] # noinspection PyProtectedMember if clz._meta.app_label == app_label and clz._meta.object_name == model_name: field.related_model = clz class_prepared.disconnect(resolve, weak=False) class_prepared.connect(resolve, weak=False) else: field.related_model = related_model
def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None): """ Create a Django Proxy Model on the fly, to be used by any Cascade Plugin. """ from django.apps import apps class Meta: proxy = True app_label = 'cmsplugin_cascade' name = str(name + 'Model') try: Model = apps.get_registered_model(Meta.app_label, name) except LookupError: bases = model_mixins + (base_model,) attrs = dict(attrs or {}, Meta=Meta, __module__=module) Model = type(name, bases, attrs) fake_proxy_models[name] = bases return Model
def get_model(app_label, model_name): """ Fetches a Django model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry not being ready yet. Raises LookupError if model isn't found. 使用app注册表获取Django模型。 这不要求具有给定app标签的应用程序存在,这使得在填充注册表时可以安全地调用。 访问模型的所有其他方法可能会引发有关注册表尚未准备就绪的异常。 如果找不到模型,则引发LookupError。 """ try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If this function is called while `apps.populate()` is # loading models, ensure that the module that defines the # target model has been imported and try looking the model up # in the app registry. This effectively emulates # `from path.to.app.models import Model` where we use # `Model = get_model('app', 'Model')` instead. # 如果在'apps.populate()`正在加载模型时调用此函数,请确保已导入定义 # 目标模型的模块并尝试在app注册表中查找模型。 这有效地模仿了path.to.app.models # 导入Model`,我们使用Model = get_model('app','Model')来代替。 app_config = apps.get_app_config(app_label) # `app_config.import_models()` cannot be used here because it # would interfere with `apps.populate()`. # `app_config.import_models()`不能在这里使用,因为它会干扰`apps.populate()`。 import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) # In order to account for case-insensitivity of model_name, # look up the model through a private API of the app registry. # 为了说明model_name的大小写不敏感,请通过app注册表的私有API查找模型。 return apps.get_registered_model(app_label, model_name) else: # This must be a different case (e.g. the model really doesn't # exist). We just re-raise the exception. # 这必须是不同的情况(例如模型确实不存在)。 我们只是重新提出异常。 raise
def get_model(app_label, model_name): """ Given an app label and a model name, returns the corresponding model class. """ try: return apps.get_model(app_label, model_name) except AppRegistryNotReady: if apps.apps_ready and not apps.models_ready: # If the models module of the considered app has not been loaded yet, # we try to import it manually in order to retrieve the model class. # This trick is usefull in order to get the model class during the # ``apps.populate()`` call and the execution of related methods of AppConfig # instances (eg. ``ready``). # Firts, the config of the consideration must be retrieved app_config = apps.get_app_config(app_label) # Then the models module is manually imported import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME)) # Finally, tries to return the registered model class return apps.get_registered_model(app_label, model_name) else: raise
def add_lazy_dependency(self, obj, operation): """ If obj is a function (thunk), delay operation; otherwise execute immediately. """ if isinstance(obj, basestring): app_label, model_name = obj.split(".") try: # This is a private API, please fix it! model = apps.get_registered_model(app_label, model_name) except LookupError: key = (app_label, model_name) value = operation pending_lookups.setdefault(key, []).append(value) else: operation(model) elif isinstance(obj, types.FunctionType): import warnings warnings.warn("Using lambdas to thunk dependencies is deprecated. Use strings instead.", DeprecationWarning, stacklevel=3) # HACK: stick the lambda into pending_lookups as a key, # which will be processed in do_all_pending. key = obj value = operation pending_lookups.setdefault(key, []).append(value) else: operation(obj)
def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None): """ Create a Django Proxy Model on the fly, to be used by any Cascade Plugin. """ from django.apps import apps class Meta: proxy = True app_label = 'cmsplugin_cascade' name = str(name + 'Model') try: Model = apps.get_registered_model(Meta.app_label, name) except LookupError: bases = model_mixins + (base_model, ) attrs = dict(attrs or {}, Meta=Meta, __module__=module) Model = type(name, bases, attrs) fake_proxy_models[name] = bases return Model
def generate_param_row_config(param, matrix, modify_flag): if modify_flag == 0: return { 'type': 'readOnly', 'inputType': None, } return { 1: { 'type': 'input', 'inputType': 'number', 'minValue': matrix.ValueLimits.get('Lower') if matrix.ValueLimits is not None else None, 'maxValue': matrix.ValueLimits.get('Upper') if matrix.ValueLimits is not None else None, }, 2: { 'type': 'input', 'inputType': 'text', }, 3: { 'type': 'input', 'inputType': 'number', 'minValue': matrix.ValueLimits.get('Lower') if matrix.ValueLimits is not None else None, 'maxValue': matrix.ValueLimits.get('Upper') if matrix.ValueLimits is not None else None, }, 4: { 'type': 'input', 'inputType': 'date', }, 5: { 'type': 'select', 'options': DynamicModelSerializer(apps.get_registered_model('common', param.Description).objects.all(), many=True, value_field=param.Description1, label_field=param.Description2, model=param.Description).data if param.Description is not None and param.Description1 is not None and param.Description2 is not None else None }, None: { 'type': 'input', 'inputType': 'text', }, }[param.FieldType]
CreateView, ListView, RedirectView) from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from numpy import nan, nansum, nanmax from djspikeval.forms import SubmissionForm # from djspikeval.util import render_to, PLOT_COLORS __all__ = [ "AnalysisBaseView", "AnalysisList", "AnalysisCreate", "AnalysisDetail", "AnalysisUpdate", "AnalysisDelete", "AnalysisDownload", "SubmissionToggle", "SubmissionStart", "AnalysisStart" ] __author__ = "pmeier82" Analysis = apps.get_registered_model("djspikeval", "analysis") Dataset = apps.get_registered_model("djspikeval", "dataset") Submission = apps.get_registered_model("djspikeval", "submission") class AnalysisBaseView(object): model = Submission class AnalysisList(AnalysisBaseView, ListView): template_name = "djspikeval/analysis/list.html" paginate_by = 10 def get_queryset(self): if self.request.user.is_superuser: return Submission.objects.all()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import apps from django.contrib import admin __author__ = "pmeier82" Algorithm = apps.get_registered_model("djspikeval", "algorithm") Analysis = apps.get_registered_model("djspikeval", "analysis") Datafile = apps.get_registered_model("djspikeval", "datafile") Dataset = apps.get_registered_model("djspikeval", "dataset") Module = apps.get_registered_model("djspikeval", "module") Result = apps.get_registered_model("djspikeval", "result") Submission = apps.get_registered_model("djspikeval", "submission") class AlgorithmAdmin(admin.ModelAdmin): pass class AnalysisAdmin(admin.ModelAdmin): pass class DatafileAdmin(admin.ModelAdmin): pass class DatasetAdmin(admin.ModelAdmin): pass
from django.apps import apps from import_export import resources Category = apps.get_registered_model('hivs_pp', 'Category') Service = apps.get_registered_model('hivs_pp', 'Service') Delivery = apps.get_registered_model('hivs_pp', 'Delivery') class CategoryResource(resources.ModelResource): class Meta: model = Category class ServiceResource(resources.ModelResource): class Meta: model = Service class DeliveryResource(resources.ModelResource): class Meta: model = Delivery
def safe_get_user_model(): """ Safe loading of the User model, customized or not. """ user_app, user_model = settings.AUTH_USER_MODEL.split('.') return apps.get_registered_model(user_app, user_model)
from django.apps import apps
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.apps import apps from .util import form_with_captcha __all__ = ["AttachmentForm"] __author__ = "pmeier82" Asset = apps.get_registered_model("base", "asset") @form_with_captcha class AttachmentForm(forms.ModelForm): """`Attachment` model form""" # meta class Meta: model = Asset fields = ("name", "data") # constructor def __init__(self, *args, **kwargs): obj = kwargs.pop("obj", None) if obj is None: raise ValueError("no related object passed!") super(AttachmentForm, self).__init__(*args, **kwargs) if self.instance.id is None: self.instance.kind = "attachment" self.instance.content_object = obj
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.apps import apps from django.forms import inlineformset_factory from .util import form_with_captcha __all__ = ["SubmissionForm"] __author__ = "pmeier82" Algorithm = apps.get_registered_model("djspikeval", "algorithm") Analysis = apps.get_registered_model("djspikeval", "analysis") Asset = apps.get_registered_model("base", "asset") Datafile = apps.get_registered_model("djspikeval", "datafile") Submission = apps.get_registered_model("djspikeval", "submission") @form_with_captcha class SubmissionForm(forms.ModelForm): """`Submission` model form""" # meta class Meta: model = Submission exclude = ("user", "status", "status_changed", "dataset") # constructor def __init__(self, *args, **kwargs): dataset = kwargs.pop("dataset", None) user = kwargs.pop("user", None)
from __future__ import unicode_literals from django.apps import apps from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse_lazy from django.shortcuts import get_object_or_404, redirect from django.views.generic import CreateView, DetailView, UpdateView, DeleteView, View from djspikeval.forms import DatafileForm __all__ = [ "DatafileBaseView", "DatafileCreate", "DatafileDetail", "DatafileUpdate", "DatafileDelete", "DatafileValidate"] __author__ = "pmeier82" Benchmark = apps.get_registered_model("djspikeval", "dataset") Trial = apps.get_registered_model("djspikeval", "datafile") class DatafileBaseView(object): model = Trial class DatafileCreate(DatafileBaseView, CreateView): template_name = "djspikeval/datafile/create.html" form_class = DatafileForm def get_form_kwargs(self): kwargs = super(DatafileCreate, self).get_form_kwargs() kwargs["user"] = self.request.user kwargs["dataset"] = get_object_or_404(Benchmark, pk=self.kwargs["pk"])
from __future__ import unicode_literals from datetime import datetime from StringIO import StringIO from django.apps import apps from django.conf import settings from django.utils import importlib from celery.task import task from spikeval.datafiles import read_gdf_sts, read_hdf5_arc from spikeval.log import Logger from ..signals import spike_analysis Analysis = apps.get_registered_model("djspikeval", "analysis") Module = apps.get_registered_model("djspikeval", "module") __all__ = ["run_modules_for_analysis"] __author__ = "pmeier82" USE_CELERY = getattr(settings, "USE_CELERY", False) if getattr(settings, "CELERY_USE_PRIORITY", None) is not None: USE_CELERY = getattr(settings, "CELERY_USE_PRIORITY") def run_modules_for_analysis(sender, **kwargs): if getattr(settings, "DEBUG", None) is True: print "starting analysis [class: %s::%s]" % (sender.__class__.__name__, sender.id) if USE_CELERY: task_run_modules.delay(sender)
from django.apps import apps from haystack.inputs import Raw from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.response import Response from drf_haystack.viewsets import HaystackViewSet from haystack_es.query import SearchQuerySet from .serializers import SearchResultSerializer from .pagination import SearchPagination from ..filters import SimpleFilterBackend Plan = apps.get_registered_model('goals', 'Plan') Goal = apps.get_registered_model('goals', 'Goal') Target = apps.get_registered_model('goals', 'Target') Indicator = apps.get_registered_model('goals', 'Indicator') Component = apps.get_registered_model('goals', 'Component') class SearchViewSet(HaystackViewSet): index_models = [Plan, Goal, Target, Indicator, Component] pagination_class = SearchPagination serializer_class = SearchResultSerializer permission_classes = [IsAuthenticatedOrReadOnly] filter_backends = [SimpleFilterBackend] filter_fields = [ 'code', 'name', 'description', 'slug', 'caption', 'plan', 'plan_code', 'plan_id', 'plan_name', 'plans_ids', 'plans_codes', 'plans_names', 'sector', 'sector_id', 'sector_code', 'sector_name', 'sectors_ids', 'sectors_codes', 'sectors_names',
def get_model(app_label, model_name): try: return apps.get_registered_model(app_label, model_name) except LookupError: pass
def get_user_model(): aum = settings.AUTH_USER_MODEL app_label, model_name = aum.split('.') return apps.get_registered_model(app_label, model_name)
from django.apps import apps from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse_lazy from django.shortcuts import get_object_or_404, redirect from django.views.generic import CreateView, DetailView, UpdateView, DeleteView, View from djspikeval.forms import DatafileForm __all__ = [ "DatafileBaseView", "DatafileCreate", "DatafileDetail", "DatafileUpdate", "DatafileDelete", "DatafileValidate" ] __author__ = "pmeier82" Benchmark = apps.get_registered_model("djspikeval", "dataset") Trial = apps.get_registered_model("djspikeval", "datafile") class DatafileBaseView(object): model = Trial class DatafileCreate(DatafileBaseView, CreateView): template_name = "djspikeval/datafile/create.html" form_class = DatafileForm def get_form_kwargs(self): kwargs = super(DatafileCreate, self).get_form_kwargs() kwargs["user"] = self.request.user kwargs["dataset"] = get_object_or_404(Benchmark, pk=self.kwargs["pk"])
def get_model(app_label, model_name): return apps.get_registered_model(app_label, model_name)
from django.views.generic import ( View, DetailView, UpdateView, DeleteView, CreateView, ListView, RedirectView) from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from numpy import nan, nansum, nanmax from ..forms import DatasetForm # from ..util import render_to, PLOT_COLORS __all__ = [ "ModuleBaseView", "ModuleList", "ModuleCreate", "ModuleDetail", "ModuleUpdate", "ModuleDelete", "ModuleDownload", "ModuleSummary", "ModuleToggle"] __author__ = "pmeier82" Dataset = apps.get_registered_model("djspikeval", "dataset") Module = apps.get_registered_model("djspikeval", "module") class ModuleBaseView(object): model = Module class ModuleList(ModuleBaseView, ListView): template_name = "djspikeval/module/list.html" paginate_by = 10 def get_context_data(self, **kwargs): cntx = super(ModuleList, self).get_context_data(**kwargs) cntx.update(scope=self.request.GET.get("scope")) return cntx
from django.utils import importlib from django.views.generic import ( View, DetailView, UpdateView, DeleteView, CreateView, ListView, RedirectView) from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from numpy import nan, nansum, nanmax from djspikeval.forms import SubmissionForm # from djspikeval.util import render_to, PLOT_COLORS __all__ = [ "AnalysisBaseView", "AnalysisList", "AnalysisCreate", "AnalysisDetail", "AnalysisUpdate", "AnalysisDelete", "AnalysisDownload", "SubmissionToggle", "SubmissionStart", "AnalysisStart"] __author__ = "pmeier82" Analysis = apps.get_registered_model("djspikeval", "analysis") Dataset = apps.get_registered_model("djspikeval", "dataset") Submission = apps.get_registered_model("djspikeval", "submission") class AnalysisBaseView(object): model = Submission class AnalysisList(AnalysisBaseView, ListView): template_name = "djspikeval/analysis/list.html" paginate_by = 10 def get_queryset(self): if self.request.user.is_superuser: return Submission.objects.all()
from django.apps import apps from rest_framework import serializers Center = apps.get_registered_model('hivs_cd', 'Center') Purpose = apps.get_registered_model('hivs_cd', 'Purpose') CondomDistribution = apps.get_registered_model('hivs_cd', 'CondomDistribution') class CenterSerializer(serializers.ModelSerializer): class Meta: model = Center fields = '__all__' class PurposeSerializer(serializers.ModelSerializer): class Meta: model = Purpose fields = '__all__' class CondomDistributionSerializer(serializers.ModelSerializer): class Meta: model = CondomDistribution fields = '__all__'
from cms.utils.compat import DJANGO_1_6 from cms.utils.helpers import reversion_register # Cannot use contrib.auth.get_user_model() at compile time. user_app_name, user_model_name = settings.AUTH_USER_MODEL.rsplit('.', 1) User = None if DJANGO_1_6: for app in settings.INSTALLED_APPS: if app.endswith(user_app_name): user_app_models = importlib.import_module(app + ".models") User = getattr(user_app_models, user_model_name) break else: from django.apps import apps try: User = apps.get_registered_model(user_app_name, user_model_name) except KeyError: pass if User is None: raise ImproperlyConfigured( "You have defined a custom user model %s, but the app %s is not " "in settings.INSTALLED_APPS" % (settings.AUTH_USER_MODEL, user_app_name) ) # NOTE: those are not just numbers!! we will do binary AND on them, # so pay attention when adding/changing them, or MASKs.. ACCESS_PAGE = 1 ACCESS_CHILDREN = 2 # just immediate children (1 level) ACCESS_PAGE_AND_CHILDREN = 3 # just immediate children (1 level) ACCESS_DESCENDANTS = 4 ACCESS_PAGE_AND_DESCENDANTS = 5
from cms.utils.compat import DJANGO_1_6 from cms.utils.helpers import reversion_register # Cannot use contrib.auth.get_user_model() at compile time. user_app_name, user_model_name = settings.AUTH_USER_MODEL.rsplit('.', 1) User = None if DJANGO_1_6: for app in settings.INSTALLED_APPS: if app.endswith(user_app_name): user_app_models = importlib.import_module(app + ".models") User = getattr(user_app_models, user_model_name) break else: from django.apps import apps try: User = apps.get_registered_model(user_app_name, user_model_name) except KeyError: pass if User is None: raise ImproperlyConfigured( "You have defined a custom user model %s, but the app %s is not " "in settings.INSTALLED_APPS" % (settings.AUTH_USER_MODEL, user_app_name) ) # NOTE: those are not just numbers!! we will do binary AND on them, # so pay attention when adding/changing them, or MASKs.. ACCESS_PAGE = 1 ACCESS_CHILDREN = 2 # just immediate children (1 level) ACCESS_PAGE_AND_CHILDREN = 3 # just immediate children (1 level) ACCESS_DESCENDANTS = 4
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.apps import apps from .util import form_with_captcha __all__ = ["DatafileForm"] __author__ = "pmeier82" Asset = apps.get_registered_model("base", "asset") Datafile = apps.get_registered_model("djspikeval", "datafile") Dataset = apps.get_registered_model("djspikeval", "dataset") @form_with_captcha class DatafileForm(forms.ModelForm): """`Datafile` model form""" # meta class Meta: model = Datafile exclude = ("created", "modified", "valid_rd_log", "valid_gt_log") # extra fields rd_upload = forms.FileField(label="Rawdata File", required=False) gt_upload = forms.FileField(label="Groundtruth File", required=False) # constructor def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None)
from django.db import models from django.apps import apps from django.contrib.auth.models import User from datetime import datetime # get artist model artistmodel = apps.get_registered_model('Artists', 'Artist') artistpainting = apps.get_registered_model('Artists', 'Artistpainting') categorypainting = apps.get_registered_model('Artists', 'Paintingofcategory') # Create your models here. # artist detail class ArtistBlog(models.Model): artist = models.ForeignKey(artistmodel, on_delete=models.CASCADE) dob = models.DateTimeField() painting = models.CharField(max_length=300) address = models.CharField(max_length=150) awards = models.CharField(max_length=200) # Customer feedback class Feedback(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) feedback = models.CharField(max_length=300) # Customer review about the product class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.CharField(max_length=200)