本文整理汇总了Python中django.contrib.admin.AdminSite.register方法的典型用法代码示例。如果您正苦于以下问题:Python AdminSite.register方法的具体用法?Python AdminSite.register怎么用?Python AdminSite.register使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.contrib.admin.AdminSite
的用法示例。
在下文中一共展示了AdminSite.register方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_default_change_form_template
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
def test_default_change_form_template(self):
site = AdminSite()
site.register(SimpleModel, TranslatableAdmin)
admin = site._registry[SimpleModel]
self.assertEqual(admin.default_change_form_template, "admin/change_form.html")
# Avoid str + __proxy__ errors
self.assertEqual("default/" + admin.default_change_form_template, "default/admin/change_form.html")
示例2: PublishPage
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class PublishPage(TestCase):
def setUp(self):
super(PublishPage, self).setUp()
self.admin_site = AdminSite('Test Admin')
class PageAdmin(PublishableAdmin):
pass
self.admin_site.register(Page, PageAdmin)
self.page_admin = PageAdmin(Page, self.admin_site)
def test_should_be_publish(self):
self.page1 = Page.objects.create(slug='page1', title='page 1')
user1 = User.objects.create_superuser('test1', '[email protected]',
'pass')
self.factory = RequestFactory()
request = self.factory.post('/publish/change_view',
data={'_publish': ''})
request.user = user1
self.page_admin.change_view(request, str(self.page1.id))
self.assertEqual(Page.objects.filter(Page.Q_PUBLISHED,
slug=self.page1.slug).count(), 1)
def test_should_be_republish(self):
self.page1 = Page.objects.create(slug='page1', title='page 1')
self.page1.publish()
user1 = User.objects.create_superuser('test1', '[email protected]',
'pass')
self.factory = RequestFactory()
request = self.factory.post('/publish/change_view',
data={'_publish': ''})
request.user = user1
self.page_admin.change_view(request, str(self.page1.id))
self.assertEqual(Page.objects.filter(Page.Q_PUBLISHED,
slug=self.page1.slug).count(), 1)
示例3: TestGetGrootPermissions
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class TestGetGrootPermissions(TestCase):
def setUp(self):
self.site = AdminSite(name='admin')
def test_default_perms(self):
self.site.register(Author, AuthorAdmin)
author_admin = self.site._registry[Author]
permissions = author_admin.get_groot_permissions(request=None)
self.assertListEqual(
list(permissions.values_list('codename', flat=True)),
['add_author', 'change_author', 'delete_author'],
)
def test_limited_perms(self):
self.site.register(Author, AuthorAdmin, groot_permissions=('add_author',))
author_admin = self.site._registry[Author]
permissions = author_admin.get_groot_permissions(request=None)
self.assertListEqual(
list(permissions.values_list('codename', flat=True)), ['add_author'],
)
示例4: super
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
actions = super(PollAdmin, self).get_change_actions(request, object_id, form_url)
actions = list(actions)
if not request.user.is_superuser:
return []
obj = self.model.objects.get(pk=object_id)
if obj.question.endswith('?'):
actions.remove('question_mark')
return actions
admin.site.register(Poll, PollAdmin)
class CommentAdmin(DjangoObjectActions, admin.ModelAdmin):
# Object actions
################
def hodor(self, request, obj):
if not obj.comment:
# bail because we need a comment
return
obj.comment = ' '.join(['hodor' for x in obj.comment.split()])
obj.save()
change_actions = ('hodor', )
admin.site.register(Comment, CommentAdmin)
support_admin = AdminSite(name='support')
support_admin.register(Poll, PollAdmin)
示例5: TestPublishableAdmin
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class TestPublishableAdmin(TestCase):
def setUp(self):
super(TestPublishableAdmin, self).setUp()
self.page1 = Page.objects.create(slug='page1', title='page 1')
self.page2 = Page.objects.create(slug='page2', title='page 2')
self.page1.publish()
self.page2.publish()
self.author1 = Author.objects.create(name='a1')
self.author2 = Author.objects.create(name='a2')
self.author1.publish()
self.author2.publish()
self.admin_site = AdminSite('Test Admin')
class PageBlockInline(PublishableStackedInline):
model = PageBlock
class PageAdmin(PublishableAdmin):
inlines = [PageBlockInline]
self.admin_site.register(Page, PageAdmin)
self.page_admin = PageAdmin(Page, self.admin_site)
# override urls, so reverse works
settings.ROOT_URLCONF = patterns(
'',
('^admin/',
include(self.admin_site.urls)),
)
def test_get_publish_status_display(self):
page = Page.objects.create(slug="hhkkk", title="hjkhjkh")
self.failUnlessEqual('Changed - not yet published',
self.page_admin.get_publish_status_display(page))
page.publish()
self.failUnlessEqual('Published',
self.page_admin.get_publish_status_display(page))
page.save()
self.failUnlessEqual('Changed',
self.page_admin.get_publish_status_display(page))
page.delete()
self.failUnlessEqual('To be deleted',
self.page_admin.get_publish_status_display(page))
def test_queryset(self):
# make sure we only get back draft objects
request = None
self.failUnlessEqual(
set([self.page1, self.page1.public, self.page2,
self.page2.public]),
set(Page.objects.all())
)
self.failUnlessEqual(
set([self.page1, self.page2]),
set(self.page_admin.queryset(request))
)
def test_get_actions_global_delete_replaced(self):
from publish.actions import delete_selected
class request(object):
GET = {}
actions = self.page_admin.get_actions(request)
self.failUnless('delete_selected' in actions)
action, name, description = actions['delete_selected']
self.failUnlessEqual(delete_selected, action)
self.failUnlessEqual('delete_selected', name)
self.failUnlessEqual(delete_selected.short_description, description)
def test_formfield_for_foreignkey(self):
# foreign key forms fields in admin
# for publishable models should be filtered
# to hide public object
request = None
parent_field = None
for field in Page._meta.fields:
if field.name == 'parent':
parent_field = field
break
self.failUnless(parent_field)
choice_field = self.page_admin.formfield_for_foreignkey(parent_field,
request)
self.failUnless(choice_field)
self.failUnless(isinstance(choice_field, ModelChoiceField))
self.failUnlessEqual(
set([self.page1, self.page1.public, self.page2,
self.page2.public]),
set(Page.objects.all())
)
self.failUnlessEqual(
set([self.page1, self.page2]),
set(choice_field.queryset)
#.........这里部分代码省略.........
示例6: PageAdmin
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class PageAdmin(admin.ModelAdmin):
inlines = [PageInline]
class MenuAdmin(admin.ModelAdmin):
inlines = [MenuInline]
admin.site.register(Student, MyUserAdmin)
admin.site.register(Course)
admin.site.register(Group, GroupAdmin)
admin.site.register(Enroll, EnrollAdmin)
admin.site.register(Period)
admin.site.register(Category)
admin.site.register(MenuItem, MenuAdmin)
admin.site.register(Page, PageAdmin)
admin.site.site_header = _("Academica administrator site")
admin_site = AdminSite(name='matricula_admin')
admin_site.site_header = _("Academica administrator site")
admin_site.register(Student, MyUserAdmin)
admin_site.register(Course)
admin_site.register(Group, GroupAdmin)
admin_site.register(Enroll, EnrollAdmin)
admin_site.register(Period)
admin_site.register(Category)
admin_site.register(MenuItem, MenuItemAdmin)
admin_site.register(Page, PageAdmin)
示例7: AdminSite
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
# #Uncomment this to test issue #1:
#from fuzziverse.user_admin import user_admin_site
from django.contrib.admin import AdminSite
user_admin_site = AdminSite()
from nested_inline.admin import NestedStackedInline, NestedModelAdmin
from fuzziverse import models
class FileUploadInline(NestedStackedInline):
model = models.InputTestCase
min_num = 0
extra = 1
class ReportInline(NestedStackedInline):
model = models.Report
min_num = 0
extra = 1
class FuzzingAttemptInline(NestedStackedInline):
model = models.FuzzingAttempt
min_num = 0
extra = 1
inlines = [FileUploadInline]
readonly_fields = ['created']
class ApplicationAdmin(NestedModelAdmin):
inlines = [ReportInline, FuzzingAttemptInline]
search_fields = ['name']
user_admin_site.register(models.Application, ApplicationAdmin)
示例8: AdminSite
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
from django.conf import settings
from django.contrib.admin import AdminSite
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin
site = AdminSite()
class CustomUserAdmin(UserAdmin):
# Remove group editing
fieldsets = UserAdmin.fieldsets[:-1]
def has_delete_permission(self, request, obj=None):
return getattr(settings, 'BACKOFFICE', False)
class CustomFlatPageAdmin(FlatPageAdmin):
list_filter = []
site.register(User, CustomUserAdmin)
site.register(FlatPage, CustomFlatPageAdmin)
示例9: AttendanceAdmin
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
list_filter = ["category_id", "designation"]
inlines = [AttendanceInline]
class AttendanceAdmin(admin.ModelAdmin):
list_display = ("employee_id", "date", "shift", "project")
list_filter = ["employee_id", "date", "project"]
class PaymentAdmin(admin.ModelAdmin):
list_display = ("paid_date", "amount", "paid_details", "project_id")
list_filter = ["project_id", "amount", "paid_date"]
class EmpPaymentAdmin(admin.ModelAdmin):
list_display = ("employee", "amount", "type", "month", "year")
list_filter = ["employee", "month", "year"]
site = AdminSite()
site.site_header = "Omar and Assosciates"
site.register(Project, ProjectAdmin)
site.register(Category)
site.register(Dealer)
site.register(Expense, ExpenseAdmin)
site.register(Employee, EmployeeAdmin)
site.register(Attendance, AttendanceAdmin)
site.register(EmployeePayment, EmpPaymentAdmin)
site.register(Payment, PaymentAdmin)
示例10: AdminSite
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class AdminSite(AdminSite):
site_title = 'FlexInvest Admin'
index_title = 'Home'
branding = "admin/logo.png"
admin_site = AdminSite()
def deactivate_account(modeladmin, request, queryset):
queryset.update(is_active=False)
deactivate_account.short_description = "Deactivate selected users"
def activate_account(modeladmin, request, queryset):
queryset.update(is_active=True)
activate_account.short_description = "Activate selected users"
class UserAdmin(UserAdmin):
list_display = ('username', 'is_active', 'last_login', 'date_joined',)
list_filter = ('groups', 'is_active',)
date_hierarchy = 'date_joined'
actions = [deactivate_account, activate_account]
admin_site.register(User, UserAdmin)
admin_site.register(Permission)
admin_site.register(Group)
admin_site.register(Bond)
admin_site.register(MoneyMarket)
admin_site.register(Residual)
admin_site.register(Trade)
admin_site.register(Cashflow)
示例11: type
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
ct = registered_model.model
DynamicModelAdmin = type(
str("%(site_name)s_%(app_label)s_%(model_name)s_Admin" % dict(
site_name = slug,
app_label = ct.app_label,
model_name = ct.model,
)),
(ModelAdmin,),
dict(
list_display = [
field.name for field in registered_model.list_display.extra(
order_by = [list_display_through+'.id']
)
],
list_filter = [
field.name for field in registered_model.list_filter.all()
],
search_fields = [
field.name for field in registered_model.search_fields.all()
],
raw_id_fields = [
field.name for field in registered_model.raw_id_fields.all()
],
)
)
admin_site.register(
ct.model_class(),
DynamicModelAdmin
)
urlpatterns.append(url('^%s/' % slug, include(admin_site.urls)))
示例12: AdminSite
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.admin import AdminSite
root_site = AdminSite(name='root')
root_site.register(User, UserAdmin)
root_site.register(Group, GroupAdmin)
tenant_site = AdminSite(name='tenant')
tenant_site.register(User, UserAdmin)
tenant_site.register(Group, GroupAdmin)
示例13: AdminTestCase
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class AdminTestCase(TestCase):
"""
Testing the admin site
"""
#: The model to test
model = None
#: The admin class to test
admin_class = None
@classmethod
def setUpClass(cls):
super(AdminTestCase, cls).setUpClass()
cls.admin_user = User.objects.create_superuser('admin', '[email protected]', password='admin')
def setUp(self):
super(AdminTestCase, self).setUp()
# Have a separate site, to avoid dependency on polymorphic wrapping or standard admin configuration
self.admin_site = AdminSite()
if self.model is not None:
self.admin_register(self.model, self.admin_class)
def tearDown(self):
clear_url_caches()
set_urlconf(None)
def register(self, model):
"""Decorator, like admin.register()"""
def _dec(admin_class):
self.admin_register(model, admin_class)
return admin_class
return _dec
def admin_register(self, model, admin_site):
"""Register an model with admin to the test case, test client and URL reversing code."""
self.admin_site.register(model, admin_site)
# Make sure the URLs are reachable by reverse()
clear_url_caches()
set_urlconf(tuple([
url('^tmp-admin/', self.admin_site.urls)
]))
def get_admin_instance(self, model):
try:
return self.admin_site._registry[model]
except KeyError:
raise ValueError("Model not registered with admin: {}".format(model))
@classmethod
def tearDownClass(cls):
super(AdminTestCase, cls).tearDownClass()
clear_url_caches()
set_urlconf(None)
def get_add_url(self, model):
admin_instance = self.get_admin_instance(model)
return reverse(admin_urlname(admin_instance.opts, 'add'))
def get_changelist_url(self, model):
admin_instance = self.get_admin_instance(model)
return reverse(admin_urlname(admin_instance.opts, 'changelist'))
def get_change_url(self, model, object_id):
admin_instance = self.get_admin_instance(model)
return reverse(admin_urlname(admin_instance.opts, 'change'), args=(object_id,))
def get_history_url(self, model, object_id):
admin_instance = self.get_admin_instance(model)
return reverse(admin_urlname(admin_instance.opts, 'history'), args=(object_id,))
def get_delete_url(self, model, object_id):
admin_instance = self.get_admin_instance(model)
return reverse(admin_urlname(admin_instance.opts, 'delete'), args=(object_id,))
def admin_get_add(self, model, qs=''):
"""
Make a direct "add" call to the admin page, circumvening login checks.
"""
admin_instance = self.get_admin_instance(model)
request = self.create_admin_request('get', self.get_add_url(model) + qs)
response = admin_instance.add_view(request)
self.assertEqual(response.status_code, 200)
return response
def admin_post_add(self, model, formdata, qs=''):
"""
Make a direct "add" call to the admin page, circumvening login checks.
"""
admin_instance = self.get_admin_instance(model)
request = self.create_admin_request('post', self.get_add_url(model) + qs, data=formdata)
response = admin_instance.add_view(request)
self.assertFormSuccess(request.path, response)
return response
def admin_get_changelist(self, model):
"""
Make a direct "add" call to the admin page, circumvening login checks.
"""
#.........这里部分代码省略.........
示例14: AdminTest
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class AdminTest(AppTestCase):
"""
Test the admin functions.
"""
def setUp(self):
# Admin objects for all tests.
self.factory = RequestFactory()
self.admin_site = AdminSite()
self.admin_user = User.objects.get(is_superuser=True)
self.settings = override_settings(
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
)
self.settings.enable()
def tearDown(self):
self.settings.disable()
def test_add_page(self):
"""
Test adding an object with placeholder field via the admin.
"""
self.admin_site.register(PlaceholderFieldTestPage, PlaceholderFieldTestPageAdmin)
modeladmin = self.admin_site._registry[PlaceholderFieldTestPage]
# Get all post data.
# Includes all inlines, so all inline formsets of other plugins will be added (with TOTAL_FORMS 0)
contents_slot = PlaceholderFieldTestPage.contents.slot
formdata = self._get_management_form_data(modeladmin)
formdata.update({
'title': 'TEST1',
'placeholder-fs-TOTAL_FORMS': '1',
'placeholder-fs-MAX_NUM_FORMS': '', # Needed for Django <= 1.4.3
'placeholder-fs-INITIAL_FORMS': '0', # Needed for Django 1.3
'placeholder-fs-0-slot': contents_slot,
'placeholder-fs-0-role': Placeholder.MAIN,
'rawhtmltestitem-TOTAL_FORMS': '1',
'rawhtmltestitem-MAX_NUM_FORMS': '',
'rawhtmltestitem-INITIAL_FORMS': '0',
'rawhtmltestitem-0-placeholder': '', # The placeholder is not defined yet, as item is not yet created.
'rawhtmltestitem-0-placeholder_slot': contents_slot, # BaseContentItemFormSet resolves the placeholder after it's created
'rawhtmltestitem-0-sort_order': '1',
'rawhtmltestitem-0-html': u'<b>foo</b>',
})
# Make a POST to the admin page.
response = self._post_add(modeladmin, formdata)
self.assertEqual(response.status_code, 302, "No redirect, received:\n\n{0}".format(self._render_response(response)))
# Check that the page exists.
page = PlaceholderFieldTestPage.objects.get(title='TEST1')
# Check that the placeholder is created,
# and properly links back to it's parent.
placeholder = page.contents
self.assertEqual(placeholder.slot, contents_slot)
self.assertEqual(placeholder.role, Placeholder.MAIN)
self.assertEqual(placeholder.parent, page)
# Check that the ContentItem is created,
# and properly links back to it's parent.
rawhtmltestitem = RawHtmlTestItem.objects.get(html=u'<b>foo</b>')
self.assertEqual(rawhtmltestitem.placeholder, placeholder)
self.assertEqual(rawhtmltestitem.parent, page)
# Also check reverse relation of placeholder
rawhtmltestitem = placeholder.contentitems.all()[0]
self.assertEqual(rawhtmltestitem.html, u'<b>foo</b>')
def _post_add(self, modeladmin, formdata):
opts = modeladmin.opts
url = reverse('admin:{0}_{1}_add'.format(*_get_url_format(opts)))
# Build request
formdata['csrfmiddlewaretoken'] = 'foo'
request = self.factory.post(url, data=formdata)
request.COOKIES[settings.CSRF_COOKIE_NAME] = 'foo'
# Add properties which middleware would typically do
request.session = {}
request.user = self.admin_user
MessageMiddleware().process_request(request)
# Make a direct call, circumvents login page.
return modeladmin.add_view(request)
def _get_management_form_data(self, modeladmin):
"""
Return the formdata that the management forms need.
"""
opts = modeladmin.opts
url = reverse('admin:{0}_{1}_add'.format(*_get_url_format(opts)))
request = self.factory.get(url)
#.........这里部分代码省略.........
示例15: TestPublishSelectedAction
# 需要导入模块: from django.contrib.admin import AdminSite [as 别名]
# 或者: from django.contrib.admin.AdminSite import register [as 别名]
class TestPublishSelectedAction(TestCase):
def setUp(self):
super(TestPublishSelectedAction, self).setUp()
self.fp1 = Page.objects.create(slug='fp1', title='FP1')
self.fp2 = Page.objects.create(slug='fp2', title='FP2')
self.fp3 = Page.objects.create(slug='fp3', title='FP3')
self.admin_site = AdminSite('Test Admin')
self.page_admin = PublishableAdmin(Page, self.admin_site)
# override urls, so reverse works
settings.ROOT_URLCONF = patterns(
'',
('^admin/',
include(self.admin_site.urls)),
)
def test_publish_selected_confirm(self):
pages = Page.objects.exclude(id=self.fp3.id)
class dummy_request(object):
META = {}
POST = {}
class user(object):
@classmethod
def has_perm(cls, *arg):
return True
@classmethod
def get_and_delete_messages(cls):
return []
response = publish_selected(self.page_admin, dummy_request, pages)
self.failIf(Page.objects.published().count() > 0)
self.failUnless(response is not None)
self.failUnlessEqual(200, response.status_code)
def test_publish_selected_confirmed(self):
pages = Page.objects.exclude(id=self.fp3.id)
class dummy_request(object):
POST = {'post': True}
class user(object):
@classmethod
def is_authenticated(cls):
return True
@classmethod
def has_perm(cls, *arg):
return True
class message_set(object):
@classmethod
def create(cls, message=None):
self._message = message
class _messages(object):
@classmethod
def add(cls, *message):
self._message = message
response = publish_selected(self.page_admin, dummy_request, pages)
self.failUnlessEqual(2, Page.objects.published().count())
self.failUnless(getattr(self, '_message', None) is not None)
self.failUnless(response is None)
def test_convert_all_published_to_html(self):
self.admin_site.register(Page, PublishableAdmin)
all_published = NestedSet()
page = Page.objects.create(slug='here', title='title')
block = PageBlock.objects.create(page=page, content='stuff here')
all_published.add(page)
all_published.add(block, parent=page)
converted = _convert_all_published_to_html(self.admin_site,
all_published)
expected = [
u'<a href="../../example_app/page/%d/">Page: here (Changed - '
u'not yet published)</a>' % page.id,
[u'Page block: PageBlock object']]
self.failUnlessEqual(expected, converted)
def test_publish_selected_does_not_have_permission(self):
self.admin_site.register(Page, PublishableAdmin)
pages = Page.objects.exclude(id=self.fp3.id)
class dummy_request(object):
POST = {}
META = {}
class user(object):
#.........这里部分代码省略.........