10 examples of 'register model in admin django' in Python

Every line of 'register model in admin django' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
86def register(self, model_or_iterable, admin_class=None, **options):
87 """
88 Register the given model(s) with the given admin class.
89
90 The model(s) should be Model classes, not instances.
91
92 If an admin class isn't given, use ModelAdmin (the default admin
93 options). If keyword arguments are given -- e.g., list_display --
94 apply them as options to the admin class.
95
96 If a model is already registered, raise AlreadyRegistered.
97
98 If a model is abstract, raise ImproperlyConfigured.
99 """
100 admin_class = admin_class or ModelAdmin
101 if isinstance(model_or_iterable, ModelBase):
102 model_or_iterable = [model_or_iterable]
103 for model in model_or_iterable:
104 if model._meta.abstract:
105 raise ImproperlyConfigured(
106 'The model %s is abstract, so it cannot be registered with admin.' % model.__name__
107 )
108
109 if model in self._registry:
110 registered_admin = str(self._registry[model])
111 msg = 'The model %s is already registered ' % model.__name__
112 if registered_admin.endswith('.ModelAdmin'):
113 # Most likely registered without a ModelAdmin subclass.
114 msg += 'in app %r.' % re.sub(r'\.ModelAdmin$', '', registered_admin)
115 else:
116 msg += 'with %r.' % registered_admin
117 raise AlreadyRegistered(msg)
118
119 # Ignore the registration if the model has been
120 # swapped out.
121 if not model._meta.swapped:
122 # If we got **options then dynamically construct a subclass of
123 # admin_class with those **options.
124 if options:
125 # For reasons I don't quite understand, without a __module__
126 # the created class appears to "live" in the wrong place,
127 # which causes issues later on.
128 options['__module__'] = __name__
129 admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
130
131 # Instantiate the admin class to save in the registry
132 self._registry[model] = admin_class(model, self)
25def create_modeladmin(modeladmin, model, name=None):
26 """
27 Allows to register a model in multiple views
28 http://stackoverflow.com/questions/2223375/multiple-modeladmins-views-
29 for-same-model-in-django-admin
30 """
31
32 class Meta:
33 proxy = True
34 app_label = model._meta.app_label
35
36 attrs = {'__module__': '', 'Meta': Meta}
37
38 newmodel = type(name, (model,), attrs)
39
40 admin.site.register(newmodel, modeladmin)
41 return modeladmin
4def register(admin_register):
5 admin_register(LogsStore)
31def _register(perm, model):
32 """
33 Real method for registering permissions. This inner function is used
34 because it must also be called back from _register_delayed
35 """
36 ct = ContentType.objects.get_for_model(model)
37 obj, new = ObjectPermissionType.objects \
38 .get_or_create(name=perm, content_type=ct)
39 if new:
40 obj.save()
58def deregister(self, app_name, model):
59 """
60 """
61 raise NotImplementedError
34def register_concept(concept_class, *args, **kwargs):
35 """ A handler for third-party apps to make registering
36 extension models based on ``aristotle_mdr.models.concept`` easier.
37
38 Sets up the version controls, search indexes, django administrator page
39 and autocomplete handlers.
40 All ``args`` and ``kwargs`` are passed to the called methods. For examples of
41 what can be passed into this method review the other methods in
42 ``aristotle_mdr.register``.
43
44 Example usage (based on the models in the extensions test suite):
45
46 register_concept(Question, extra_fieldsets=[('Question','question_text'),]
47 """
48
49 register_concept_reversions(concept_class, *args, **kwargs) # must come before admin
50 register_concept_admin(concept_class, *args, **kwargs)
51 register_concept_search_index(concept_class, *args, **kwargs)
7def register(cls, admin_cls):
8 cls.add_to_class('category', models.ForeignKey('articles.Category', verbose_name=_('category')))
9
10 cls._meta.unique_together += [('category', 'slug')]
11
12 @classmethod
13 def get_urlpatterns(cls):
14 from articles.modules.category import views
15 return patterns('',
16 url(r'^(?P[a-z0-9_/-]+/)articles/(?P[a-z0-9_-]+)/$', views.CategoryArticleDetail.as_view(), name="article_detail"),
17 url(r'^(?P[a-z0-9_/-]+/)articles/$', views.CategoryArticleList.as_view(), name='article_category'),
18 url(r'^$', views.CategoryArticleList.as_view(), name='article_index'),
19 )
20 cls.get_urlpatterns = get_urlpatterns
21
22 def get_absolute_url(self):
23 return ('article_detail', 'articles.urls', (), {
24 'category_url': self.category.local_url,
25 'slug': self.slug,
26 })
27 cls.get_absolute_url = app_models.permalink(get_absolute_url)
28
29 if admin_cls:
30 admin_cls.list_filter += [ 'category',]
31 admin_cls.list_display.insert(1, 'category', )
32 admin_cls.add_extension_options(_('Category'), {
33 'fields': ('category',),
34 })
164def patch_admin(model, admin_site=None, AdminClass=None, skip_non_revision=False):
165 """
166 Enables version control with full admin integration for a model that has
167 already been registered with the django admin site.
168
169 This is excellent for adding version control to existing Django contrib
170 applications.
171
172 :param skip_non_revision: If ==True: Skip models that are not register with ModelAdmin
173 """
174 admin_site = admin_site or admin.site
175 try:
176 ModelAdmin = admin_site._registry[model].__class__
177 except KeyError:
178 raise NotRegistered("The model {model} has not been registered with the admin site.".format(model=model))
179
180 if skip_non_revision:
181 if not hasattr(ModelAdmin, "object_history_template"):
182 logger.info(
183 "Skip activate compare admin, because model %r is not registered with revision manager."
184 % model._meta.object_name
185 )
186 return
187
188 # Unregister existing admin class.
189 admin_site.unregister(model)
190
191 # Register patched admin class.
192 if not AdminClass:
193 from reversion_compare.admin import CompareVersionAdmin
194
195 class PatchedModelAdmin(CompareVersionAdmin, ModelAdmin):
196 pass
197
198 else:
199
200 class PatchedModelAdmin(AdminClass, ModelAdmin):
201 pass
202
203 admin_site.register(model, PatchedModelAdmin)
4def register(model, site=admin.site):
5 def decorator(klass):
6 site.register(model, klass)
7 return klass
8 return decorator
134def force_unregister(model_or_iterable, adminsite=None):
135 import django.contrib.admin
136 from iadmin.options import IModelAdmin
137 site = adminsite or django.contrib.admin.site
138 if isinstance(model_or_iterable, ModelBase):
139 model_or_iterable = [model_or_iterable]
140
141 for model in model_or_iterable:
142 if model in site._registry:
143 site.unregister(model)

Related snippets