django / tests / regressiontests / admin_widgets / tests.py

The default branch has multiple heads

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# encoding: utf-8

from datetime import datetime

from django import forms
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import widgets
from django.contrib.admin.widgets import (FilteredSelectMultiple,
    AdminSplitDateTime, AdminFileWidget, ForeignKeyRawIdWidget, AdminRadioSelect,
    RelatedFieldWidgetWrapper, ManyToManyRawIdWidget,
    AutocompleteWidget, MultipleAutocompleteWidget)
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models import DateField
from django.test import TestCase as DjangoTestCase
from django.utils import simplejson
from django.utils.html import conditional_escape
from django.utils.translation import activate, deactivate
from django.utils.unittest import TestCase

import models

class AdminSiteStub(object):
    root_path = '/admin/'
    name = 'widgets-admin'

class AdminFormfieldForDBFieldTests(TestCase):
    """
    Tests for correct behavior of ModelAdmin.formfield_for_dbfield
    """

    def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides):
        """
        Helper to call formfield_for_dbfield for a given model and field name
        and verify that the returned formfield is appropriate.
        """
        # Override any settings on the model admin
        class MyModelAdmin(admin.ModelAdmin):
            pass
        for k in admin_overrides:
            setattr(MyModelAdmin, k, admin_overrides[k])

        # Construct the admin, and ask it for a formfield
        ma = MyModelAdmin(model, admin.site)
        ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None)

        # "unwrap" the widget wrapper, if needed
        if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper):
            widget = ff.widget.widget
        else:
            widget = ff.widget

        # Check that we got a field of the right type
        self.assert_(
            isinstance(widget, widgetclass),
            "Wrong widget for %s.%s: expected %s, got %s" % \
                (model.__class__.__name__, fieldname, widgetclass, type(widget))
        )

        # Return the formfield so that other tests can continue
        return ff

    def testDateField(self):
        self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget)

    def testDateTimeField(self):
        self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime)

    def testTimeField(self):
        self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget)

    def testTextField(self):
        self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget)

    def testURLField(self):
        self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget)

    def testIntegerField(self):
        self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget)

    def testCharField(self):
        self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget)

    def testFileField(self):
        self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget)

    def testForeignKey(self):
        self.assertFormfield(models.Event, 'band', forms.Select)

    def testRawIDForeignKey(self):
        self.assertFormfield(models.Event, 'band', widgets.ForeignKeyRawIdWidget,
                             raw_id_fields=['band'])

    def testRadioFieldsForeignKey(self):
        ff = self.assertFormfield(models.Event, 'band', widgets.AdminRadioSelect,
                                  radio_fields={'band':admin.VERTICAL})
        self.assertEqual(ff.empty_label, None)

    def testManyToMany(self):
        self.assertFormfield(models.Band, 'members', forms.SelectMultiple)

    def testRawIDManyTOMany(self):
        self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget,
                             raw_id_fields=['members'])

    def testFilteredManyToMany(self):
        self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple,
                             filter_vertical=['members'])

    def testFormfieldOverrides(self):
        self.assertFormfield(models.Event, 'start_date', forms.TextInput,
                             formfield_overrides={DateField: {'widget': forms.TextInput}})

    def testFieldWithChoices(self):
        self.assertFormfield(models.Member, 'gender', forms.Select)

    def testChoicesWithRadioFields(self):
        self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect,
                             radio_fields={'gender':admin.VERTICAL})

    def testInheritance(self):
        self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget)


class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
    fixtures = ["admin-widgets-users.xml"]

    def testFilterChoicesByRequestUser(self):
        """
        Ensure the user can only see their own cars in the foreign key dropdown.
        """
        self.client.login(username="super", password="secret")
        response = self.client.get("/widget_admin/admin_widgets/cartire/add/")
        self.assert_("BMW M3" not in response.content)
        self.assert_("Volkswagon Passat" in response.content)


class AdminForeignKeyWidgetChangeList(DjangoTestCase):
    fixtures = ["admin-widgets-users.xml"]
    admin_root = '/widget_admin'

    def setUp(self):
        self.client.login(username="super", password="secret")

    def tearDown(self):
        self.client.logout()

    def test_changelist_foreignkey(self):
        response = self.client.get('%s/admin_widgets/car/' % self.admin_root)
        self.assertTrue('%s/auth/user/add/' % self.admin_root in response.content)


