def test_custom_lookup_with_pk_shortcut(self): self.assertEqual(CharPK._meta.pk.name, 'char_pk') # Not equal to 'pk'. m = admin.ModelAdmin(CustomIdUser, custom_site) abc = CharPK.objects.create(char_pk='abc') abcd = CharPK.objects.create(char_pk='abcd') m = admin.ModelAdmin(CharPK, custom_site) m.search_fields = ['pk__exact'] request = self.factory.get('/', data={SEARCH_VAR: 'abc'}) cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abc]) request = self.factory.get('/', data={SEARCH_VAR: 'abcd'}) cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abcd])
def setUp(self): self.author = Author.objects.create() self.categories = ( Category.objects.create(), Category.objects.create(), Category.objects.create(), ) self.articles = ( Article(author=self.author), Article(author=self.author, category=self.categories[1]), Article(author=self.author, category=self.categories[2]), ) self.categories[1].delete() self.request_factory = RequestFactory() self.request = self.request_factory.get('/', {}) self.modeladmin_default = admin.ModelAdmin(Category, AdminSite()) self.modeladmin = CategoryAdmin(Category, AdminSite()) User.objects.create_superuser('super', '*****@*****.**', 'secret') self.client.login(username='******', password='******')
def test_model_admin_field(self): # borrows from regressiontests/admin_widgets/tests.py from django.contrib import admin ma = admin.ModelAdmin(Post, admin.site) self.assert_( isinstance( ma.formfield_for_dbfield(Post._meta.get_field('body')).widget, AdminMarkupTextareaWidget))
def setUp(self): self.modeladmin = admin.ModelAdmin(UserAttendance, "") self.factory = RequestFactory() self.request = self.factory.get("") self.request.subdomain = "testing-campaign" setattr(self.request, "session", "session") self.messages = FallbackStorage(self.request) setattr(self.request, "_messages", self.messages)
def test_admin_rendering(self): ma = admin.ModelAdmin(TestModel, self.site) obj = TestModel(phone='415 123 4567 x 88') Form = ma.get_form(self.request) f = Form(instance=obj) expected = '<tr><th><label for="id_phone_0">Phone:</label></th><td><input type="text" name="phone_0" ' \ 'value="(415) 123-4567" size="13" required id="id_phone_0" />\n\n ext. ' \ '<input type="text" name="phone_1" value="88" size="4" id="id_phone_1" /></td></tr>' self.assertEqual(str(f), expected)
def test_admin_rendering(self): ma = admin.ModelAdmin(TestModel, self.site) obj = TestModel(phone='415 123 4567 x 88') Form = ma.get_form(self.request, fields=['phone']) f = Form(instance=obj) self.assertEqual( str(f), _rendered_field_html(phone_number='(415) 123-4567', extension='88', required=True))
def setUp(self): self.modeladmin = admin.ModelAdmin(models.UserAttendance, "") self.factory = RequestFactory() self.request = self.factory.get("") self.request.subdomain = "testing-campaign" self.request.user = models.User.objects.get(username="******") setattr(self.request, 'session', 'session') self.messages = FallbackStorage(self.request) setattr(self.request, '_messages', self.messages) call_command('denorm_init') util.rebuild_denorm_models(models.Team.objects.filter(pk=1))
def setUp(self): self.thumbnail_image = ThumbnailImage() self.site = AdminSite() self.ma = admin.ModelAdmin(ThumbnailImage, self.site) self.thumb = ThumbnailImage.objects.create( thumbnail_image=SimpleUploadedFile( name='test_thumb_delete_me.png', content=open(test_img, 'rb').read(), content_type='image/png', )) self.thumb.save()
def get_filters(self): params = dict(self.request.GET.items()) opts = self.model._meta use_distinct = False list_filters = self.get_list_filters() new_params = {} has_filters = False # Normalize the types of keys list_names = [f if isinstance(f, str) else f.parameter_name for f in list_filters] for key, value in params.items(): # ignore keys not in list_filters if key.startswith(tuple(list_names)): new_params[force_str(key)] = value has_filters = bool(new_params) filter_specs = [] for list_filter in list_filters: if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(self.request, new_params, self.model, None) else: field_path = None if isinstance(list_filter, (tuple, list)): # Custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # Field name, so use the default registered FieldListFilter field, field_list_filter_class = list_filter, FieldListFilter.create if not isinstance(field, models.Field): field_path = field field = get_fields_from_path(self.model, field_path)[-1] model_admin = admin.ModelAdmin(self.model, admin.site) spec = field_list_filter_class(field, self.request, new_params, self.model, model_admin, field_path=field_path) # Check if we need to use distinct() use_distinct = (use_distinct or lookup_needs_distinct(opts, field_path)) if spec and spec.has_output(): filter_specs.append(spec) # All the parameters used by the various ListFilters have been removed # lookup_params, now only contains other parameters passed via the query string. # We now loop through the remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them needs distinct(). If # the lookup parameters aren't real fields, then bail out. try: for key, value in new_params.items(): new_params[key] = prepare_lookup_value(key, value) use_distinct = (use_distinct or lookup_needs_distinct(opts, key)) return filter_specs, has_filters, use_distinct except FieldDoesNotExist as e: raise IncorrectLookupParameters from e
def setUp(self): self.modeladmin = admin.ModelAdmin(models.UserAttendance, "") self.factory = RequestFactory() self.request = self.factory.get("") self.request.subdomain = "testing-campaign" self.request.user = mommy.make( "auth.User", username="******", is_staff=True, is_superuser=True, ) setattr(self.request, 'session', 'session') self.messages = FallbackStorage(self.request) setattr(self.request, '_messages', self.messages)
def test_extra_param(self): """ With extra=0, there should be one form. """ class ExtraInline(GenericTabularInline): model = Media extra = 0 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [ExtraInline] e = self._create_object(Episode) request = self.factory.get('/generic_inline_admin/admin/generic_inline_admin/episode/%s/' % e.pk) request.user = User(username='******', is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data['inline_admin_formsets'][0].formset self.assertEqual(formset.total_form_count(), 1) self.assertEqual(formset.initial_form_count(), 1)
def test_get_max_num(self): class GetMaxNumInline(GenericTabularInline): model = Media extra = 5 def get_max_num(self, request, obj): return 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [GetMaxNumInline] e = self._create_object(Episode) request = self.factory.get('/generic_inline_admin/admin/generic_inline_admin/episode/%s/' % e.pk) request.user = User(username='******', is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data['inline_admin_formsets'][0].formset self.assertEqual(formset.max_num, 2)
def test_get_extra(self): class GetExtraInline(GenericTabularInline): model = Media extra = 4 def get_extra(self, request, obj): return 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [GetExtraInline] e = self._create_object(Episode) request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,))) request.user = User(username='******', is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data['inline_admin_formsets'][0].formset self.assertEqual(formset.extra, 2)
def setUp(self): self.factory = RequestFactory() self.site = AdminSite() self.ma = admin.ModelAdmin(Theme, self.site) self.t1 = Theme.objects.create( name="Test1", description="Test Description", default_theme=True, active_theme=True, title="Test Title", tagline="Test Tagline", running_hex="ffffff", running_text_hex="ffffff", running_link_hex="ffffff", pb_text="Test Powered By Text", pb_link="http://boundlessgeo.com/", docs_text="Documentation", docs_link="/static/docs/html/index.html", background_logo="theme/img/default-background.png", primary_logo="theme/img/default-primary-logo.png", banner_logo="theme/img/default-banner-logo.png" ) self.t1.save() self.t2 = Theme.objects.create( name="Test2", description="Test Description", default_theme=False, active_theme=True, title="Test Title", tagline="Test Tagline", running_hex="ffffff", running_text_hex="ffffff", running_link_hex="ffffff", pb_text="Test Powered By Text", pb_link="http://boundlessgeo.com/", docs_text="Documentation", docs_link="https://boundlessgeo.github.io/" "exchange-documentation/", background_logo=None, primary_logo=None, banner_logo=None ) self.t2.save()
def test_min_num_param(self): """ With extra=3 and min_num=2, there should be five forms. """ class MinNumInline(GenericTabularInline): model = Media extra = 3 min_num = 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [MinNumInline] e = self._create_object(Episode) request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,))) request.user = User(username='******', is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data['inline_admin_formsets'][0].formset self.assertEqual(formset.total_form_count(), 5) self.assertEqual(formset.initial_form_count(), 1)
def test_get_min_num(self): class GetMinNumInline(GenericTabularInline): model = Media min_num = 5 def get_min_num(self, request, obj): return 2 modeladmin = admin.ModelAdmin(Episode, admin_site) modeladmin.inlines = [GetMinNumInline] e = self._create_object(Episode) request = self.factory.get( reverse("admin:generic_inline_admin_episode_change", args=(e.pk, ))) request.user = User(username="******", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(e.pk)) formset = response.context_data["inline_admin_formsets"][0].formset self.assertEqual(formset.min_num, 2)
def setUp(self): self.author = Author.objects.create(name='author 0') self.categories = ( Category.objects.create(name='category 0'), Category.objects.create(name='category 1'), Category.objects.create(name='category 2'), ) self.articles = ( Article(name='article 0', author=self.author), Article(name='article 1', author=self.author, category=self.categories[1]), Article(name='article 2', author=self.author, category=self.categories[2]), ) self.categories[1].delete() self.request_factory = RequestFactory() self.request = self.request_factory.get('/', {}) self.modeladmin_default = admin.ModelAdmin(Category, AdminSite()) self.modeladmin = CategoryAdmin(Category, AdminSite()) User.objects.create_superuser("super", "", "secret") self.client.login(username="******", password="******")
def setUp(self): self.objs = Fixtures({ "userattendances", "campaigns", "payments", "phases", "price_levels", "teams", "invoices", "trips", "company_admins", "competitions", }) self.modeladmin = admin.ModelAdmin(models.UserAttendance, "") self.factory = RequestFactory() self.request = self.factory.get("") self.request.subdomain = "testing-campaign" self.request.user = self.objs.users.user setattr(self.request, "session", "session") self.messages = FallbackStorage(self.request) setattr(self.request, "_messages", self.messages) call_command("denorm_init") util.rebuild_denorm_models([self.objs.teams.basic])
def add_access_token_view(request): """ View for adding an an access token. Requires superuser access. """ if not settings.ENABLE_ADMIN_ADD_ACCESS_TOKEN_VIEW: raise Http404() if not request.user.is_superuser: raise PermissionDenied() is_post = request.method == 'POST' initial = {'adviser': request.user} data = request.POST if is_post else None form = AddAccessTokenForm(initial=initial, data=data) if is_post and form.is_valid(): token, timeout_hours = form.save() message = format_html(SUCCESS_MESSAGE_TEMPLATE, token=token, timeout_hours=timeout_hours) django_messages.add_message(request, django_messages.SUCCESS, message) admin_index = reverse('admin:index') return HttpResponseRedirect(admin_index) template_name = 'admin/oauth/add_access_token.html' # The only way to get the standard list of media files is via a ModelAdmin, # so, unfortunately, we have to create one here to get needed .js files loaded model_admin = admin.ModelAdmin(Advisor, site) context = { 'form': form, 'media': model_admin.media, 'title': gettext('Add access token'), } return TemplateResponse(request, template_name, context)
def testAdminFormField(self): ma = admin.ModelAdmin(Post, admin.site) self.assertEqual( ma.formfield_for_dbfield(Post._meta.get_field('body'), request=None).widget.__class__, AdminMarkItUpWidget)
def setup(self): self.modeladmin = admin.ModelAdmin(DummyModel, admin.site) DummyModel.objects.create(name='Foo', slug='foo', email='*****@*****.**')
def testAdminFormField(self): ma = admin.ModelAdmin(Post, admin.site) self.assertEquals( ma.formfield_for_dbfield( Post._meta.get_field('body')).widget.__class__, AdminMarkupTextareaWidget)
def get_form_class(self): if 'admin' in self.request.META.get('HTTP_REFERER'): self.form_class = (site._registry.get(self.model) or admin.ModelAdmin(self.model, site)).get_form( self.request) return super().get_form_class()
def test_htmlfield(self): ma = admin.ModelAdmin(TestModel, self.site) self.assertIsInstance( ma.get_form(None).base_fields['foobar'].widget, AdminTinyMCE)