本文整理汇总了Python中django.contrib.admin方法的典型用法代码示例。如果您正苦于以下问题:Python contrib.admin方法的具体用法?Python contrib.admin怎么用?Python contrib.admin使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.contrib
的用法示例。
在下文中一共展示了contrib.admin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_template_response
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def process_template_response(self, request, response):
try:
url = resolve(request.path_info)
except Resolver404:
return response
if not url.app_name == 'admin' and \
url.url_name not in ['index', 'app_list']:
# current view is not a django admin index
# or app_list view, bail out!
return response
try:
app_list = response.context_data['app_list']
except KeyError:
# there is no app_list! nothing to reorder
return response
self.init_config(request, app_list)
ordered_app_list = self.get_app_list()
response.context_data['app_list'] = ordered_app_list
return response
示例2: test_admin_excluded_when_false_in_settings
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def test_admin_excluded_when_false_in_settings():
"""Tests that admin views are not loaded when disabled in settings."""
# pylint: disable=protected-access
reload(subscription_admin)
try:
admin.site._registry[models.SubscriptionPlan]
except KeyError:
assert True
else:
assert False
try:
admin.site._registry[models.UserSubscription]
except KeyError:
assert True
else:
assert False
try:
admin.site._registry[models.SubscriptionTransaction]
except KeyError:
assert True
else:
assert False
示例3: test_no_resolver
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def test_no_resolver(self, request_factory):
request = request_factory.get('/admin/')
openapi_request = DjangoOpenAPIRequest(request)
path = {}
query = {}
headers = {
'Cookie': '',
}
cookies = {}
assert openapi_request.parameters == RequestParameters(
path=path,
query=query,
header=headers,
cookie=cookies,
)
assert openapi_request.method == request.method.lower()
assert openapi_request.full_url_pattern == \
request._current_scheme_host + request.path
assert openapi_request.body == request.body
assert openapi_request.mimetype == request.content_type
示例4: test_simple
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def test_simple(self, request_factory):
from django.urls import resolve
request = request_factory.get('/admin/')
request.resolver_match = resolve('/admin/')
openapi_request = DjangoOpenAPIRequest(request)
path = {}
query = {}
headers = {
'Cookie': '',
}
cookies = {}
assert openapi_request.parameters == RequestParameters(
path=path,
query=query,
header=headers,
cookie=cookies,
)
assert openapi_request.method == request.method.lower()
assert openapi_request.full_url_pattern == \
request._current_scheme_host + request.path
assert openapi_request.body == request.body
assert openapi_request.mimetype == request.content_type
示例5: delete
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def delete(self, **kwargs):
# first drop the table, we have to do this first, else
# django will complain about no content type existing
Model = apps.get_model("django_models_from_csv", self.name)
ModelSchemaEditor().drop_table(Model)
# then remove django app and content-types/permissions
app_config = apps.get_app_config("django_models_from_csv")
wipe_models_and_permissions(app_config, self.name)
# finally kill the row
super().delete(**kwargs)
# delete it from the django app registry
try:
del apps.all_models["django_models_from_csv"][self.name]
except KeyError as err:
raise LookupError("'{}' not found.".format(self.name))
# Unregister the model from the admin, before we wipe it out
try:
admin.site.unregister(Model)
except admin.sites.NotRegistered:
pass
示例6: _build_context
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def _build_context(self, request, customer_uuid):
"""
Build common context parts used by different handlers in this view.
"""
# TODO: pylint acts stupid - find a way around it without suppressing
enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid) # pylint: disable=no-member
search_keyword = self.get_search_keyword(request)
linked_learners = self.get_enterprise_customer_user_queryset(request, search_keyword, customer_uuid)
pending_linked_learners = self.get_pending_users_queryset(search_keyword, customer_uuid)
context = {
self.ContextParameters.ENTERPRISE_CUSTOMER: enterprise_customer,
self.ContextParameters.PENDING_LEARNERS: pending_linked_learners,
self.ContextParameters.LEARNERS: linked_learners,
self.ContextParameters.SEARCH_KEYWORD: search_keyword or '',
self.ContextParameters.ENROLLMENT_URL: settings.LMS_ENROLLMENT_API_PATH,
}
context.update(admin.site.each_context(request))
context.update(self._build_admin_context(request, enterprise_customer))
return context
示例7: revert
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def revert(self, request, queryset):
"""
Admin action to revert a configuration back to the selected value
"""
if queryset.count() != 1:
self.message_user(request, _("Please select a single configuration to revert to."))
return
target = queryset[0]
target.id = None
target.changed_by = request.user
target.save(action_type='create')
self.message_user(request, _("Reverted configuration."))
return HttpResponseRedirect(
reverse(
'admin:{}_{}_change'.format(
self.model._meta.app_label,
self.model._meta.model_name,
),
args=(target.id,),
)
)
示例8: get_inline_actions
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def get_inline_actions(self, request, obj=None):
"""
Returns a list of all actions for this Admin.
"""
# If self.actions is explicitly set to None that means that we don't
# want *any* actions enabled on this page.
if self.inline_actions is None:
return []
actions = []
# Gather actions from the inline admin and all parent classes,
# starting with self and working back up.
for klass in self.__class__.mro()[::-1]:
class_actions = getattr(klass, 'inline_actions', [])
# Avoid trying to iterate over None
if not class_actions:
continue
for action in class_actions:
if action not in actions:
actions.append(action)
return actions
示例9: test_delete_str_in_model_admin
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def test_delete_str_in_model_admin(self):
"""
Test if the admin delete page shows the correct string representation
for a proxy model.
"""
user = TrackerUser.objects.get(name='Django Pony')
proxy = ProxyTrackerUser.objects.get(name='Django Pony')
user_str = 'Tracker user: <a href="%s">%s</a>' % (
reverse('admin_proxy:proxy_models_trackeruser_change', args=(user.pk,)), user
)
proxy_str = 'Proxy tracker user: <a href="%s">%s</a>' % (
reverse('admin_proxy:proxy_models_proxytrackeruser_change', args=(proxy.pk,)), proxy
)
self.client.force_login(self.superuser)
response = self.client.get(reverse('admin_proxy:proxy_models_trackeruser_delete', args=(user.pk,)))
delete_str = response.context['deleted_objects'][0]
self.assertEqual(delete_str, user_str)
response = self.client.get(reverse('admin_proxy:proxy_models_proxytrackeruser_delete', args=(proxy.pk,)))
delete_str = response.context['deleted_objects'][0]
self.assertEqual(delete_str, proxy_str)
示例10: init_config
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def init_config(self, request, app_list):
self.request = request
self.app_list = app_list
self.config = getattr(settings, 'ADMIN_REORDER', None)
if not self.config:
# ADMIN_REORDER settings is not defined.
raise ImproperlyConfigured('ADMIN_REORDER config is not defined.')
if not isinstance(self.config, (tuple, list)):
raise ImproperlyConfigured(
'ADMIN_REORDER config parameter must be tuple or list. '
'Got {config}'.format(config=self.config))
admin_index = admin.site.index(request)
try:
# try to get all installed models
app_list = admin_index.context_data['app_list']
except KeyError:
# use app_list from context if this fails
pass
# Flatten all models from apps
self.models_list = []
for app in app_list:
for model in app['models']:
model['model_name'] = self.get_model_name(
app['app_label'], model['object_name'])
self.models_list.append(model)
示例11: _using_hijack_admin_mixin
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def _using_hijack_admin_mixin():
from hijack_admin.admin import HijackUserAdminMixin
user_admin_class_name = getattr(
settings, 'HIJACK_USER_ADMIN_CLASS_NAME', None)
user_admin_class = user_admin_class_name \
if user_admin_class_name else type(
admin.site._registry.get(get_user_model(), None))
return issubclass(user_admin_class, HijackUserAdminMixin)
示例12: check_get_requests_allowed
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def check_get_requests_allowed(app_configs, **kwargs):
errors = []
if not hijack_settings.HIJACK_ALLOW_GET_REQUESTS:
errors.append(
Error(
'Hijack GET requests must be allowed for django-hijack-admin to work.',
hint='Set HIJACK_ALLOW_GET_REQUESTS to True.',
obj=None,
id='hijack_admin.E001',
)
)
return errors
示例13: check_custom_user_model
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def check_custom_user_model(app_configs, **kwargs):
warnings = []
if (settings.AUTH_USER_MODEL != DEFAULT_AUTH_USER_MODEL and
not _using_hijack_admin_mixin()):
warnings.append(
Warning(
'django-hijack-admin does not work out the box with a custom user model.',
hint='Please mix HijackUserAdminMixin into your custom UserAdmin.',
obj=settings.AUTH_USER_MODEL,
id='hijack_admin.W001',
)
)
return warnings
示例14: clear_logs
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def clear_logs(request):
"""Clear admin activity logs if user has permissions"""
if not request.user.is_authenticated(): # should be applied to anything under /console
return redirect('login')
if request.user.has_perm('admin.delete_logentry'):
LogEntry.objects.all().filter(user__pk=request.user.id).delete()
messages.info(request, 'Successfully cleared admin activity logs.', fail_silently=True)
else:
messages.warning(request, 'Unable to clear the admin activity logs.', fail_silently=True)
return redirect('admin:index')
示例15: test_basic_merged_view
# 需要导入模块: from django import contrib [as 别名]
# 或者: from django.contrib import admin [as 别名]
def test_basic_merged_view(self):
"""
With no special settings, the MergedInlineAdmin should order the
merged inlines by ID
"""
response = self.client.get(reverse('admin:tests_author_change', args=(1,)))
self.assertEqual(response.status_code, 200)
self.assertStringOrder(response, [
'Romeo and Juliet',
'Shall I compare thee to a summer',
'A Midsummer Night',
'As a decrepit father takes delight',
'Julius Caesar',
])