class AdminForeignKeyRawIdWidget(DjangoTestCase):
    fixtures = ["admin-widgets-users.xml"]
    admin_root = '/widget_admin'

    def setUp(self):
        self.client.login(username="super", password="secret")

    def tearDown(self):
        self.client.logout()

    def test_nonexistent_target_id(self):
        band = models.Band.objects.create(name='Bogey Blues')
        pk = band.pk
        band.delete()
        post_data = {
            "band": u'%s' % pk,
        }
        # Try posting with a non-existent pk in a raw id field: this
        # should result in an error message, not a server exception.
        response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root,
            post_data)
        self.assertContains(response,
            'Select a valid choice. That choice is not one of the available choices.')

    def test_invalid_target_id(self):

        for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234):
            # This should result in an error message, not a server exception.
            response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root,
                {"band": test_str})

            self.assertContains(response,
                'Select a valid choice. That choice is not one of the available choices.')


class FilteredSelectMultipleWidgetTest(TestCase):
    def test_render(self):
        w = FilteredSelectMultiple('test', False)
        self.assertEqual(
            conditional_escape(w.render('test', 'test')),
            '<select multiple="multiple" name="test" class="selectfilter">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 0, "%(ADMIN_MEDIA_PREFIX)s"); });</script>\n' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX}
        )

    def test_stacked_render(self):
        w = FilteredSelectMultiple('test', True)
        self.assertEqual(
            conditional_escape(w.render('test', 'test')),
            '<select multiple="multiple" name="test" class="selectfilterstacked">\n</select><script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_test", "test", 1, "%(ADMIN_MEDIA_PREFIX)s"); });</script>\n' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX}
        )


class AdminSplitDateTimeWidgetTest(TestCase):
    def test_render(self):
        w = AdminSplitDateTime()
        self.assertEqual(
            conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))),
            '<p class="datetime">Date: <input value="2007-12-01" type="text" class="vDateField" name="test_0" size="10" /><br />Time: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>',
        )

    def test_localization(self):
        w = AdminSplitDateTime()

        activate('de-at')
        old_USE_L10N = settings.USE_L10N
        settings.USE_L10N = True
        w.is_localized = True
        self.assertEqual(
            conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))),
            '<p class="datetime">Datum: <input value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>',
        )
        deactivate()
        settings.USE_L10N = old_USE_L10N


class AdminFileWidgetTest(DjangoTestCase):
    def test_render(self):
        band = models.Band.objects.create(name='Linkin Park')
        album = band.album_set.create(
            name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
        )

        w = AdminFileWidget()
        self.assertEqual(
            conditional_escape(w.render('test', album.cover_art)),
            '<p class="file-upload">Currently: <a target="_blank" href="%(STORAGE_URL)salbums/hybrid_theory.jpg">albums\hybrid_theory.jpg</a> <span class="clearable-file-input"><input type="checkbox" name="test-clear" id="test-clear_id" /> <label for="test-clear_id">Clear</label></span><br />Change: <input type="file" name="test" /></p>' % { 'STORAGE_URL': default_storage.url('') },
        )

        self.assertEqual(
            conditional_escape(w.render('test', SimpleUploadedFile('test', 'content'))),
            '<input type="file" name="test" />',
        )


class ForeignKeyRawIdWidgetTest(DjangoTestCase):
    def test_render(self):
        band = models.Band.objects.create(name='Linkin Park')
        band.album_set.create(
            name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
        )
        rel = models.Album._meta.get_field('band').rel
        admin_site = AdminSiteStub()

        w = ForeignKeyRawIdWidget(rel)
        w_admin_site = ForeignKeyRawIdWidget(rel, admin_site=admin_site)
        self.assertEqual(
            conditional_escape(w.render('test', band.pk, attrs={})),
            '<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="../../../admin_widgets/band/?t=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "bandpk": band.pk},
        )
        self.assertEqual(
            conditional_escape(w_admin_site.render('test', band.pk, attrs={})),
            '<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="%(admin_site_root_path)sadmin_widgets/band/?t=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "bandpk": band.pk, "admin_site_root_path": admin_site.root_path},
        )

    def test_relations_to_non_primary_key(self):
        # Check that ForeignKeyRawIdWidget works with fields which aren't
        # related to the model's primary key.
        apple = models.Inventory.objects.create(barcode=86, name='Apple')
        models.Inventory.objects.create(barcode=22, name='Pear')
        core = models.Inventory.objects.create(
            barcode=87, name='Core', parent=apple
        )
        rel = models.Inventory._meta.get_field('parent').rel
        admin_site = AdminSiteStub()

        w = ForeignKeyRawIdWidget(rel)
        w_admin_site = ForeignKeyRawIdWidget(rel, admin_site=admin_site)
        self.assertEqual(
            w.render('test', core.parent_id, attrs={}),
            '<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="../../../admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX},
        )
        self.assertEqual(
            w_admin_site.render('test', core.parent_id, attrs={}),
            '<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="%(admin_site_root_path)sadmin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "admin_site_root_path": admin_site.root_path},
        )


    def test_proper_manager_for_label_lookup(self):
        # see #9258
        rel = models.Inventory._meta.get_field('parent').rel
        w = ForeignKeyRawIdWidget(rel)

        hidden = models.Inventory.objects.create(
            barcode=93, name='Hidden', hidden=True
        )
        child_of_hidden = models.Inventory.objects.create(
            barcode=94, name='Child of hidden', parent=hidden
        )
        self.assertEqual(
            w.render('test', child_of_hidden.parent_id, attrs={}),
            '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="../../../admin_widgets/inventory/?t=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX},
        )


