本文整理汇总了Python中django.contrib.admin.ModelAdmin类的典型用法代码示例。如果您正苦于以下问题:Python ModelAdmin类的具体用法?Python ModelAdmin怎么用?Python ModelAdmin使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModelAdmin类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: response_add
def response_add(self, request, obj, post_url_continue='../../%s/'):
"""Proxy to ensure the post_url_continue default is correct"""
return ModelAdmin.response_add(self, request, obj, post_url_continue)
示例2: test_custom_min_num
def test_custom_min_num(self):
"""
Ensure that get_min_num is called and used correctly.
"""
bt_head = BinaryTree.objects.create(name="Tree Head")
BinaryTree.objects.create(name="First Child", parent=bt_head)
class MinNumInline(TabularInline):
model = BinaryTree
extra = 3
def get_min_num(self, request, obj=None, **kwargs):
if obj:
return 5
return 2
modeladmin = ModelAdmin(BinaryTree, admin_site)
modeladmin.inlines = [MinNumInline]
min_forms = '<input id="id_binarytree_set-MIN_NUM_FORMS" name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="%d" />'
total_forms = '<input id="id_binarytree_set-TOTAL_FORMS" name="binarytree_set-TOTAL_FORMS" type="hidden" value="%d" />'
request = self.factory.get('/admin/admin_inlines/binarytree/add/')
request.user = User(username='super', is_superuser=True)
response = modeladmin.changeform_view(request)
self.assertContains(response, min_forms % 2)
self.assertContains(response, total_forms % 5)
request = self.factory.get("/admin/admin_inlines/binarytree/%d/" % bt_head.id)
request.user = User(username='super', is_superuser=True)
response = modeladmin.changeform_view(request, object_id=str(bt_head.id))
self.assertContains(response, min_forms % 5)
self.assertContains(response, total_forms % 8)
示例3: make_active_brother
def make_active_brother(modeladmin, request, queryset):
group = Group.objects.get(name='Active Brother')
for user in queryset:
user.groups.add(group)
ModelAdmin.message_user(self=modeladmin, request=request,
message='Selected users were added to the '
'Active Brother group')
示例4: test_custom_min_num
def test_custom_min_num(self):
bt_head = BinaryTree.objects.create(name="Tree Head")
BinaryTree.objects.create(name="First Child", parent=bt_head)
class MinNumInline(TabularInline):
model = BinaryTree
extra = 3
def get_min_num(self, request, obj=None, **kwargs):
if obj:
return 5
return 2
modeladmin = ModelAdmin(BinaryTree, admin_site)
modeladmin.inlines = [MinNumInline]
min_forms = (
'<input id="id_binarytree_set-MIN_NUM_FORMS" '
'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="%d">'
)
total_forms = (
'<input id="id_binarytree_set-TOTAL_FORMS" '
'name="binarytree_set-TOTAL_FORMS" type="hidden" value="%d">'
)
request = self.factory.get(reverse('admin:admin_inlines_binarytree_add'))
request.user = User(username='super', is_superuser=True)
response = modeladmin.changeform_view(request)
self.assertInHTML(min_forms % 2, response.rendered_content)
self.assertInHTML(total_forms % 5, response.rendered_content)
request = self.factory.get(reverse('admin:admin_inlines_binarytree_change', args=(bt_head.id,)))
request.user = User(username='super', is_superuser=True)
response = modeladmin.changeform_view(request, object_id=str(bt_head.id))
self.assertInHTML(min_forms % 5, response.rendered_content)
self.assertInHTML(total_forms % 8, response.rendered_content)
示例5: test_choice_links
def test_choice_links(self):
modeladmin = ModelAdmin(Question, site)
modeladmin.date_hierarchy = 'posted'
posted_dates = (
datetime.date(2017, 10, 1),
datetime.date(2017, 10, 1),
datetime.date(2017, 12, 15),
datetime.date(2017, 12, 15),
datetime.date(2017, 12, 31),
datetime.date(2018, 2, 1),
)
Question.objects.bulk_create(Question(question='q', posted=posted) for posted in posted_dates)
tests = (
({}, [['year=2017'], ['year=2018']]),
({'year': 2016}, []),
({'year': 2017}, [['month=10', 'year=2017'], ['month=12', 'year=2017']]),
({'year': 2017, 'month': 9}, []),
({'year': 2017, 'month': 12}, [['day=15', 'month=12', 'year=2017'], ['day=31', 'month=12', 'year=2017']]),
)
for query, expected_choices in tests:
with self.subTest(query=query):
query = {'posted__%s' % q: val for q, val in query.items()}
request = self.factory.get('/', query)
changelist = modeladmin.get_changelist_instance(request)
spec = date_hierarchy(changelist)
choices = [choice['link'] for choice in spec['choices']]
expected_choices = [
'&'.join('posted__%s' % c for c in choice) for choice in expected_choices
]
expected_choices = [('?' + choice) if choice else '' for choice in expected_choices]
self.assertEqual(choices, expected_choices)
示例6: test_min_num
def test_min_num(self):
"""
Ensure that min_num and extra determine number of forms.
"""
class MinNumInline(TabularInline):
model = BinaryTree
min_num = 2
extra = 3
modeladmin = ModelAdmin(BinaryTree, admin_site)
modeladmin.inlines = [MinNumInline]
min_forms = (
'<input id="id_binarytree_set-MIN_NUM_FORMS" name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="2" />'
)
total_forms = (
'<input id="id_binarytree_set-TOTAL_FORMS" name="binarytree_set-TOTAL_FORMS" type="hidden" value="5" />'
)
request = self.factory.get(reverse("admin:admin_inlines_binarytree_add"))
request.user = User(username="super", is_superuser=True)
response = modeladmin.changeform_view(request)
self.assertContains(response, min_forms)
self.assertContains(response, total_forms)
示例7: unpublish_page
def unpublish_page(modeladmin: admin.ModelAdmin, request: HttpRequest, queryset: QuerySet):
pages_updated = queryset.update(published=False)
if pages_updated == 1:
message = '1 page was'
else:
message = '{:d} page were'.format(pages_updated)
modeladmin.message_user(request, '{:s} successfully marked as published.'.format(message))
示例8: test_admin_forms
def test_admin_forms(self):
site = AdminSite()
model_admin = ModelAdmin(IntModel, site)
form_clazz = model_admin.get_form(None)
form_instance = form_clazz()
try:
form_instance.as_table()
except TypeError:
self.fail('HTML Rendering of the form caused a TypeError')
示例9: app_settings
def app_settings(self, request, app_name):
model_classes = registered_settings.get(app_name)
if not model_classes:
raise Http404
forms = []
fieldsets = []
model_admin = ModelAdmin(Root, self)
for model_name, model in model_classes.items():
instance = getattr(settings, '%s_%s' % (app_name, model_name))
model_admin = self.registered_settings.get(model)
if not model_admin:
model_admin = ModelAdmin(model, self)
form_class = model_admin.get_form(request, instance)
form = form_class(
prefix=model_name,
data=request.POST or None,
instance=instance
)
forms.append(form)
meta = getattr(model, '_meta')
name = '%s %s' % (app_name.title(), meta.verbose_name)
readonly_fields = model_admin.readonly_fields
fields = list(form.fields.keys()) + list(readonly_fields)
fs = Fieldset(form, name, readonly_fields, fields)
fieldsets.append(fs)
# list comprehension to evaluate all forms
if all([form.is_valid() for form in forms]):
for form in forms:
form.save()
msg = '%s settings have been saved.' % app_name.title()
messages.info(request, msg)
if '_save' in request.POST:
url = reverse('admin:settings', current_app=self.name)
return redirect(url)
return redirect(request.get_full_path())
context = {
'app_name': app_name.title(),
'forms': forms,
'fieldsets': fieldsets,
'opts': FakeOpts(),
'change': True,
'is_popup': False,
'save_as': False,
'has_add_permission': False,
'has_delete_permission': False,
'has_change_permission': True,
'media': model_admin.media,
}
return TemplateResponse(
request,
'admin/dbsettings/app_settings.html',
context,
current_app=self.name
)
示例10: lookup_allowed
def lookup_allowed(self, lookup, value):
# overriden to allow filter on cell_filter fields
# import django.contrib.admin.options
# django.contrib.admin.options.QUERY_TERMS.update({'not':'not'})
original = DjangoModelAdmin.lookup_allowed(self, lookup, value)
if original:
return True
model = self.model
parts = lookup.split(LOOKUP_SEP)
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
pk_attr_name = None
for part in parts[:-1]:
field, _, _, _ = model._meta.get_field_by_name(part)
if hasattr(field, 'rel'):
model = field.rel.to
pk_attr_name = model._meta.pk.name
elif isinstance(field, RelatedObject):
model = field.model
pk_attr_name = model._meta.pk.name
else:
pk_attr_name = None
if pk_attr_name and len(parts) > 1 and parts[-1] == pk_attr_name:
parts.pop()
clean_lookup = LOOKUP_SEP.join(parts)
flat_filter = [isinstance(v, tuple) and v[0] or v for v in self.list_filter]
flat_filter.extend([isinstance(v, tuple) and v[0] or v for v in self.cell_filter])
return clean_lookup in self.extra_allowed_filter or clean_lookup in flat_filter
示例11: __call__
def __call__(self, request, url):
if url is not None:
import re
matches = re.match('^add/(\d+)$',url)
if matches:
return self.add_view(request, option_type=matches.groups()[0])
return ModelAdmin.__call__(self, request, url)
示例12: get_form
def get_form(self, request, obj=None, **kwargs):
if request.method == 'POST' and obj is None:
try:
request.POST['dispatcher'] = Dispatcher.objects.get(name__iexact=u' '.join((request.user.last_name, request.user.first_name)))
except:
pass
return ModelAdmin.get_form(self, request, obj=obj, **kwargs)
示例13: changelist_view
def changelist_view(self, request, extra_context=None):
if extra_context is None:
extra_context = {}
extra_context['menu_option_types'] = MenuOption.MODEL_TYPE_CHOICES
extra_context['app_label'] = _("GDT Nav")
extra_context['menu_groups'] = MenuGroup.objects.order_by('name')
return ModelAdmin.changelist_view(self, request, extra_context)
示例14: merge
def merge(modeladmin, request, queryset):
main = queryset[0]
tail = queryset[1:]
related = main._meta.get_all_related_objects()
valnames = dict()
for r in related:
valnames.setdefault(r.related_model, []).append(r.field.name)
manyrelated = main._meta.get_all_related_many_to_many_objects()
manyvalnames = dict()
for r in manyrelated:
manyvalnames.setdefault(r.related_model, []).append(r.field.name)
for place in tail:
for model, field_names in valnames.items():
for field_name in field_names:
model.objects.filter(**{field_name: place}).update(**{field_name: main})
for model, field_names in manyvalnames.items():
for field_name in field_names:
for manytomany in model.objects.filter(**{field_name: place}):
manyfield = getattr(manytomany, field_name) # gets attribute from string
manyfield.remove(place)
manyfield.add(main)
place.delete()
# merge all TeamsOnTournament on same Tournament for this Team
modelname = modeladmin.__class__.__name__
if modelname is 'TeamAdmin':
tours = []
team = Team.objects.get(name=main)
totm = TeamOnTournament.objects.filter(team=team)
for tour in totm:
if tour.tournament not in tours:
tours.append(tour.tournament)
for tour in tours:
totm = TeamOnTournament.objects.filter(team=team).filter(tournament=tour)
if len(totm) > 1:
for instance in totm[1:]:
for player in instance.players.all():
totm[0].players.add(player)
instance.delete()
ModelAdmin.message_user(modeladmin, request, 'sloučeno, v objektu můžete zvolit výsledné jméno')
示例15: edit
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)