Here are the examples of the python api django.db.models.get_model taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
148 Examples
4
Example 1
Project: snowy Source File: startmigration.py
def model_unkey(key):
"For 'appname.modelname', return the model."
app, modelname = key.split(".", 1)
model = models.get_model(app, modelname)
if not model:
print "Couldn't find model '%s' in app '%s'" % (modelname, app)
sys.exit(1)
return model
3
Example 2
def get_initial_value(app_label, model_name, field_name):
"""Derive an initial value for a field.
If a default has been provided on the field definition or the field allows
for an empty string, that value will be used. Otherwise, a placeholder
callable will be used. This callable cannot actually be used in an
evolution, but will indicate that user input is required.
"""
model = models.get_model(app_label, model_name)
field = model._meta.get_field(field_name)
if field and (field.has_default() or (field.empty_strings_allowed and field.blank)):
return field.get_default()
return NullFieldInitialCallback(app_label, model_name, field_name)
3
Example 3
def render(self, context):
model = get_model(*self.model.split('.'))
if model is None:
raise TemplateSyntaxError(_('tag_cloud_for_model tag was given an invalid model: %s') % self.model)
context[self.context_var] = \
Tag.objects.cloud_for_model(model, **self.kwargs)
return ''
3
Example 4
Project: django-secure-auth Source File: auth_forms.py
def get_available_auth_methods(user):
available = []
for auth_type in AUTH_TYPES:
if not auth_type[0]:
available.append(auth_type)
continue
model = get_model('secureauth', 'UserAuth%s' % auth_type[0])
if model.objects.filter(user=user, enabled=True).exists():
available.append(auth_type)
return available
3
Example 5
Project: milkman Source File: dairy.py
def get_model_class_from_string(self, model_name):
assert '.' in model_name, ("'model_class' must be either a model"
" or a model name in the format"
" app_label.model_name")
app_label, model_name = model_name.split(".")
return models.get_model(app_label, model_name)
3
Example 6
Project: jaikuenginepatch Source File: dbutils.py
@property
def reference_class(self):
if isinstance(self._reference_class, basestring):
from django.db import models
self._reference_class = models.get_model(
*self._reference_class.split('.', 1))
return self._reference_class
3
Example 7
Project: zipfelchappe Source File: forms.py
def get_backer_profile_form():
from .app_settings import BACKER_PROFILE
if BACKER_PROFILE:
from django.db import models
app_label, model_name = BACKER_PROFILE.split('.')
profile_model = models.get_model(app_label, model_name)
class BackerProfileForm(forms.ModelForm):
class Meta:
model = profile_model
exclude = ('backer',)
else:
class BackerProfileForm(forms.Form):
""" Empty form """
def save(self, *args, **kwargs):
return None
return BackerProfileForm
3
Example 8
Project: neo4django Source File: nodequeryset_tests.py
def setup():
global Person, neo4django, gdb, Query, OPERATORS, IndexedMouse, \
DEFAULT_DB_ALIAS, Condition, models, RelatedCat, RelatedDog
from neo4django.tests import Person, neo4django, gdb
from neo4django.db import DEFAULT_DB_ALIAS, models
from neo4django.db.models.query import Query, OPERATORS, \
Condition
from django.db.models import get_model
RelatedCat = get_model('tests','RelatedCat')
RelatedDog = get_model('tests','RelatedDog')
IndexedMouse = get_model('tests','IndexedMouse')
3
Example 9
Project: django-oscar-support Source File: utils.py
@classmethod
def generate_ticket_number(cls):
return {
# we don't want the ticket number to start at zero
'number': get_model('oscar_support', 'Ticket').objects.count() + 1,
'subticket_id': 0,
}
3
Example 10
Project: django-entity-event Source File: context_loader.py
def load_fetched_objects_into_contexts(events, model_data, context_hints_per_source):
"""
Given the fetched model data and the context hints for each source, go through each
event and populate the contexts with the loaded information.
"""
for event in events:
context_hints = context_hints_per_source.get(event.source, {})
for context_key, hints in context_hints.items():
model = get_model(hints['app_name'], hints['model_name'])
for d, value in dict_find(event.context, context_key):
if isinstance(value, list):
for i, model_id in enumerate(d[context_key]):
d[context_key][i] = model_data[model].get(model_id)
else:
d[context_key] = model_data[model].get(value)
3
Example 11
def create(self, is_social, **kwargs):
if 'user' not in kwargs and 'user_id' not in kwargs:
siteuser_model = models.get_model('social_login', 'SiteUser')
user = siteuser_model.objects.create(is_social=is_social)
kwargs['user_id'] = user.id
return super(BaseManager, self).create(**kwargs)
3
Example 12
def render(self, context):
model = get_model(*self.model.split('.'))
if model is None:
raise TemplateSyntaxError(_('supertagged_objects tag was given an invalid model: %s') % self.model)
context[self.context_var] = \
SuperTaggedItem.objects.get_by_model(model, self.tag.resolve(context))
return ''
3
Example 13
Project: django-userprofiles Source File: test_utils.py
@override_settings(USERPROFILES_USE_PROFILE=True)
def test_get_profile_module_enabled(self):
settings.AUTH_PROFILE_MODULE = None
self.assertRaises(SiteProfileNotAvailable, utils.get_profile_model)
settings.AUTH_PROFILE_MODULE = 'test_project.test_accounts.Profile'
self.assertRaises(SiteProfileNotAvailable, utils.get_profile_model)
settings.AUTH_PROFILE_MODULE = 'test_accounts.InvalidProfile'
self.assertRaises(SiteProfileNotAvailable, utils.get_profile_model)
settings.AUTH_PROFILE_MODULE = 'test_accounts.Profile'
self.assertEqual(utils.get_profile_model(), get_model('test_accounts', 'Profile'))
3
Example 14
def discover_models(self):
apps = [(app, get_app(app)) for app in self.apps]
for app_name, app_module in apps:
self.appmodels[app_name] = []
models = get_models(app_module)
models_to_exclude = getattr(settings, 'DILLA_EXCLUDE_MODELS', None)
if models_to_exclude:
for excluded_model in models_to_exclude:
try:
models.remove(get_model(*excluded_model.split('.')))
except ValueError:
pass
self.appmodels[app_name].extend(models)
log.debug('Preparing to spam following models: %s' % self.appmodels)
3
Example 15
Project: django-form-designer Source File: fields.py
@staticmethod
def get_model_from_string(model_path):
try:
app_label, model_name = model_path.rsplit('.models.')
return models.get_model(app_label, model_name)
except:
return None
3
Example 16
Project: sharding-example Source File: integration.py
def test_get_model_on_slaves(self):
# Ensure we're registered as part of the app's models (both abstract and partitions)
from django.db.models import get_model
result = get_model('sample', 'testmodel_partition0', only_installed=False)
self.assertNotEquals(result, None)
self.assertEqual(result.__name__, 'TestModel_Partition0')
3
Example 17
Project: django-fancypages Source File: fp_container_tags.py
def get_container(self, context):
Container = get_model('fancypages', 'Container')
# check first if the container name refers to a
# variable in the context and use it a container
try:
return self.container_name.resolve(context)
except template.VariableDoesNotExist:
pass
# container variable is not in the context. we have to look
# up the container from the variable name and - if the object
# is not None - the object the container is attached to.
try:
ctn = Container.get_container_by_name(
name=self.container_name.var, obj=self.object,
language_code=self.language_code)
except KeyError:
ctn = None
return ctn
3
Example 18
def get_notification_language(user):
"""
Returns site-specific notification language for this user. Raises
LanguageStoreNotAvailable if this site does not use translated
notifications.
"""
LANGUAGE_MODULE = getattr(settings, 'NOTIFICATION_LANGUAGE_MODULE', False)
if LANGUAGE_MODULE:
try:
app_label, model_name = LANGUAGE_MODULE.split('.')
model = models.get_model(app_label, model_name)
language_model = model.objects.get(user__id__exact=user.id)
if hasattr(language_model, 'language'):
return language_model.language
except (ImportError, ImproperlyConfigured, model.DoesNotExist):
raise LanguageStoreNotAvailable
raise LanguageStoreNotAvailable
3
Example 19
Project: django-la-facebook Source File: default.py
def create_profile(self, request, access, token, user):
if hasattr(settings, 'AUTH_PROFILE_MODULE'):
profile_model = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
profile, created = profile_model.objects.get_or_create(
user = user,
)
profile = self.update_profile_from_graph(request, access, token, profile)
profile.save()
else:
# Do nothing because users have no site profile defined
# TODO - should we pass a warning message? Raise a SiteProfileNotAvailable error?
logger.warning("DefaultFacebookCallback.create_profile: unable to" \
"create/update profile as no AUTH_PROFILE_MODULE setting" \
"has been defined")
pass
3
Example 20
Project: hydroshare2 Source File: __init__.py
def edit(request):
"""
Process the inline editing form.
"""
model = get_model(request.POST["app"], request.POST["model"])
obj = model.objects.get(id=request.POST["id"])
form = get_edit_form(obj, request.POST["fields"], data=request.POST,
files=request.FILES)
authorize(request, obj)
if form.is_valid():
form.save()
model_admin = ModelAdmin(model, admin.site)
message = model_admin.construct_change_message(request, form, None)
model_admin.log_change(request, obj, message)
response = ""
else:
response = list(form.errors.values())[0][0]
return HttpResponse(response)
3
Example 21
Project: timebank Source File: auth_backends.py
@property
def user_class(self):
if not hasattr(self, '_user_class'):
self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
if not self._user_class:
raise ImproperlyConfigured('Could not get custom user model')
return self._user_class
3
Example 22
Project: dynamic-models Source File: dynamic_models.py
def build_existing_survey_response_models():
""" Builds all existing dynamic models at once. """
# To avoid circular imports, the model is retrieved from the model cache
Survey = models.get_model('surveymaker', 'Survey')
for survey in Survey.objects.all():
Response = get_survey_response_model(survey)
# Create the table if necessary, shouldn't be necessary anyway
utils.create_db_table(Response)
# While we're at it...
utils.add_necessary_db_columns(Response)
3
Example 23
def handle_label(self, label, **options):
self.stdout.write('Rebuilding TransitionLog states for %s\n' % label)
app_label, model_label = label.rsplit('.', 1)
model = models.get_model(app_label, model_label)
if not hasattr(model, '_workflows'):
raise base.CommandError("Model %s isn't attached to a workflow." % label)
for field_name, state_field in model._workflows.items():
self._handle_field(label, model, field_name, state_field.workflow, **options)
3
Example 24
Project: django-oscar-support Source File: utils.py
@classmethod
def get_initial_status(cls):
TicketStatus = get_model("oscar_support", "TicketStatus")
try:
initial_status = TicketStatus.objects.get(
slug=defaults.SUPPORT_INITIAL_STATUS_SLUG
)
except TicketStatus.DoesNotExist:
initial_status = TicketStatus.objects.create(
slug=defaults.SUPPORT_INITIAL_STATUS_SLUG,
name=defaults.SUPPORT_INITIAL_STATUS
)
return initial_status
3
Example 25
Project: django-dockit Source File: xml_serializer.py
def _get_model_from_node(self, node, attr):
"""
Helper to look up a model from a <object model=...> or a <field
rel=... to=...> node.
"""
model_identifier = node.getAttribute(attr)
if not model_identifier:
raise base.DeserializationError(
"<%s> node is missing the required '%s' attribute" \
% (node.nodeName, attr))
try:
Model = models.get_model(*model_identifier.split("."))
except TypeError:
Model = None
if Model is None:
raise base.DeserializationError(
"<%s> node has invalid model identifier: '%s'" % \
(node.nodeName, model_identifier))
return Model
3
Example 26
def add_role(self, name, permissions):
'''
e.g. add_role('accountant', [('finance','BusinessPlan', 'can_review')])
'''
role, flag = Group.objects.get_or_create(name=name)
log('role', role)
for app_label, model_class_name, codename in permissions:
model_class = django.db.models.get_model(app_label, model_class_name)
content_type = ContentType.objects.get_for_model(model_class)
permission = Permission.objects.get(content_type=content_type,
codename=codename)
role.permissions.add(permission)
log('%s.permission' % role.name, permission)
role.save()
self.roles[name] = role
return role
3
Example 27
def get_notification_language(user):
"""
Returns site-specific notification language for this user. Raises
LanguageStoreNotAvailable if this site does not use translated
notifications.
"""
if getattr(settings, "NOTIFICATION_LANGUAGE_MODULE", False):
try:
app_label, model_name = settings.NOTIFICATION_LANGUAGE_MODULE.split(".")
model = models.get_model(app_label, model_name)
language_model = model._default_manager.get(user__id__exact=user.id)
if hasattr(language_model, "language"):
return language_model.language
except (ImportError, ImproperlyConfigured, model.DoesNotExist):
raise LanguageStoreNotAvailable
raise LanguageStoreNotAvailable
3
Example 28
Project: django-easymode Source File: easy_locale.py
def handle(self, targetdir, app=None, **options):
""" command execution """
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
models = get_models(get_app(unpack[0]))
else:
models = get_models()
messagemaker = MakeModelMessages(targetdir)
for model in models:
if hasattr(model, 'localized_fields'):
for instance in model.objects.all():
messagemaker(instance)
3
Example 29
def render(self, context):
model = get_model(*self.model.split('.'))
if model is None:
raise TemplateSyntaxError(_('supertagged_objects tag was given an invalid model: %s') % self.model)
context[self.context_var] = \
SuperTaggedItem.objects.get_related(self.obj.resolve(context), model, **self.kwargs)
return ''
3
Example 30
def render(self, context):
# Let any VariableDoesNotExist raised bubble up
args = [self.node.resolve(context)]
if self.foreign_key is not None:
app_label, model_name, fk_attr = self.foreign_key.split('.')
cls = get_model(app_label, model_name)
if cls is None:
raise template.TemplateSyntaxError(_('drilldown_tree_for_node tag was given an invalid model: %s') % '.'.join([app_label, model_name]))
try:
cls._meta.get_field(fk_attr)
except FieldDoesNotExist:
raise template.TemplateSyntaxError(_('drilldown_tree_for_node tag was given an invalid model field: %s') % fk_attr)
args.extend([cls, fk_attr, self.count_attr, self.cuemulative])
context[self.context_var] = drilldown_tree_for_node(*args)
return ''
3
Example 31
def import_model(path):
"""
Passed a string "app.Model", will return Model registered inside app.
"""
split = path.split('.', 1)
return get_model(split[0], split[1])
3
Example 32
def _resolve_model(obj):
"""
Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situtations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key definition.
String representations should have the format:
'appname.ModelName'
"""
if type(obj) == str and len(obj.split(".")) == 2:
app_name, model_name = obj.split(".")
return models.get_model(app_name, model_name)
elif inspect.isclass(obj) and issubclass(obj, models.Model):
return obj
else:
raise ValueError("{0} is not a Django model".format(obj))
3
Example 33
def get_partition(self, partition_key, create=True):
""" Get the partition for this model for partition_key. By default,
this will create the partition. Pass create=False to prevent this.
"""
app_label = self.model._meta.app_label
model_name = self._model_name_for_partition(partition_key)
model = get_model(app_label, model_name)
if model is None and create:
return self._ensure_partition(partition_key)
else:
return model
3
Example 34
def _get_manager(self, model_or_manager):
"""
Utility function to return default manager from model or instance
object or given manager.
"""
if isinstance(model_or_manager, basestring):
app, model = model_or_manager.split('.')
model_or_manager = get_model(app, model)
if hasattr(model_or_manager, '_default_manager'):
return model_or_manager._default_manager
return model_or_manager
3
Example 35
Project: blue-channel Source File: tagging_tags.py
def render(self, context):
model = get_model(*self.model.split('.'))
if model is None:
raise TemplateSyntaxError(_('tagged_objects tag was given an invalid model: %s') % self.model)
context[self.context_var] = \
TaggedItem.objects.get_by_model(model, self.tag.resolve(context))
return ''
3
Example 36
@property
def products(self):
Product = models.get_model('catalogue', 'Product')
product_range = self.offer.condition.range
if product_range.includes_all_products:
return Product.browsable.filter(is_discountable=True)
return product_range.included_products.filter(is_discountable=True)
3
Example 37
def render(self, context):
model = get_model(*self.model.split('.'))
if model is None:
raise TemplateSyntaxError('most_popular_for_model tag was given an invalid model: %s' % self.model)
context[self.context_var] = ViewTracker.objects.get_for_model(model=model).get_most_popular(limit=self.limit)
return ''
3
Example 38
Project: django-object-events Source File: models.py
def __init__(self):
"""Checks if there's a user profile."""
if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
raise SiteProfileNotAvailable(
'You need to set AUTH_PROFILE_MODULE in your project settings')
try:
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
except ValueError:
raise SiteProfileNotAvailable(
'app_label and model_name should be separated by a dot in'
' the AUTH_PROFILE_MODULE setting')
self.model = models.get_model(app_label, model_name)
if self.model is None:
raise SiteProfileNotAvailable(
'Unable to load the profile model, check'
' AUTH_PROFILE_MODULE in your project settings')
if not hasattr(self.model(), 'interval'):
raise SiteProfileNotAvailable('Model has no field "interval"')
3
Example 39
Project: django-signalqueue Source File: mappings.py
@classmethod
def model_from_identifier(cls, model_identifier):
from django.db.models import get_model
try:
return get_model(*model_identifier.split('.'))
except (TypeError, AttributeError, ValueError):
return None
3
Example 40
def get_models(self):
"""Return an alphabetical list of model classes in the index."""
search_models = self.models
if self.cleaned_data['models']:
search_models = []
for model in self.cleaned_data['models']:
class_model = models.get_model(*model.split('.'))
#if class_model._meta.model_name in INCLUDED_APPS:
search_models.append(class_model)
return search_models
3
Example 41
Project: django-zebra Source File: views.py
def _try_to_get_customer_from_customer_id(stripe_customer_id):
if options.ZEBRA_CUSTOMER_MODEL:
m = get_model(*options.ZEBRA_CUSTOMER_MODEL.split('.'))
try:
return m.objects.get(stripe_customer_id=stripe_customer_id)
except:
pass
return None
3
Example 42
Project: templated-emails Source File: utils.py
def get_users_language(user):
"""
Returns site-specific language for this user. Raises
LanguageStoreNotAvailable if this site does not use translated
notifications.
"""
if getattr(settings, 'NOTIFICATION_LANGUAGE_MODULE', False):
try:
app_label, model_name = settings.NOTIFICATION_LANGUAGE_MODULE.split('.')
model = models.get_model(app_label, model_name)
language_model = model._default_manager.get(user__id__exact=user.id)
if hasattr(language_model, 'language'):
return language_model.language
except (ImportError, ImproperlyConfigured, model.DoesNotExist):
raise LanguageStoreNotAvailable
raise LanguageStoreNotAvailable
3
Example 43
Project: django-databrowse Source File: sites.py
def model_page(self, request, app_label, model_name, rest_of_url=None):
"""
Handles the model-specific functionality of the databrowse site,
delegating<to the appropriate ModelDatabrowse class.
"""
try:
model = get_model(app_label, model_name)
except LookupError:
model = None
if model is None:
raise http.Http404("App %r, model %r, not found." %
(app_label, model_name))
try:
databrowse_class = self.registry[model]
except KeyError:
raise http.Http404("This model exists but has not been registered "
"with databrowse.")
return databrowse_class(model, self).root(request, rest_of_url)
3
Example 44
Project: tastypie_user_session Source File: auth.py
def _get_user_profile_class(self):
"""
TODO: Figure out if we should check that
settings.AUTH_PROFILE_MODULE is properly set.
Currently, we just assume it is and use it.
"""
app_label, model_name = settings.AUTH_PROFILE_MODULE.split(".")
return models.get_model(app_label, model_name)
3
Example 45
Project: django-dbsettings Source File: forms.py
def specialize(self, field):
"Wrapper to add module_name and class_name for regrouping"
field.label = capfirst(field.label)
module_name, class_name, _ = RE_FIELD_NAME.match(field.name).groups()
app_label = self.apps[field.name]
field.module_name = app_label
if class_name:
model = get_model(app_label, class_name)
if model:
class_name = model._meta.verbose_name
field.class_name = class_name
field.verbose_name = self.verbose_names[field.name]
return field
3
Example 46
def get_user_model():
from . import app_settings
from django.db.models import get_model
try:
app_label, model_name = app_settings.USER_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the"
" form 'app_label.model_name'")
user_model = get_model(app_label, model_name)
if user_model is None:
raise ImproperlyConfigured("AUTH_USER_MODEL refers to model"
" '%s' that has not been installed"
% app_settings.USER_MODEL)
return user_model
3
Example 47
def get_file(request, app_label, model_name, field_name, object_id, filename):
model = get_model(app_label, model_name)
instance = get_object_or_404(model, pk =unquote(object_id))
condition = getattr(instance, field_name).condition
if not model:
raise Http404("")
if not hasattr(instance, field_name):
raise Http404("")
if condition(request, instance):
pre_download.send(sender = model, instance = instance, field_name = field_name, request = request)
return METHOD(request, instance, field_name)
else:
raise PermissionDenied()
3
Example 48
def render(self, context):
cls = get_model(*self.model.split('.'))
if cls is None:
raise template.TemplateSyntaxError(_('full_tree_for_model tag was given an invalid model: %s') % self.model)
context[self.context_var] = cls._tree_manager.all()
return ''
3
Example 49
def get_user_model():
custom_model = settings.ODESK_CUSTOM_USER_MODEL
if not custom_model:
return User
app_label, model_name = custom_model.split('.')
model = models.get_model(app_label, model_name)
if model is None:
raise ImproperlyConfigured('Unable to load the user model' +\
'check ODESK_CUSTOM_USER_MODEL in your project settings')
return model
3
Example 50
def decode_object(ref):
decoded = ref.split(".")
if len(decoded) == 4:
app, name, pk, msgid = decoded
return get_model(app, name).objects.get(pk=pk), msgid
app, name, pk = decoded
return get_model(app, name).objects.get(pk=pk), None