class ManyToManyRawIdWidgetTest(DjangoTestCase):
    def test_render(self):
        band = models.Band.objects.create(name='Linkin Park')
        band.album_set.create(
            name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
        )

        m1 = models.Member.objects.create(name='Chester')
        m2 = models.Member.objects.create(name='Mike')
        band.members.add(m1, m2)
        rel = models.Band._meta.get_field('members').rel

        admin_site = AdminSiteStub()
        w = ManyToManyRawIdWidget(rel)
        w_admin_site = ManyToManyRawIdWidget(rel, admin_site=admin_site)
        self.assertEqual(
            conditional_escape(w.render('test', [m1.pk, m2.pk], attrs={})),
            '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="../../../admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "m1pk": m1.pk, "m2pk": m2.pk},
        )

        self.assertEqual(
            conditional_escape(w.render('test', [m1.pk])),
            '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="../../../admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "m1pk": m1.pk},
        )
        self.assertEqual(
            conditional_escape(w_admin_site.render('test', [m1.pk])),
            '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="%(admin_site_root_path)sadmin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_MEDIA_PREFIX)simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % {"ADMIN_MEDIA_PREFIX": settings.ADMIN_MEDIA_PREFIX, "m1pk": m1.pk, "admin_site_root_path": admin_site.root_path},
        )

        self.assertEqual(w._has_changed(None, None), False)
        self.assertEqual(w._has_changed([], None), False)
        self.assertEqual(w._has_changed(None, [u'1']), True)
        self.assertEqual(w._has_changed([1, 2], [u'1', u'2']), False)
        self.assertEqual(w._has_changed([1, 2], [u'1']), True)
        self.assertEqual(w._has_changed([1, 2], [u'1', u'3']), True)

class RelatedFieldWidgetWrapperTests(DjangoTestCase):
    def test_no_can_add_related(self):
        rel = models.Inventory._meta.get_field('parent').rel
        w = AdminRadioSelect()
        # Used to fail with a name error.
        w = RelatedFieldWidgetWrapper(w, rel, admin.site)
        self.assertFalse(w.can_add_related)


class AutocompleteWidgetTest(DjangoTestCase):
    def test_render(self):
        band = models.Band.objects.create(name='Linkin Park')
        band.album_set.create(
            name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
        )
        album = band.album_set.all()[0]

        widget_settings = {
            'fields': ('name',),
            'id': 'id',
            'limit': 5,
            'value': lambda o: unicode(o),
            'label': lambda o: unicode(o),
            'queryset': models.Album.objects.all(),
            }
        admin_site = AdminSiteStub()

        w = AutocompleteWidget(widget_settings, admin_site=admin_site)
        field_name = 'test'
        expected = "\n".join((
            '<div class="djangoautocomplete-wrapper">',
            '<input type="hidden" name="test" value="%(_pk)s" id="id_hidden_%(field_name)s" />',
            '<input type="text" value="%(_name)s" />',
            '</div>',
            '<script type="text/javascript">django.jQuery("#id_%(field_name)s").djangoautocomplete({"force_selection": true, "multiple": %(multiple)s, "source": "../autocomplete/%(field_name)s/"});</script>',
            ''
            )) % {'field_name': field_name,
                  '_pk': album.pk,
                  '_name': album.name,
                  'multiple': 'false',
                  }
        self.assertEqual(
            conditional_escape(w.render('test', album.pk, attrs={})),
            expected,
        )
        self.assertEqual(
            conditional_escape(w.render('test', long(album.pk), attrs={})),
            expected,
        )


