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)
def disprove_tutorial_comment_action(modeladmin: ModelAdmin, request: HttpRequest, queryset: QuerySet): # After update update_queryset becomes empty because of applied exclusion # thus, we store update item primary keys in update_item_pks t use later update_queryset = queryset.exclude( confirm_status=ConfirmStatusChoices.DISPROVED).filter(is_active=True) update_item_pks = [comment.pk for comment in update_queryset] updated_count = update_queryset.update( confirm_status=ConfirmStatusChoices.DISPROVED) # Execute new query to get updated objects for notification send_mail_queryset = queryset.filter( pk__in=update_item_pks).select_related("user", "tutorial") # Send notifications confirm_disprove_notifier_result = TutorialCommentConfirmDisproveNotifier( request, send_mail_queryset).notify() modeladmin.message_user(request, f"{updated_count} مورد با موفقیت رد شد", messages.SUCCESS) message_user_email_results(request, modeladmin, confirm_disprove_notifier_result)
class AdminTests(base.TestCase): def setUp(self): self.site = AdminSite() self.model_admin = ModelAdmin(self.models.Links, self.site) self.links = self.models.Links.objects.create() def test_formfield_warning(self): with self.assertRaises(FutureWarning), warnings.catch_warnings(): warnings.filterwarnings('error', category=FutureWarning) self.model_admin.get_form(MockRequest(), self.links)() def test_admin(self): form = self.model_admin.get_form(MockRequest(), self.links)(instance=self.links, data={ 'related_objects': '' }) self.assertTrue(form.is_valid()) def test_submit_form(self): self.links.related_objects = [ self.models.Project.objects.create(), self.models.Task.objects.create() ] form = self.model_admin.get_form(MockRequest(), self.links)(instance=self.links, data={ 'related_objects': '' }) form.save() self.assertEqual(self.links.related_objects.all().count(), 2)
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="******", is_superuser=True) response = modeladmin.changeform_view(request) self.assertContains(response, min_forms) self.assertContains(response, total_forms)
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='******', 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='******', 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)
def deactivate(modeladmin: admin.ModelAdmin, request: WSGIRequest, queryset: QuerySet): queryset.update(active=False) model = queryset.model model.objects.disconnect(model.signal, model.receiver, model) modeladmin.message_user(request, _('Total deactivated: %s' % queryset.count()))
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='******', 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='******', 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)
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')
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='******', 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='******', 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)
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)
def unlink_from_gsuite_action(modeladmin: ModelAdmin, request: HttpRequest, queryset: QuerySet) -> None: """ Unlink Users from GSuite """ count, _ = GoogleAssociation.objects.filter( user__alumni__in=queryset).delete() modeladmin.message_user( request, 'Unlinked {} user(s) from their GSuite Account(s). '.format(count))
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) request.user = self.superuser 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)
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))
def delete_expired_coupons(modeladmin, request, queryset): count = 0 for coupon in queryset: expiration_date = coupon.ruleset.validity.expiration_date if timezone.now() >= expiration_date: coupon.delete() count += 1 ModelAdmin.message_user(modeladmin, request, "{0} Expired coupons deleted!".format(count))
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')
def swap(model_admin: admin.ModelAdmin, request, queryset: QuerySet): if queryset.count() != 2: model_admin.message_user(request, _('Swapped can be only directly two matches.'), level=messages.ERROR) return first, second = queryset # type: Match, Match first.match_term, second.match_term = second.match_term, first.match_term first.save(update_fields=['match_term', ]) second.save(update_fields=['match_term', ]) model_admin.message_user(request, _('Successfully swapped.'), level=messages.SUCCESS)
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 )
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) request.user = self.superuser 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)
def test_choice_links_datetime(self): modeladmin = ModelAdmin(Question, site) modeladmin.date_hierarchy = 'expires' Question.objects.bulk_create([ Question(question='q1', expires=datetime.datetime(2017, 10, 1)), Question(question='q2', expires=datetime.datetime(2017, 10, 1)), Question(question='q3', expires=datetime.datetime(2017, 12, 15)), Question(question='q4', expires=datetime.datetime(2017, 12, 15)), Question(question='q5', expires=datetime.datetime(2017, 12, 31)), Question(question='q6', expires=datetime.datetime(2018, 2, 1)), ]) 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 = {'expires__%s' % q: val for q, val in query.items()} request = self.factory.get('/', query) request.user = self.superuser changelist = modeladmin.get_changelist_instance(request) spec = date_hierarchy(changelist) choices = [choice['link'] for choice in spec['choices']] expected_choices = [ '?' + '&'.join('expires__%s' % c for c in choice) for choice in expected_choices ] self.assertEqual(choices, expected_choices)
def test_choice_links_datetime(self): modeladmin = ModelAdmin(Question, site) modeladmin.date_hierarchy = "expires" Question.objects.bulk_create([ Question(question="q1", expires=datetime.datetime(2017, 10, 1)), Question(question="q2", expires=datetime.datetime(2017, 10, 1)), Question(question="q3", expires=datetime.datetime(2017, 12, 15)), Question(question="q4", expires=datetime.datetime(2017, 12, 15)), Question(question="q5", expires=datetime.datetime(2017, 12, 31)), Question(question="q6", expires=datetime.datetime(2018, 2, 1)), ]) 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 = {"expires__%s" % q: val for q, val in query.items()} request = self.factory.get("/", query) request.user = self.superuser changelist = modeladmin.get_changelist_instance(request) spec = date_hierarchy(changelist) choices = [choice["link"] for choice in spec["choices"]] expected_choices = [ "?" + "&".join("expires__%s" % c for c in choice) for choice in expected_choices ] self.assertEqual(choices, expected_choices)
def reset_coupon_usage(modeladmin, request, queryset): to_update = [] for coupon_user in queryset: if coupon_user.times_used > 0: coupon_user.times_used = 0 to_update.append(coupon_user) CouponUser.objects.bulk_update(to_update, fields=['times_used'], batch_size=500) ModelAdmin.message_user(modeladmin, request, "Coupons reseted!")
def _show_message(model_admin: ModelAdmin, request: HttpRequest, n: int, message: str, error: str) -> None: if n == 0: model_admin.message_user(request, error, messages.ERROR) else: model_admin.message_user( request, message % { "count": n, "items": model_ngettext(model_admin.opts, n) }, messages.SUCCESS, )
def test_get_actions_raw(self): """Directly tests the get_actions()-method""" factory = RequestFactory() request = factory.get(reverse('admin:miniuser_miniuser_changelist')) ma = MiniUserAdmin(MiniUser, self.site) modeladmin = ModelAdmin(MiniUser, self.site) actions = modeladmin.get_actions(request) self.assertIn('delete_selected', actions) actions = ma.get_actions(request) self.assertNotIn('delete_selected', actions)
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)
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
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)
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)
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')
def link_to_gsuite_action(modeladmin: ModelAdmin, request: HttpRequest, queryset: QuerySet) -> None: """ Link to GSuite links users to a GSuite Account """ profiles = get_user_model().objects.filter(alumni__in=queryset) link_gsuite_users(profiles, False, on_message=lambda x: modeladmin.message_user(request, x))
def message_user_email_results( request: HttpRequest, modeladmin: ModelAdmin, notifications_result: NotificationResult, ): if notifications_result.success: successful_notifications_msg = ( f"{notifications_result.success} اطلاعیه با موفقیت ارسال شد") modeladmin.message_user(request, successful_notifications_msg, messages.SUCCESS) if notifications_result.failed: failed_notifications_msg = ( f"ارسال {notifications_result.failed} اطلاعیه با خطا مواجه شد") modeladmin.message_user(request, failed_notifications_msg, messages.ERROR)
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)
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): opts = self.model._meta target_template = None if add and self.add_form_template is None: target_template = 'add_form_template' elif self.change_form_template is None: target_template = 'change_form_template' if target_template: setattr(self, target_template, self.get_template(request, 'change_form.html')) return DjangoModelAdmin.render_change_form(self, request, context, add, change, form_url, obj)
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('/admin/admin_inlines/binarytree/add/') request.user = User(username='******', is_superuser=True) response = modeladmin.changeform_view(request) self.assertContains(response, min_forms) self.assertContains(response, total_forms)
class MergeSchoolForm(forms.ModelForm): add_to_merge = forms.ModelChoiceField(School.objects.all(), required=False, label=_("Add to merge"), widget=ForeignKeyRawIdWidget(Contestant._meta.get_field('school').remote_field, site)) class Meta: model = School fields = ('name', 'uai', 'acronym', 'type', 'academy', 'address', 'postal_code', 'city', 'country', 'lat', 'lng', 'approved', 'imported') # hack to include the JS for ForeignKeyRawIdWidget media = ModelAdmin(School, site).media
def confirm_tutorial_comment_action( modeladmin: ModelAdmin, request: HttpRequest, queryset: QuerySet[TutorialComment], ): # After update update_queryset becomes empty because of applied exclusion # then we store update item primary keys in update_item_pks t use later update_queryset = queryset.exclude( confirm_status=ConfirmStatusChoices.CONFIRMED).filter(is_active=True) update_item_pks = [comment.pk for comment in update_queryset] updated_count = update_queryset.update( confirm_status=ConfirmStatusChoices.CONFIRMED) # Execute new query to get updated objects for notification send_mail_queryset = queryset.filter( pk__in=update_item_pks).select_related("user", "tutorial", "parent_comment", "parent_comment__user") # Send notifications confirm_disprove_notifier_result = TutorialCommentConfirmDisproveNotifier( request, send_mail_queryset).notify() reply_notifier_result = TutorialCommentReplyNotifier( request, send_mail_queryset).notify() tutorial_author_new_comment_notifier_result = ( TutorialAuthorNewConfirmedCommentNotifier(request, send_mail_queryset).notify()) emails_result = (confirm_disprove_notifier_result + reply_notifier_result + tutorial_author_new_comment_notifier_result) # Send messages confirm_msg = f"{updated_count} مورد با موفقیت تایید شد" modeladmin.message_user(request, confirm_msg, messages.SUCCESS) message_user_email_results(request, modeladmin, emails_result)
def disprove_tutorial_action(modeladmin: ModelAdmin, request: HttpRequest, queryset: QuerySet): update_queryset = queryset.exclude( confirm_status=ConfirmStatusChoices.DISPROVED).filter(is_active=True) update_item_pks = [tutorial.pk for tutorial in update_queryset] updated = update_queryset.update( confirm_status=ConfirmStatusChoices.DISPROVED) # Execute new query to get updated objects for notification send_mail_queryset = queryset.filter( pk__in=update_item_pks).select_related("author") # Send notifications notifier = TutorialConfirmDisproveNotifier(request, send_mail_queryset) notify_result = notifier.notify() modeladmin.message_user(request, f"{updated} مورد با موفقیت رد شد", messages.SUCCESS) message_user_email_results(request, modeladmin, notify_result)
def changelist_view(self, request, extra_context=None): try: action = self.get_actions(request)[request.POST['action']][0] action_acts_on_all = action.acts_on_all except (KeyError, AttributeError): action_acts_on_all = False if action_acts_on_all: post = request.POST.copy() post.setlist(helpers.ACTION_CHECKBOX_NAME, self.model.objects.values_list('pk', flat=True)) request.POST = post return ModelAdmin.changelist_view(self, request, extra_context)
def test_min_num(self): """ 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='******', is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms, response.rendered_content) self.assertInHTML(total_forms, response.rendered_content)
def get_form(self, request, obj=None, **kwargs): """ Push request into the ModelForm. Requires the form to override __init__ and remove request from the kwargs. See: http://stackoverflow.com/questions/1057252/how-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clean-met """ ModelForm = ModelAdmin.get_form(self, request, obj, **kwargs) class ModelFormWithRequestWrapper(ModelForm): """class wrapping actual model form class to capture request""" def __new__(cls, *args, **kwargs): kwargs['request'] = request return ModelForm(*args, **kwargs) return ModelFormWithRequestWrapper
def test_no_raw_delete(self): """ Raw delete wasn't preventing the deletion of corresponding DB entries, so `reset_attempts` was introduced. """ request_mock = Mock(GET={}) original_django_actions = ModelAdmin.get_actions( self.admin, request_mock) actions = self.admin.get_actions(request_mock) self.assertIn('delete_selected', original_django_actions, 'Just making sure we are testing correctly') self.assertNotIn('delete_selected', actions, msg='Should be removed') self.assertIn('reset_attempts', actions, 'Use `reset_attempts` custom action')
def get_urls(self): from django.conf.urls.defaults import patterns, url urlpatterns = ModelAdmin.get_urls(self) def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = (self.model._meta.app_label, self.model._meta.module_name ) urlpatterns = patterns('', url(r'^add/(?P<option_type>\d)/$', wrap(self.add_view), name='%s_%s_add_by_type' % info), ) + urlpatterns return urlpatterns
def has_delete_permission(self, request, obj=None): """ Returns True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* object of the given type. """ r = ModelAdmin.has_delete_permission(self, request, obj) if obj and r: r = self.is_authorized(request.user, obj) return r
def log_changes(request, obj_start, obj_end, add=True): obj_changes = u'' modeladmin = ModelAdmin(User, ModelAdmin) if add: obj_changes = u'Objeto adicionado' modeladmin.log_addition(request, obj_end) else: obj_changes = diff_changes_model(obj_start, obj_end) modeladmin.log_change(request, obj_end, {'changed': obj_changes}) return obj_changes
def delete_view(self, request, object_id, extra_context=None): "The 'delete' admin view for this model." blocked = [] blocked_related = [] obj = self.model.objects.get(id=object_id) if not self.is_authorized(request.user, obj): blocked = [ obj ] if not blocked: blocked_related = self.related_not_authorized(request.user, [obj]) if not blocked_related: ## let default Admin delete_view handle all other cases return ModelAdmin.delete_view(self, request, object_id, extra_context=extra_context) return self.delete_blocked_response(request, [obj], blocked, blocked_related, template='delete_blocked.html')
def changelist_view(self, request, extra_context=None): response = ModelAdmin.changelist_view(self, request, extra_context=extra_context) queryset = response.context_data['cl'].get_query_set(request) queryset_len = queryset.count() if queryset_len == 0: response.context_data['person'] = None else: if request.GET.has_key('q'): try: response.context_data['person'] = Person.objects.get(name__icontains=request.GET['q']) except: response.context_data['person'] = None else: min_date = queryset.aggregate(Min('date'))['date__min'] max_date = queryset.aggregate(Max('date'))['date__max'] start_debt = Debt.objects.filter(person=response.context_data['person'], date__lt=min_date).aggregate(Sum('total'))['total__sum'] or 0.0 final_debt = Debt.objects.filter(person=response.context_data['person'], date__lte=max_date).aggregate(Sum('total'))['total__sum'] or 0.0 response.context_data['start_debt'] = start_debt response.context_data['final_debt'] = final_debt response.context_data['period_debt'] = final_debt - start_debt return response
def formfield_for_dbfield(self, db_field, **kwargs): ret = DjangoModelAdmin.formfield_for_dbfield(self, db_field, **kwargs) if ret and isinstance(ret.widget, widgets.RelatedFieldWidgetWrapper): ret.widget.__class__ = IRelatedFieldWidgetWrapper return ret
def __init__(self, model, admin_site): self.extra_allowed_filter = [] self.full_list_display = self.list_display DjangoModelAdmin.__init__(self, model, admin_site) self._process_cell_filter()
def formfield_for_dbfield(self, db_field, **kwargs): if isinstance(db_field, models.FileField): return self.formfield_for_file_field(db_field, kwargs.pop("request", None), **kwargs) return ModelAdmin.formfield_for_dbfield(self, db_field, **kwargs)
def validate(cls, model): if issubclass(model, models.Model): ModelAdmin.check(model) else: _validate(cls, model)
def add_view(self, request, form_url='', extra_context=None): context = self.get_context_data(**(extra_context or {} )) return DjangoModelAdmin.add_view(self, request, form_url, context)
def get_action_choices(self, request, default_choices=[]): return ModelAdmin.get_action_choices(self, request, default_choices=default_choices)
def delete_statistics(modeladmin: admin.ModelAdmin, request: HttpRequest, queryset: QuerySet): for l in queryset: HitModel.objects.filter(for_link=l).delete() modeladmin.message_user(request, 'Statistics deleted')
def test_min_num(self): """ 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='******', is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms, response.rendered_content) self.assertInHTML(total_forms, response.rendered_content)