class MultipleAutocompleteWidgetTest(DjangoTestCase):
    fixtures = ["admin-widgets-users.xml"]
    admin_root = '/widget_admin'

    def setUp(self):
        band = models.Band.objects.create(name='Linkin Park')
        band.album_set.create(
            name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
        )
        band2 = models.Band.objects.create(name='Johnny Cash')
        band2.album_set.create(
            name='At San Quentin'
        )
        self.bands = (band, band2)
    
    def _get_expected(self, name, bands, show_search=False):
        bands = [] if bands is None else bands
        expected = [
            '<div class="djangoautocomplete-wrapper">',
            '<input type="hidden" name="%(field_name)s" value="%(band_pks)s" id="id_hidden_%(field_name)s" />',
            '<input type="text" value="" />',  # input is for data entry only
            ]
        if bands:                
            expected += ['<ul class="ui-autocomplete-values">']
            expected += ['<li>%s</li>' % b.name for b in bands]
            expected += ['</ul>']
        expected += ['</div>']
        if show_search:
            expected += ['<a href="/admin/admin_widgets/band/?t=id" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%simg/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % (name, settings.ADMIN_MEDIA_PREFIX)]
        expected += [
            '<script type="text/javascript">django.jQuery("#id_%(field_name)s").djangoautocomplete({"force_selection": true, "multiple": %(multiple)s, "source": "../autocomplete/%(field_name)s/"});</script>',
            ''
            ]
        expected = "\n".join(expected) % {
            'field_name': name,
            'band_pks': ','.join([str(b.pk) for b in bands]),
            'multiple': 'true',
            }
        return expected

    def test_render(self):
        bands = self.bands

        widget_settings = {
            'fields': ('name',),
            'id': 'id',
            'limit': 5,
            'value': lambda o: unicode(o),
            'label': lambda o: unicode(o),
            'queryset': models.Band.objects.all(),
            'show_search': False,
            }
        with_search_settings = widget_settings.copy()
        with_search_settings['show_search'] = True
        admin_site = AdminSiteStub()
        
        w = MultipleAutocompleteWidget(widget_settings, admin_site=admin_site)
        expected_multiple = self._get_expected('test_multiple', bands)
        self.assertEqual(
            conditional_escape(w.render('test_multiple', [b.pk for b in bands], attrs={})),
            expected_multiple,
        )

        w = MultipleAutocompleteWidget(widget_settings, admin_site=admin_site)
        bands_just_one = bands[:1]
        expected_single = self._get_expected('test_single', bands_just_one)
        self.assertEqual(
            conditional_escape(w.render('test_single', [b.pk for b in bands_just_one], attrs={})),
            expected_single,
        )

        w = MultipleAutocompleteWidget(widget_settings, admin_site=admin_site)
        bands_none = None
        expected_none = self._get_expected('test_none', bands_none)
        self.assertEqual(
            conditional_escape(w.render('test_none', bands_none, attrs={})),
            expected_none,
        )

        w = MultipleAutocompleteWidget(widget_settings, admin_site=admin_site)
        bands_empty = []
        expected_empty = self._get_expected('test_empty', bands_empty)
        self.assertEqual(
            conditional_escape(w.render('test_empty', bands_empty, attrs={})),
            expected_empty,
        )

        w = MultipleAutocompleteWidget(with_search_settings, admin_site=admin_site)
        bands_none = None
        expected_search = self._get_expected('test_search', bands_none, show_search=True)
        self.assertEqual(
            conditional_escape(w.render('test_search', bands_none, attrs={})),
            expected_search,
        )
        

    def test_lookup(self):
        band = self.bands[1]
        self.client.login(username="super", password="secret")
        response = self.client.get('%s/admin_widgets/album/autocomplete/band/?term=johnny' % self.admin_root )
        self.assertEqual(simplejson.loads(response.content),
                         [{'id': band.id, 
                           'value': band.name,
                           'label': band.name}])
        response = self.client.get('%s/admin_widgets/album/autocomplete/band/?term=a' % self.admin_root )
        self.assertEqual(simplejson.loads(response.content),
                         [{'id': band.id, 
                           'value': band.name,
                           'label': band.name} for band in self.bands])
        response = self.client.get('%s/admin_widgets/album/autocomplete/band/?term=%s&by_id=1' % (self.admin_root, band.id ))
        self.assertEqual(simplejson.loads(response.content),
                         [{'id': band.id, 
                           'value': band.name,
                           'label': band.name}])
        

    def test_different_id(self):
        self.client.login(username="super", password="secret")
        user = models.User.objects.get(username='testser')
        user.member_set.create(
            name='Man Named Sue',
            user=user,
        )
        expected = [{'id': user.email, 
                     'value': user.username,
                     'label': user.username}]
        lookup_url = "%s/admin_widgets/member/autocomplete/user/?term=%%s" % self.admin_root
        lookup_by_id_url = "%s&by_id=1" % lookup_url

        response = self.client.get(lookup_url % user.username[:2])
        self.assertEqual(simplejson.loads(response.content),
                         expected)
        response = self.client.get(lookup_url % user.email[:2])
        self.assertEqual(simplejson.loads(response.content),
                         expected)
        response = self.client.get(lookup_url % user.first_name[:2])
        self.assertEqual(simplejson.loads(response.content),
                         expected)
        response = self.client.get(lookup_by_id_url % user.email)
        self.assertEqual(simplejson.loads(response.content),
                         expected)
        
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.