PEP8 cleanup

Signed-off-by: Jason Myers <jason@jasonamyers.com>
This commit is contained in:
Jason Myers 2013-11-02 23:36:09 -05:00
parent 0fdb692c6c
commit 7a61c68c50
128 changed files with 739 additions and 206 deletions

View File

@ -1,26 +1,32 @@
from django.db import models from django.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
class Event(models.Model): class Event(models.Model):
# Oracle can have problems with a column named "date" # Oracle can have problems with a column named "date"
date = models.DateField(db_column="event_date") date = models.DateField(db_column="event_date")
class Parent(models.Model): class Parent(models.Model):
name = models.CharField(max_length=128) name = models.CharField(max_length=128)
class Child(models.Model): class Child(models.Model):
parent = models.ForeignKey(Parent, editable=False, null=True) parent = models.ForeignKey(Parent, editable=False, null=True)
name = models.CharField(max_length=30, blank=True) name = models.CharField(max_length=30, blank=True)
age = models.IntegerField(null=True, blank=True) age = models.IntegerField(null=True, blank=True)
class Genre(models.Model): class Genre(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
class Band(models.Model): class Band(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
nr_of_members = models.PositiveIntegerField() nr_of_members = models.PositiveIntegerField()
genres = models.ManyToManyField(Genre) genres = models.ManyToManyField(Genre)
@python_2_unicode_compatible @python_2_unicode_compatible
class Musician(models.Model): class Musician(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -28,6 +34,7 @@ class Musician(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Group(models.Model): class Group(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -36,26 +43,32 @@ class Group(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class Membership(models.Model): class Membership(models.Model):
music = models.ForeignKey(Musician) music = models.ForeignKey(Musician)
group = models.ForeignKey(Group) group = models.ForeignKey(Group)
role = models.CharField(max_length=15) role = models.CharField(max_length=15)
class Quartet(Group): class Quartet(Group):
pass pass
class ChordsMusician(Musician): class ChordsMusician(Musician):
pass pass
class ChordsBand(models.Model): class ChordsBand(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
members = models.ManyToManyField(ChordsMusician, through='Invitation') members = models.ManyToManyField(ChordsMusician, through='Invitation')
class Invitation(models.Model): class Invitation(models.Model):
player = models.ForeignKey(ChordsMusician) player = models.ForeignKey(ChordsMusician)
band = models.ForeignKey(ChordsBand) band = models.ForeignKey(ChordsBand)
instrument = models.CharField(max_length=15) instrument = models.CharField(max_length=15)
class Swallow(models.Model): class Swallow(models.Model):
origin = models.CharField(max_length=255) origin = models.CharField(max_length=255)
load = models.FloatField() load = models.FloatField()
@ -77,6 +90,7 @@ class OrderedObjectManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(OrderedObjectManager, self).get_queryset().order_by('number') return super(OrderedObjectManager, self).get_queryset().order_by('number')
class OrderedObject(models.Model): class OrderedObject(models.Model):
""" """
Model with Manager that defines a default order. Model with Manager that defines a default order.
@ -88,5 +102,6 @@ class OrderedObject(models.Model):
objects = OrderedObjectManager() objects = OrderedObjectManager()
class CustomIdUser(models.Model): class CustomIdUser(models.Model):
uuid = models.AutoField(primary_key=True) uuid = models.AutoField(primary_key=True)

View File

@ -54,6 +54,7 @@ class ActionAdmin(admin.ModelAdmin):
class Person(models.Model): class Person(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
class PersonAdmin(admin.ModelAdmin): class PersonAdmin(admin.ModelAdmin):
def response_post_save_add(self, request, obj): def response_post_save_add(self, request, obj):
@ -68,6 +69,7 @@ class PersonAdmin(admin.ModelAdmin):
class Car(models.Model): class Car(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
class CarAdmin(admin.ModelAdmin): class CarAdmin(admin.ModelAdmin):
def response_add(self, request, obj, post_url_continue=None): def response_add(self, request, obj, post_url_continue=None):

View File

@ -5,9 +5,11 @@ from django.contrib.admindocs.middleware import XViewMiddleware
xview_dec = decorator_from_middleware(XViewMiddleware) xview_dec = decorator_from_middleware(XViewMiddleware)
def xview(request): def xview(request):
return HttpResponse() return HttpResponse()
class XViewClass(View): class XViewClass(View):
def get(self, request): def get(self, request):
return HttpResponse() return HttpResponse()

View File

@ -27,6 +27,7 @@ class Department(models.Model):
def __str__(self): def __str__(self):
return self.description return self.description
@python_2_unicode_compatible @python_2_unicode_compatible
class Employee(models.Model): class Employee(models.Model):
department = models.ForeignKey(Department, to_field="code") department = models.ForeignKey(Department, to_field="code")

View File

@ -153,6 +153,7 @@ class ChildModel1Inline(admin.TabularInline):
class ChildModel2Inline(admin.StackedInline): class ChildModel2Inline(admin.StackedInline):
model = ChildModel2 model = ChildModel2
# admin for #19425 and #18388 # admin for #19425 and #18388
class BinaryTreeAdmin(admin.TabularInline): class BinaryTreeAdmin(admin.TabularInline):
model = BinaryTree model = BinaryTree
@ -169,10 +170,12 @@ class BinaryTreeAdmin(admin.TabularInline):
return max_num - obj.binarytree_set.count() return max_num - obj.binarytree_set.count()
return max_num return max_num
# admin for #19524 # admin for #19524
class SightingInline(admin.TabularInline): class SightingInline(admin.TabularInline):
model = Sighting model = Sighting
# admin and form for #18263 # admin and form for #18263
class SomeChildModelForm(forms.ModelForm): class SomeChildModelForm(forms.ModelForm):

View File

@ -89,6 +89,7 @@ class Inner2(models.Model):
dummy = models.IntegerField() dummy = models.IntegerField()
holder = models.ForeignKey(Holder2) holder = models.ForeignKey(Holder2)
class Holder3(models.Model): class Holder3(models.Model):
dummy = models.IntegerField() dummy = models.IntegerField()
@ -99,38 +100,47 @@ class Inner3(models.Model):
# Models for ticket #8190 # Models for ticket #8190
class Holder4(models.Model): class Holder4(models.Model):
dummy = models.IntegerField() dummy = models.IntegerField()
class Inner4Stacked(models.Model): class Inner4Stacked(models.Model):
dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.") dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.")
holder = models.ForeignKey(Holder4) holder = models.ForeignKey(Holder4)
class Inner4Tabular(models.Model): class Inner4Tabular(models.Model):
dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.") dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.")
holder = models.ForeignKey(Holder4) holder = models.ForeignKey(Holder4)
# Models for #12749 # Models for #12749
class Person(models.Model): class Person(models.Model):
firstname = models.CharField(max_length=15) firstname = models.CharField(max_length=15)
class OutfitItem(models.Model): class OutfitItem(models.Model):
name = models.CharField(max_length=15) name = models.CharField(max_length=15)
class Fashionista(models.Model): class Fashionista(models.Model):
person = models.OneToOneField(Person, primary_key=True) person = models.OneToOneField(Person, primary_key=True)
weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True) weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True)
class ShoppingWeakness(models.Model): class ShoppingWeakness(models.Model):
fashionista = models.ForeignKey(Fashionista) fashionista = models.ForeignKey(Fashionista)
item = models.ForeignKey(OutfitItem) item = models.ForeignKey(OutfitItem)
# Models for #13510 # Models for #13510
class TitleCollection(models.Model): class TitleCollection(models.Model):
pass pass
class Title(models.Model): class Title(models.Model):
collection = models.ForeignKey(TitleCollection, blank=True, null=True) collection = models.ForeignKey(TitleCollection, blank=True, null=True)
title1 = models.CharField(max_length=100) title1 = models.CharField(max_length=100)
@ -138,19 +148,24 @@ class Title(models.Model):
# Models for #15424 # Models for #15424
class Poll(models.Model): class Poll(models.Model):
name = models.CharField(max_length=40) name = models.CharField(max_length=40)
class Question(models.Model): class Question(models.Model):
poll = models.ForeignKey(Poll) poll = models.ForeignKey(Poll)
class Novel(models.Model): class Novel(models.Model):
name = models.CharField(max_length=40) name = models.CharField(max_length=40)
class Chapter(models.Model): class Chapter(models.Model):
name = models.CharField(max_length=40) name = models.CharField(max_length=40)
novel = models.ForeignKey(Novel) novel = models.ForeignKey(Novel)
class FootNote(models.Model): class FootNote(models.Model):
""" """
Model added for ticket 19838 Model added for ticket 19838
@ -160,6 +175,7 @@ class FootNote(models.Model):
# Models for #16838 # Models for #16838
class CapoFamiglia(models.Model): class CapoFamiglia(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -211,12 +227,15 @@ class BinaryTree(models.Model):
# Models for #19524 # Models for #19524
class LifeForm(models.Model): class LifeForm(models.Model):
pass pass
class ExtraTerrestrial(LifeForm): class ExtraTerrestrial(LifeForm):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Sighting(models.Model): class Sighting(models.Model):
et = models.ForeignKey(ExtraTerrestrial) et = models.ForeignKey(ExtraTerrestrial)
place = models.CharField(max_length=100) place = models.CharField(max_length=100)
@ -234,9 +253,11 @@ class SomeChildModel(models.Model):
# Other models # Other models
class ProfileCollection(models.Model): class ProfileCollection(models.Model):
pass pass
class Profile(models.Model): class Profile(models.Model):
collection = models.ForeignKey(ProfileCollection, blank=True, null=True) collection = models.ForeignKey(ProfileCollection, blank=True, null=True)
first_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100)

View File

@ -279,6 +279,7 @@ class TestInlineMedia(TestCase):
self.assertContains(response, 'my_awesome_admin_scripts.js') self.assertContains(response, 'my_awesome_admin_scripts.js')
self.assertContains(response, 'my_awesome_inline_scripts.js') self.assertContains(response, 'my_awesome_inline_scripts.js')
class TestInlineAdminForm(TestCase): class TestInlineAdminForm(TestCase):
urls = "admin_inlines.urls" urls = "admin_inlines.urls"
@ -465,9 +466,9 @@ class TestInlinePermissions(TestCase):
self.assertContains(response, 'Add another Inner2') self.assertContains(response, 'Add another Inner2')
# 3 extra forms only, not the existing instance form # 3 extra forms only, not the existing instance form
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
'value="3" name="inner2_set-TOTAL_FORMS" />', html=True) 'value="3" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertNotContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' self.assertNotContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
def test_inline_change_fk_change_perm(self): def test_inline_change_fk_change_perm(self):
permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct)
@ -477,12 +478,12 @@ class TestInlinePermissions(TestCase):
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# Just the one form for existing instances # Just the one form for existing instances
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
# max-num 0 means we can't add new ones # max-num 0 means we can't add new ones
self.assertContains(response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" '
'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True) 'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True)
def test_inline_change_fk_add_change_perm(self): def test_inline_change_fk_add_change_perm(self):
permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct)
@ -494,9 +495,9 @@ class TestInlinePermissions(TestCase):
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance and three extra for new # One form for existing instance and three extra for new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
def test_inline_change_fk_change_del_perm(self): def test_inline_change_fk_change_del_perm(self):
permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct)
@ -508,9 +509,9 @@ class TestInlinePermissions(TestCase):
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance only, no new # One form for existing instance only, no new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"') self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
def test_inline_change_fk_all_perms(self): def test_inline_change_fk_all_perms(self):
@ -525,9 +526,9 @@ class TestInlinePermissions(TestCase):
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance only, three for new # One form for existing instance only, three for new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True)
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" '
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"') self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
@ -698,5 +699,6 @@ class SeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class SeleniumChromeTests(SeleniumFirefoxTests): class SeleniumChromeTests(SeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class SeleniumIETests(SeleniumFirefoxTests): class SeleniumIETests(SeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'

View File

@ -11,6 +11,7 @@ class Band(models.Model):
class Meta: class Meta:
ordering = ('name',) ordering = ('name',)
class Song(models.Model): class Song(models.Model):
band = models.ForeignKey(Band) band = models.ForeignKey(Band)
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -20,13 +21,16 @@ class Song(models.Model):
class Meta: class Meta:
ordering = ('name',) ordering = ('name',)
class SongInlineDefaultOrdering(admin.StackedInline): class SongInlineDefaultOrdering(admin.StackedInline):
model = Song model = Song
class SongInlineNewOrdering(admin.StackedInline): class SongInlineNewOrdering(admin.StackedInline):
model = Song model = Song
ordering = ('duration', ) ordering = ('duration', )
class DynOrderingBandAdmin(admin.ModelAdmin): class DynOrderingBandAdmin(admin.ModelAdmin):
def get_ordering(self, request): def get_ordering(self, request):

View File

@ -12,6 +12,7 @@ from .models import (Band, Song, SongInlineDefaultOrdering,
class MockRequest(object): class MockRequest(object):
pass pass
class MockSuperUser(object): class MockSuperUser(object):
def has_perm(self, perm): def has_perm(self, perm):
return True return True

View File

@ -289,6 +289,7 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase):
self.assertNoOutput(err) self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:NoArgsCommand") self.assertOutput(out, "EXECUTE:NoArgsCommand")
class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings.py file that """A series of tests for django-admin.py when using a settings.py file that
contains the test application specified using a full path. contains the test application specified using a full path.
@ -355,6 +356,7 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
self.assertNoOutput(err) self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:NoArgsCommand") self.assertOutput(out, "EXECUTE:NoArgsCommand")
class DjangoAdminMinimalSettings(AdminScriptTestCase): class DjangoAdminMinimalSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings.py file that """A series of tests for django-admin.py when using a settings.py file that
doesn't contain the test application. doesn't contain the test application.
@ -421,6 +423,7 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase):
self.assertNoOutput(out) self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'") self.assertOutput(err, "Unknown command: 'noargs_command'")
class DjangoAdminAlternateSettings(AdminScriptTestCase): class DjangoAdminAlternateSettings(AdminScriptTestCase):
"""A series of tests for django-admin.py when using a settings file """A series of tests for django-admin.py when using a settings file
with a name other than 'settings.py'. with a name other than 'settings.py'.
@ -796,6 +799,7 @@ class ManageFullPathDefaultSettings(AdminScriptTestCase):
self.assertNoOutput(err) self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:NoArgsCommand") self.assertOutput(out, "EXECUTE:NoArgsCommand")
class ManageMinimalSettings(AdminScriptTestCase): class ManageMinimalSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that """A series of tests for manage.py when using a settings.py file that
doesn't contain the test application. doesn't contain the test application.
@ -862,6 +866,7 @@ class ManageMinimalSettings(AdminScriptTestCase):
self.assertNoOutput(out) self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'") self.assertOutput(err, "Unknown command: 'noargs_command'")
class ManageAlternateSettings(AdminScriptTestCase): class ManageAlternateSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings file """A series of tests for manage.py when using a settings file
with a name other than 'settings.py'. with a name other than 'settings.py'.
@ -1121,6 +1126,7 @@ class CustomTestRunner(DiscoverRunner):
def run_tests(self, test_labels, extra_tests=None, **kwargs): def run_tests(self, test_labels, extra_tests=None, **kwargs):
pass pass
class ManageTestCommand(AdminScriptTestCase): class ManageTestCommand(AdminScriptTestCase):
def setUp(self): def setUp(self):
from django.core.management.commands.test import Command as TestCommand from django.core.management.commands.test import Command as TestCommand
@ -1214,6 +1220,7 @@ class ManageRunserver(AdminScriptTestCase):
self.cmd.handle(addrport="deadbeef:7654") self.cmd.handle(addrport="deadbeef:7654")
self.assertServerSettings('deadbeef', '7654') self.assertServerSettings('deadbeef', '7654')
class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase): class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
def setUp(self): def setUp(self):
self.write_settings('settings.py', sdict={ self.write_settings('settings.py', sdict={
@ -1464,6 +1471,7 @@ class CommandTypes(AdminScriptTestCase):
self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]")) self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]"))
self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]")) self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]"))
class ArgumentOrder(AdminScriptTestCase): class ArgumentOrder(AdminScriptTestCase):
"""Tests for 2-stage argument parsing scheme. """Tests for 2-stage argument parsing scheme.
@ -1751,6 +1759,7 @@ class DiffSettings(AdminScriptTestCase):
self.assertNoOutput(err) self.assertNoOutput(err)
self.assertOutput(out, "### STATIC_URL = None") self.assertOutput(out, "### STATIC_URL = None")
class Dumpdata(AdminScriptTestCase): class Dumpdata(AdminScriptTestCase):
"""Tests for dumpdata management command.""" """Tests for dumpdata management command."""

View File

@ -19,6 +19,7 @@ class Article(models.Model):
return "nothing" return "nothing"
test_from_model_with_override.short_description = "not What you Expect" test_from_model_with_override.short_description = "not What you Expect"
@python_2_unicode_compatible @python_2_unicode_compatible
class Count(models.Model): class Count(models.Model):
num = models.PositiveSmallIntegerField() num = models.PositiveSmallIntegerField()
@ -27,12 +28,15 @@ class Count(models.Model):
def __str__(self): def __str__(self):
return six.text_type(self.num) return six.text_type(self.num)
class Event(models.Model): class Event(models.Model):
date = models.DateTimeField(auto_now_add=True) date = models.DateTimeField(auto_now_add=True)
class Location(models.Model): class Location(models.Model):
event = models.OneToOneField(Event, verbose_name='awesome event') event = models.OneToOneField(Event, verbose_name='awesome event')
class Guest(models.Model): class Guest(models.Model):
event = models.OneToOneField(Event) event = models.OneToOneField(Event)
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
@ -40,5 +44,6 @@ class Guest(models.Model):
class Meta: class Meta:
verbose_name = "awesome guest" verbose_name = "awesome guest"
class EventGuide(models.Model): class EventGuide(models.Model):
event = models.ForeignKey(Event, on_delete=models.DO_NOTHING) event = models.ForeignKey(Event, on_delete=models.DO_NOTHING)

View File

@ -80,6 +80,7 @@ class NestedObjectsTests(TestCase):
# One for Location, one for Guest, and no query for EventGuide # One for Location, one for Guest, and no query for EventGuide
n.collect(objs) n.collect(objs)
class UtilTests(SimpleTestCase): class UtilTests(SimpleTestCase):
def test_values_from_lookup_field(self): def test_values_from_lookup_field(self):
""" """
@ -228,9 +229,8 @@ class UtilTests(SimpleTestCase):
) )
self.assertEqual( self.assertEqual(
label_for_field("test_from_model", Article, label_for_field("test_from_model", Article,
model_admin = MockModelAdmin, model_admin=MockModelAdmin,
return_attr = True return_attr=True),
),
("not Really the Model", MockModelAdmin.test_from_model) ("not Really the Model", MockModelAdmin.test_from_model)
) )

View File

@ -12,10 +12,12 @@ from .models import Song, Book, Album, TwoAlbumFKAndAnE, City
class SongForm(forms.ModelForm): class SongForm(forms.ModelForm):
pass pass
class ValidFields(admin.ModelAdmin): class ValidFields(admin.ModelAdmin):
form = SongForm form = SongForm
fields = ['title'] fields = ['title']
class ValidFormFieldsets(admin.ModelAdmin): class ValidFormFieldsets(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs): def get_form(self, request, obj=None, **kwargs):
class ExtraFieldForm(SongForm): class ExtraFieldForm(SongForm):
@ -28,6 +30,7 @@ class ValidFormFieldsets(admin.ModelAdmin):
}), }),
) )
class ValidationTestCase(TestCase): class ValidationTestCase(TestCase):
def test_readonly_and_editable(self): def test_readonly_and_editable(self):

View File

@ -120,11 +120,13 @@ class Color(models.Model):
def __str__(self): def __str__(self):
return self.value return self.value
# we replicate Color to register with another ModelAdmin # we replicate Color to register with another ModelAdmin
class Color2(Color): class Color2(Color):
class Meta: class Meta:
proxy = True proxy = True
@python_2_unicode_compatible @python_2_unicode_compatible
class Thing(models.Model): class Thing(models.Model):
title = models.CharField(max_length=20) title = models.CharField(max_length=20)
@ -613,10 +615,12 @@ class PrePopulatedPostLargeSlug(models.Model):
published = models.BooleanField(default=False) published = models.BooleanField(default=False)
slug = models.SlugField(max_length=1000) slug = models.SlugField(max_length=1000)
class AdminOrderedField(models.Model): class AdminOrderedField(models.Model):
order = models.IntegerField() order = models.IntegerField()
stuff = models.CharField(max_length=200) stuff = models.CharField(max_length=200)
class AdminOrderedModelMethod(models.Model): class AdminOrderedModelMethod(models.Model):
order = models.IntegerField() order = models.IntegerField()
stuff = models.CharField(max_length=200) stuff = models.CharField(max_length=200)
@ -625,14 +629,17 @@ class AdminOrderedModelMethod(models.Model):
return self.order return self.order
some_order.admin_order_field = 'order' some_order.admin_order_field = 'order'
class AdminOrderedAdminMethod(models.Model): class AdminOrderedAdminMethod(models.Model):
order = models.IntegerField() order = models.IntegerField()
stuff = models.CharField(max_length=200) stuff = models.CharField(max_length=200)
class AdminOrderedCallable(models.Model): class AdminOrderedCallable(models.Model):
order = models.IntegerField() order = models.IntegerField()
stuff = models.CharField(max_length=200) stuff = models.CharField(max_length=200)
@python_2_unicode_compatible @python_2_unicode_compatible
class Report(models.Model): class Report(models.Model):
title = models.CharField(max_length=100) title = models.CharField(max_length=100)
@ -651,6 +658,7 @@ class MainPrepopulated(models.Model):
slug1 = models.SlugField(blank=True) slug1 = models.SlugField(blank=True)
slug2 = models.SlugField(blank=True) slug2 = models.SlugField(blank=True)
class RelatedPrepopulated(models.Model): class RelatedPrepopulated(models.Model):
parent = models.ForeignKey(MainPrepopulated) parent = models.ForeignKey(MainPrepopulated)
name = models.CharField(max_length=75) name = models.CharField(max_length=75)
@ -671,6 +679,7 @@ class UnorderedObject(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
bool = models.BooleanField(default=True) bool = models.BooleanField(default=True)
class UndeletableObject(models.Model): class UndeletableObject(models.Model):
""" """
Model whose show_delete in admin change_view has been disabled Model whose show_delete in admin change_view has been disabled
@ -678,30 +687,36 @@ class UndeletableObject(models.Model):
""" """
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
class UnchangeableObject(models.Model): class UnchangeableObject(models.Model):
""" """
Model whose change_view is disabled in admin Model whose change_view is disabled in admin
Refs #20640. Refs #20640.
""" """
class UserMessenger(models.Model): class UserMessenger(models.Model):
""" """
Dummy class for testing message_user functions on ModelAdmin Dummy class for testing message_user functions on ModelAdmin
""" """
class Simple(models.Model): class Simple(models.Model):
""" """
Simple model with nothing on it for use in testing Simple model with nothing on it for use in testing
""" """
class Choice(models.Model): class Choice(models.Model):
choice = models.IntegerField(blank=True, null=True, choice = models.IntegerField(blank=True, null=True,
choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion'))) choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion')))
class _Manager(models.Manager): class _Manager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(_Manager, self).get_queryset().filter(pk__gt=1) return super(_Manager, self).get_queryset().filter(pk__gt=1)
class FilteredManager(models.Model): class FilteredManager(models.Model):
def __str__(self): def __str__(self):
return "PK=%d" % self.pk return "PK=%d" % self.pk
@ -709,26 +724,33 @@ class FilteredManager(models.Model):
pk_gt_1 = _Manager() pk_gt_1 = _Manager()
objects = models.Manager() objects = models.Manager()
class EmptyModelVisible(models.Model): class EmptyModelVisible(models.Model):
""" See ticket #11277. """ """ See ticket #11277. """
class EmptyModelHidden(models.Model): class EmptyModelHidden(models.Model):
""" See ticket #11277. """ """ See ticket #11277. """
class EmptyModelMixin(models.Model): class EmptyModelMixin(models.Model):
""" See ticket #11277. """ """ See ticket #11277. """
class State(models.Model): class State(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class City(models.Model): class City(models.Model):
state = models.ForeignKey(State) state = models.ForeignKey(State)
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Restaurant(models.Model): class Restaurant(models.Model):
city = models.ForeignKey(City) city = models.ForeignKey(City)
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Worker(models.Model): class Worker(models.Model):
work_at = models.ForeignKey(Restaurant) work_at = models.ForeignKey(Restaurant)
name = models.CharField(max_length=50) name = models.CharField(max_length=50)

View File

@ -84,8 +84,8 @@ class AdminViewBasicTestCase(TestCase):
""" """
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTrue(response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2)), self.assertTrue(response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2)),
failing_msg failing_msg)
)
class AdminViewBasicTest(AdminViewBasicTestCase): class AdminViewBasicTest(AdminViewBasicTestCase):
def testTrailingSlashRequired(self): def testTrailingSlashRequired(self):
@ -94,8 +94,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
""" """
response = self.client.get('/test_admin/%s/admin_views/article/add' % self.urlbit) response = self.client.get('/test_admin/%s/admin_views/article/add' % self.urlbit)
self.assertRedirects(response, self.assertRedirects(response,
'/test_admin/%s/admin_views/article/add/' % self.urlbit, status_code=301 '/test_admin/%s/admin_views/article/add/' % self.urlbit,
) status_code=301)
def testBasicAddGet(self): def testBasicAddGet(self):
""" """
@ -109,8 +109,7 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit, {'name': 'My Section'}) response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit, {'name': 'My Section'})
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertContains(response, 'value="My Section"', self.assertContains(response, 'value="My Section"',
msg_prefix="Couldn't find an input with the right value in the response" msg_prefix="Couldn't find an input with the right value in the response")
)
def testBasicEditGet(self): def testBasicEditGet(self):
""" """
@ -394,11 +393,9 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit) response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertContains(response, '<div id="changelist-filter">', self.assertContains(response, '<div id="changelist-filter">',
msg_prefix="Expected filter not found in changelist view" msg_prefix="Expected filter not found in changelist view")
)
self.assertNotContains(response, '<a href="?color__id__exact=3">Blue</a>', self.assertNotContains(response, '<a href="?color__id__exact=3">Blue</a>',
msg_prefix="Changelist filter not correctly limited by limit_choices_to" msg_prefix="Changelist filter not correctly limited by limit_choices_to")
)
def testRelationSpanningFilters(self): def testRelationSpanningFilters(self):
response = self.client.get('/test_admin/%s/admin_views/chapterxtra1/' % response = self.client.get('/test_admin/%s/admin_views/chapterxtra1/' %
@ -1557,7 +1554,7 @@ class AdminViewStringPrimaryKeyTest(TestCase):
response = self.client.get('/test_admin/admin/') response = self.client.get('/test_admin/admin/')
counted_presence_after = response.content.count(force_bytes(should_contain)) counted_presence_after = response.content.count(force_bytes(should_contain))
self.assertEqual(counted_presence_before - 1, self.assertEqual(counted_presence_before - 1,
counted_presence_after) counted_presence_after)
def test_logentry_get_admin_url(self): def test_logentry_get_admin_url(self):
"LogEntry.get_admin_url returns a URL to edit the entry's object or None for non-existent (possibly deleted) models" "LogEntry.get_admin_url returns a URL to edit the entry's object or None for non-existent (possibly deleted) models"
@ -1612,13 +1609,13 @@ class AdminViewStringPrimaryKeyTest(TestCase):
def test_change_view_history_link(self): def test_change_view_history_link(self):
"""Object history button link should work and contain the pk value quoted.""" """Object history button link should work and contain the pk value quoted."""
url = reverse('admin:%s_modelwithstringprimarykey_change' % url = reverse('admin:%s_modelwithstringprimarykey_change' %
ModelWithStringPrimaryKey._meta.app_label, ModelWithStringPrimaryKey._meta.app_label,
args=(quote(self.pk),)) args=(quote(self.pk),))
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
expected_link = reverse('admin:%s_modelwithstringprimarykey_history' % expected_link = reverse('admin:%s_modelwithstringprimarykey_history' %
ModelWithStringPrimaryKey._meta.app_label, ModelWithStringPrimaryKey._meta.app_label,
args=(quote(self.pk),)) args=(quote(self.pk),))
self.assertContains(response, '<a href="%s" class="historylink"' % expected_link) self.assertContains(response, '<a href="%s" class="historylink"' % expected_link)
@ -2553,8 +2550,7 @@ action)</option>
response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/') response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/')
self.assertEqual(response.context["action_form"], None) self.assertEqual(response.context["action_form"], None)
self.assertContains(response, 'jquery.min.js', self.assertContains(response, 'jquery.min.js',
msg_prefix="jQuery missing from admin pages for model with no admin actions" msg_prefix="jQuery missing from admin pages for model with no admin actions")
)
def test_action_column_class(self): def test_action_column_class(self):
"Tests that the checkbox column class is present in the response" "Tests that the checkbox column class is present in the response"
@ -3631,8 +3627,7 @@ class ReadonlyTest(TestCase):
self.assertContains(response, "InlineMultiline<br />test<br />string") self.assertContains(response, "InlineMultiline<br />test<br />string")
self.assertContains(response, self.assertContains(response,
formats.localize(datetime.date.today() - datetime.timedelta(days=7)) formats.localize(datetime.date.today() - datetime.timedelta(days=7)))
)
self.assertContains(response, '<div class="form-row field-coolness">') self.assertContains(response, '<div class="form-row field-coolness">')
self.assertContains(response, '<div class="form-row field-awesomeness_level">') self.assertContains(response, '<div class="form-row field-awesomeness_level">')
@ -3829,7 +3824,7 @@ class UserAdminTest(TestCase):
adminform = response.context['adminform'] adminform = response.context['adminform']
self.assertTrue('password' not in adminform.form.errors) self.assertTrue('password' not in adminform.form.errors)
self.assertEqual(adminform.form.errors['password2'], self.assertEqual(adminform.form.errors['password2'],
["The two password fields didn't match."]) ["The two password fields didn't match."])
def test_user_fk_popup(self): def test_user_fk_popup(self):
"""Quick user addition in a FK popup shouldn't invoke view for further user customization""" """Quick user addition in a FK popup shouldn't invoke view for further user customization"""

View File

@ -1,6 +1,7 @@
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse from django.http import HttpResponse
@staff_member_required @staff_member_required
def secure_view(request): def secure_view(request):
return HttpResponse('%s' % request.POST) return HttpResponse('%s' % request.POST)

View File

@ -8,6 +8,7 @@ from django.utils.encoding import python_2_unicode_compatible
class MyFileField(models.FileField): class MyFileField(models.FileField):
pass pass
@python_2_unicode_compatible @python_2_unicode_compatible
class Member(models.Model): class Member(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -18,6 +19,7 @@ class Member(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Band(models.Model): class Band(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -27,6 +29,7 @@ class Band(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Album(models.Model): class Album(models.Model):
band = models.ForeignKey(Band) band = models.ForeignKey(Band)
@ -37,10 +40,12 @@ class Album(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class HiddenInventoryManager(models.Manager): class HiddenInventoryManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(HiddenInventoryManager, self).get_queryset().filter(hidden=False) return super(HiddenInventoryManager, self).get_queryset().filter(hidden=False)
@python_2_unicode_compatible @python_2_unicode_compatible
class Inventory(models.Model): class Inventory(models.Model):
barcode = models.PositiveIntegerField(unique=True) barcode = models.PositiveIntegerField(unique=True)
@ -55,6 +60,7 @@ class Inventory(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class Event(models.Model): class Event(models.Model):
main_band = models.ForeignKey(Band, limit_choices_to=models.Q(pk__gt=0), related_name='events_main_band_at') main_band = models.ForeignKey(Band, limit_choices_to=models.Q(pk__gt=0), related_name='events_main_band_at')
supporting_bands = models.ManyToManyField(Band, null=True, blank=True, related_name='events_supporting_band_at') supporting_bands = models.ManyToManyField(Band, null=True, blank=True, related_name='events_supporting_band_at')
@ -64,6 +70,7 @@ class Event(models.Model):
link = models.URLField(blank=True) link = models.URLField(blank=True)
min_age = models.IntegerField(blank=True, null=True) min_age = models.IntegerField(blank=True, null=True)
@python_2_unicode_compatible @python_2_unicode_compatible
class Car(models.Model): class Car(models.Model):
owner = models.ForeignKey(User) owner = models.ForeignKey(User)
@ -73,15 +80,18 @@ class Car(models.Model):
def __str__(self): def __str__(self):
return "%s %s" % (self.make, self.model) return "%s %s" % (self.make, self.model)
class CarTire(models.Model): class CarTire(models.Model):
""" """
A single car tire. This to test that a user can only select their own cars. A single car tire. This to test that a user can only select their own cars.
""" """
car = models.ForeignKey(Car) car = models.ForeignKey(Car)
class Honeycomb(models.Model): class Honeycomb(models.Model):
location = models.CharField(max_length=20) location = models.CharField(max_length=20)
class Bee(models.Model): class Bee(models.Model):
""" """
A model with a FK to a model that won't be registered with the admin A model with a FK to a model that won't be registered with the admin
@ -90,6 +100,7 @@ class Bee(models.Model):
""" """
honeycomb = models.ForeignKey(Honeycomb) honeycomb = models.ForeignKey(Honeycomb)
class Individual(models.Model): class Individual(models.Model):
""" """
A model with a FK to itself. It won't be registered with the admin, so the A model with a FK to itself. It won't be registered with the admin, so the
@ -99,9 +110,11 @@ class Individual(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
parent = models.ForeignKey('self', null=True) parent = models.ForeignKey('self', null=True)
class Company(models.Model): class Company(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
class Advisor(models.Model): class Advisor(models.Model):
""" """
A model with a m2m to a model that won't be registered with the admin A model with a m2m to a model that won't be registered with the admin
@ -122,6 +135,7 @@ class Student(models.Model):
class Meta: class Meta:
ordering = ('name',) ordering = ('name',)
@python_2_unicode_compatible @python_2_unicode_compatible
class School(models.Model): class School(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)

View File

@ -25,6 +25,7 @@ admin_static_prefix = lambda: {
'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL, 'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL,
} }
class AdminFormfieldForDBFieldTests(TestCase): class AdminFormfieldForDBFieldTests(TestCase):
""" """
Tests for correct behavior of ModelAdmin.formfield_for_dbfield Tests for correct behavior of ModelAdmin.formfield_for_dbfield
@ -269,6 +270,7 @@ class FilteredSelectMultipleWidgetTest(DjangoTestCase):
'<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_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix() '<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_STATIC_PREFIX)s"); });</script>\n' % admin_static_prefix()
) )
class AdminDateWidgetTest(DjangoTestCase): class AdminDateWidgetTest(DjangoTestCase):
def test_attrs(self): def test_attrs(self):
""" """
@ -287,6 +289,7 @@ class AdminDateWidgetTest(DjangoTestCase):
'<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />', '<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />',
) )
class AdminTimeWidgetTest(DjangoTestCase): class AdminTimeWidgetTest(DjangoTestCase):
def test_attrs(self): def test_attrs(self):
""" """
@ -305,6 +308,7 @@ class AdminTimeWidgetTest(DjangoTestCase):
'<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />', '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />',
) )
class AdminSplitDateTimeWidgetTest(DjangoTestCase): class AdminSplitDateTimeWidgetTest(DjangoTestCase):
def test_render(self): def test_render(self):
w = widgets.AdminSplitDateTime() w = widgets.AdminSplitDateTime()
@ -495,6 +499,7 @@ class ManyToManyRawIdWidgetTest(DjangoTestCase):
'<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk} '<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk}
) )
class RelatedFieldWidgetWrapperTests(DjangoTestCase): class RelatedFieldWidgetWrapperTests(DjangoTestCase):
def test_no_can_add_related(self): def test_no_can_add_related(self):
rel = models.Individual._meta.get_field('parent').rel rel = models.Individual._meta.get_field('parent').rel
@ -631,6 +636,7 @@ class DateTimePickerSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests): class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests): class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@ -686,9 +692,11 @@ class DateTimePickerShortcutsSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase
self.assertGreater(member.birthdate, now - error_margin) self.assertGreater(member.birthdate, now - error_margin)
self.assertLess(member.birthdate, now + error_margin) self.assertLess(member.birthdate, now + error_margin)
class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests): class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests): class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@ -714,7 +722,7 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas
super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp() super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp()
def assertActiveButtons(self, mode, field_name, choose, remove, def assertActiveButtons(self, mode, field_name, choose, remove,
choose_all=None, remove_all=None): choose_all=None, remove_all=None):
choose_link = '#id_%s_add_link' % field_name choose_link = '#id_%s_add_link' % field_name
choose_all_link = '#id_%s_add_all_link' % field_name choose_all_link = '#id_%s_add_all_link' % field_name
remove_link = '#id_%s_remove_link' % field_name remove_link = '#id_%s_remove_link' % field_name
@ -928,9 +936,11 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas
self.assertEqual(list(self.school.alumni.all()), self.assertEqual(list(self.school.alumni.all()),
[self.jason, self.peter]) [self.jason, self.peter])
class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests): class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests): class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@ -1025,9 +1035,11 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'),
'42,98') '42,98')
class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests): class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests): class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@ -1072,8 +1084,10 @@ class RelatedFieldWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
self.assertEqual(len(profiles), 1) self.assertEqual(len(profiles), 1)
self.assertEqual(profiles[0].user.username, username_value) self.assertEqual(profiles[0].user.username, username_value)
class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests): class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests): class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'

View File

@ -12,6 +12,7 @@ class Author(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Publisher(models.Model): class Publisher(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
@ -20,6 +21,7 @@ class Publisher(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Book(models.Model): class Book(models.Model):
isbn = models.CharField(max_length=9) isbn = models.CharField(max_length=9)
@ -35,6 +37,7 @@ class Book(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Store(models.Model): class Store(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)

View File

@ -61,6 +61,7 @@ class Store(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class Entries(models.Model): class Entries(models.Model):
EntryID = models.AutoField(primary_key=True, db_column='Entry ID') EntryID = models.AutoField(primary_key=True, db_column='Entry ID')
Entry = models.CharField(unique=True, max_length=50) Entry = models.CharField(unique=True, max_length=50)
@ -69,7 +70,7 @@ class Entries(models.Model):
class Clues(models.Model): class Clues(models.Model):
ID = models.AutoField(primary_key=True) ID = models.AutoField(primary_key=True)
EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column = 'Entry ID') EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column='Entry ID')
Clue = models.CharField(max_length=150) Clue = models.CharField(max_length=150)
@ -88,13 +89,16 @@ class HardbackBook(Book):
def __str__(self): def __str__(self):
return "%s (hardback): %s" % (self.name, self.weight) return "%s (hardback): %s" % (self.name, self.weight)
# Models for ticket #21150 # Models for ticket #21150
class Alfa(models.Model): class Alfa(models.Model):
name = models.CharField(max_length=10, null=True) name = models.CharField(max_length=10, null=True)
class Bravo(models.Model): class Bravo(models.Model):
pass pass
class Charlie(models.Model): class Charlie(models.Model):
alfa = models.ForeignKey(Alfa, null=True) alfa = models.ForeignKey(Alfa, null=True)
bravo = models.ForeignKey(Bravo, null=True) bravo = models.ForeignKey(Bravo, null=True)

View File

@ -432,6 +432,7 @@ class EscapingChecks(TestCase):
# response should be an non-zero integer # response should be an non-zero integer
self.assertTrue(int(response)) self.assertTrue(int(response))
@override_settings(DEBUG=True) @override_settings(DEBUG=True)
class EscapingChecksDebug(EscapingChecks): class EscapingChecksDebug(EscapingChecks):
pass pass
@ -509,12 +510,12 @@ class BackendTestCase(TestCase):
def test_cursor_executemany(self): def test_cursor_executemany(self):
#4896: Test cursor.executemany #4896: Test cursor.executemany
args = [(i, i**2) for i in range(-5, 6)] args = [(i, i ** 2) for i in range(-5, 6)]
self.create_squares_with_executemany(args) self.create_squares_with_executemany(args)
self.assertEqual(models.Square.objects.count(), 11) self.assertEqual(models.Square.objects.count(), 11)
for i in range(-5, 6): for i in range(-5, 6):
square = models.Square.objects.get(root=i) square = models.Square.objects.get(root=i)
self.assertEqual(square.square, i**2) self.assertEqual(square.square, i ** 2)
def test_cursor_executemany_with_empty_params_list(self): def test_cursor_executemany_with_empty_params_list(self):
#4765: executemany with params=[] does nothing #4765: executemany with params=[] does nothing
@ -524,11 +525,11 @@ class BackendTestCase(TestCase):
def test_cursor_executemany_with_iterator(self): def test_cursor_executemany_with_iterator(self):
#10320: executemany accepts iterators #10320: executemany accepts iterators
args = iter((i, i**2) for i in range(-3, 2)) args = iter((i, i ** 2) for i in range(-3, 2))
self.create_squares_with_executemany(args) self.create_squares_with_executemany(args)
self.assertEqual(models.Square.objects.count(), 5) self.assertEqual(models.Square.objects.count(), 5)
args = iter((i, i**2) for i in range(3, 7)) args = iter((i, i ** 2) for i in range(3, 7))
with override_settings(DEBUG=True): with override_settings(DEBUG=True):
# same test for DebugCursorWrapper # same test for DebugCursorWrapper
self.create_squares_with_executemany(args) self.create_squares_with_executemany(args)
@ -544,20 +545,20 @@ class BackendTestCase(TestCase):
@skipUnlessDBFeature('supports_paramstyle_pyformat') @skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_cursor_executemany_with_pyformat(self): def test_cursor_executemany_with_pyformat(self):
#10070: Support pyformat style passing of paramters #10070: Support pyformat style passing of paramters
args = [{'root': i, 'square': i**2} for i in range(-5, 6)] args = [{'root': i, 'square': i ** 2} for i in range(-5, 6)]
self.create_squares(args, 'pyformat', multiple=True) self.create_squares(args, 'pyformat', multiple=True)
self.assertEqual(models.Square.objects.count(), 11) self.assertEqual(models.Square.objects.count(), 11)
for i in range(-5, 6): for i in range(-5, 6):
square = models.Square.objects.get(root=i) square = models.Square.objects.get(root=i)
self.assertEqual(square.square, i**2) self.assertEqual(square.square, i ** 2)
@skipUnlessDBFeature('supports_paramstyle_pyformat') @skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_cursor_executemany_with_pyformat_iterator(self): def test_cursor_executemany_with_pyformat_iterator(self):
args = iter({'root': i, 'square': i**2} for i in range(-3, 2)) args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2))
self.create_squares(args, 'pyformat', multiple=True) self.create_squares(args, 'pyformat', multiple=True)
self.assertEqual(models.Square.objects.count(), 5) self.assertEqual(models.Square.objects.count(), 5)
args = iter({'root': i, 'square': i**2} for i in range(3, 7)) args = iter({'root': i, 'square': i ** 2} for i in range(3, 7))
with override_settings(DEBUG=True): with override_settings(DEBUG=True):
# same test for DebugCursorWrapper # same test for DebugCursorWrapper
self.create_squares(args, 'pyformat', multiple=True) self.create_squares(args, 'pyformat', multiple=True)
@ -987,6 +988,7 @@ class BackendUtilTests(TestCase):
equal('0.1234567890', 12, 0, equal('0.1234567890', 12, 0,
'0') '0')
@unittest.skipUnless( @unittest.skipUnless(
connection.vendor == 'postgresql', connection.vendor == 'postgresql',
"This test applies only to PostgreSQL") "This test applies only to PostgreSQL")

View File

@ -19,11 +19,13 @@ class Article(models.Model):
def __str__(self): def __str__(self):
return self.headline return self.headline
class ArticleSelectOnSave(Article): class ArticleSelectOnSave(Article):
class Meta: class Meta:
proxy = True proxy = True
select_on_save = True select_on_save = True
@python_2_unicode_compatible @python_2_unicode_compatible
class SelfRef(models.Model): class SelfRef(models.Model):
selfref = models.ForeignKey('self', null=True, blank=True, selfref = models.ForeignKey('self', null=True, blank=True,

View File

@ -87,7 +87,8 @@ class ModelTest(TestCase):
# Django raises an Article.DoesNotExist exception for get() if the # Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object. # parameters don't match any object.
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
ObjectDoesNotExist, ObjectDoesNotExist,
"Article matching query does not exist.", "Article matching query does not exist.",
Article.objects.get, Article.objects.get,
@ -102,7 +103,8 @@ class ModelTest(TestCase):
pub_date__month=8, pub_date__month=8,
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
ObjectDoesNotExist, ObjectDoesNotExist,
"Article matching query does not exist.", "Article matching query does not exist.",
Article.objects.get, Article.objects.get,
@ -135,21 +137,24 @@ class ModelTest(TestCase):
# Django raises an Article.MultipleObjectsReturned exception if the # Django raises an Article.MultipleObjectsReturned exception if the
# lookup matches more than one object # lookup matches more than one object
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
MultipleObjectsReturned, MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!", "get\(\) returned more than one Article -- it returned 2!",
Article.objects.get, Article.objects.get,
headline__startswith='Area', headline__startswith='Area',
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
MultipleObjectsReturned, MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!", "get\(\) returned more than one Article -- it returned 2!",
Article.objects.get, Article.objects.get,
pub_date__year=2005, pub_date__year=2005,
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
MultipleObjectsReturned, MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!", "get\(\) returned more than one Article -- it returned 2!",
Article.objects.get, Article.objects.get,
@ -165,14 +170,16 @@ class ModelTest(TestCase):
Article(headline='Area %s' % i, pub_date=datetime(2005, 7, 28)) Article(headline='Area %s' % i, pub_date=datetime(2005, 7, 28))
for i in range(MAX_GET_RESULTS) for i in range(MAX_GET_RESULTS)
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
MultipleObjectsReturned, MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned %d!" % MAX_GET_RESULTS, "get\(\) returned more than one Article -- it returned %d!" % MAX_GET_RESULTS,
Article.objects.get, Article.objects.get,
headline__startswith='Area', headline__startswith='Area',
) )
Article.objects.create(headline='Area %s' % MAX_GET_RESULTS, pub_date=datetime(2005, 7, 28)) Article.objects.create(headline='Area %s' % MAX_GET_RESULTS, pub_date=datetime(2005, 7, 28))
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
MultipleObjectsReturned, MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned more than %d!" % MAX_GET_RESULTS, "get\(\) returned more than one Article -- it returned more than %d!" % MAX_GET_RESULTS,
Article.objects.get, Article.objects.get,
@ -219,7 +226,8 @@ class ModelTest(TestCase):
self.assertEqual(a4.headline, 'Fourth article') self.assertEqual(a4.headline, 'Fourth article')
# Don't use invalid keyword arguments. # Don't use invalid keyword arguments.
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
TypeError, TypeError,
"'foo' is an invalid keyword argument for this function", "'foo' is an invalid keyword argument for this function",
Article, Article,
@ -315,7 +323,8 @@ class ModelTest(TestCase):
Article.objects.dates, Article.objects.dates,
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
FieldDoesNotExist, FieldDoesNotExist,
"Article has no field named 'invalid_field'", "Article has no field named 'invalid_field'",
Article.objects.dates, Article.objects.dates,
@ -323,7 +332,8 @@ class ModelTest(TestCase):
"year", "year",
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
AssertionError, AssertionError,
"'kind' must be one of 'year', 'month' or 'day'.", "'kind' must be one of 'year', 'month' or 'day'.",
Article.objects.dates, Article.objects.dates,
@ -331,7 +341,8 @@ class ModelTest(TestCase):
"bad_kind", "bad_kind",
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
AssertionError, AssertionError,
"'order' must be either 'ASC' or 'DESC'.", "'order' must be either 'ASC' or 'DESC'.",
Article.objects.dates, Article.objects.dates,
@ -419,14 +430,16 @@ class ModelTest(TestCase):
"<Article: Updated article 8>"]) "<Article: Updated article 8>"])
# Also, once you have sliced you can't filter, re-order or combine # Also, once you have sliced you can't filter, re-order or combine
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
AssertionError, AssertionError,
"Cannot filter a query once a slice has been taken.", "Cannot filter a query once a slice has been taken.",
Article.objects.all()[0:5].filter, Article.objects.all()[0:5].filter,
id=a.id, id=a.id,
) )
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
AssertionError, AssertionError,
"Cannot reorder a query once a slice has been taken.", "Cannot reorder a query once a slice has been taken.",
Article.objects.all()[0:5].order_by, Article.objects.all()[0:5].order_by,
@ -461,7 +474,8 @@ class ModelTest(TestCase):
# An Article instance doesn't have access to the "objects" attribute. # An Article instance doesn't have access to the "objects" attribute.
# That's only available on the class. # That's only available on the class.
six.assertRaisesRegex(self, six.assertRaisesRegex(
self,
AttributeError, AttributeError,
"Manager isn't accessible via Article instances", "Manager isn't accessible via Article instances",
getattr, getattr,
@ -605,8 +619,8 @@ class ModelTest(TestCase):
) )
dicts = Article.objects.filter( dicts = Article.objects.filter(
pub_date__year=2008).extra(select={'dashed-value': '1'} pub_date__year=2008).extra(
).values('headline', 'dashed-value') select={'dashed-value': '1'}).values('headline', 'dashed-value')
self.assertEqual([sorted(d.items()) for d in dicts], self.assertEqual([sorted(d.items()) for d in dicts],
[[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]]) [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]])
@ -723,6 +737,7 @@ class ModelTest(TestCase):
# hash) # hash)
hash(Article()) hash(Article())
class ConcurrentSaveTests(TransactionTestCase): class ConcurrentSaveTests(TransactionTestCase):
available_apps = ['basic'] available_apps = ['basic']
@ -808,6 +823,7 @@ class ManagerTest(TestCase):
sorted(self.QUERYSET_PROXY_METHODS), sorted(self.QUERYSET_PROXY_METHODS),
) )
class SelectOnSaveTests(TestCase): class SelectOnSaveTests(TestCase):
def test_select_on_save(self): def test_select_on_save(self):
a1 = Article.objects.create(pub_date=datetime.now()) a1 = Article.objects.create(pub_date=datetime.now())

View File

@ -8,6 +8,7 @@ from django.forms import ModelForm
temp_storage_dir = tempfile.mkdtemp() temp_storage_dir = tempfile.mkdtemp()
temp_storage = FileSystemStorage(temp_storage_dir) temp_storage = FileSystemStorage(temp_storage_dir)
class Photo(models.Model): class Photo(models.Model):
title = models.CharField(max_length=30) title = models.CharField(max_length=30)
image = models.FileField(storage=temp_storage, upload_to='tests') image = models.FileField(storage=temp_storage, upload_to='tests')
@ -22,6 +23,7 @@ class Photo(models.Model):
super(Photo, self).save(force_insert, force_update) super(Photo, self).save(force_insert, force_update)
self._savecount += 1 self._savecount += 1
class PhotoForm(ModelForm): class PhotoForm(ModelForm):
class Meta: class Meta:
model = Photo model = Photo

View File

@ -5,21 +5,26 @@ class Country(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
iso_two_letter = models.CharField(max_length=2) iso_two_letter = models.CharField(max_length=2)
class Place(models.Model): class Place(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Meta: class Meta:
abstract = True abstract = True
class Restaurant(Place): class Restaurant(Place):
pass pass
class Pizzeria(Restaurant): class Pizzeria(Restaurant):
pass pass
class State(models.Model): class State(models.Model):
two_letter_code = models.CharField(max_length=2, primary_key=True) two_letter_code = models.CharField(max_length=2, primary_key=True)
class TwoFields(models.Model): class TwoFields(models.Model):
f1 = models.IntegerField(unique=True) f1 = models.IntegerField(unique=True)
f2 = models.IntegerField(unique=True) f2 = models.IntegerField(unique=True)

View File

@ -7,5 +7,6 @@ class CloseHookMixin(object):
def close(self, **kwargs): def close(self, **kwargs):
self.closed = True self.closed = True
class CacheClass(CloseHookMixin, LocMemCache): class CacheClass(CloseHookMixin, LocMemCache):
pass pass

View File

@ -5,5 +5,6 @@ class LiberalKeyValidationMixin(object):
def validate_key(self, key): def validate_key(self, key):
pass pass
class CacheClass(LiberalKeyValidationMixin, LocMemCache): class CacheClass(LiberalKeyValidationMixin, LocMemCache):
pass pass

View File

@ -7,6 +7,7 @@ def expensive_calculation():
expensive_calculation.num_runs += 1 expensive_calculation.num_runs += 1
return timezone.now() return timezone.now()
class Poll(models.Model): class Poll(models.Model):
question = models.CharField(max_length=200) question = models.CharField(max_length=200)
answer = models.CharField(max_length=200) answer = models.CharField(max_length=200)

View File

@ -40,10 +40,12 @@ from django.views.decorators.cache import cache_page
from .models import Poll, expensive_calculation from .models import Poll, expensive_calculation
# functions/classes for complex data type tests # functions/classes for complex data type tests
def f(): def f():
return 42 return 42
class C: class C:
def m(n): def m(n):
return 24 return 24
@ -823,6 +825,7 @@ class BaseCacheTests(object):
self.assertEqual(get_cache_data.content, content.encode('utf-8')) self.assertEqual(get_cache_data.content, content.encode('utf-8'))
self.assertEqual(get_cache_data.cookies, response.cookies) self.assertEqual(get_cache_data.cookies, response.cookies)
def custom_key_func(key, key_prefix, version): def custom_key_func(key, key_prefix, version):
"A customized cache key function" "A customized cache key function"
return 'CUSTOM-' + '-'.join([key_prefix, str(version), key]) return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
@ -1004,6 +1007,7 @@ class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
self.cache.decr(key) self.cache.decr(key)
self.assertEqual(expire, self.cache._expire_info[_key]) self.assertEqual(expire, self.cache._expire_info[_key])
# memcached backend isn't guaranteed to be available. # memcached backend isn't guaranteed to be available.
# To check the memcached backend, the test settings file will # To check the memcached backend, the test settings file will
# need to contain at least one cache backend setting that points at # need to contain at least one cache backend setting that points at
@ -1581,6 +1585,7 @@ class CacheI18nTest(TestCase):
get_cache_data = FetchFromCacheMiddleware().process_request(request) get_cache_data = FetchFromCacheMiddleware().process_request(request)
self.assertIsNone(get_cache_data) self.assertIsNone(get_cache_data)
@override_settings( @override_settings(
CACHES={ CACHES={
'default': { 'default': {
@ -1816,6 +1821,7 @@ class CacheMiddlewareTest(IgnoreDeprecationWarningsMixin, TestCase):
response = other_with_prefix_view(request, '16') response = other_with_prefix_view(request, '16')
self.assertEqual(response.content, b'Hello World 16') self.assertEqual(response.content, b'Hello World 16')
@override_settings( @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix', CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=1, CACHE_MIDDLEWARE_SECONDS=1,

View File

@ -1,9 +1,11 @@
from django.db import models from django.db import models
class Book(models.Model): class Book(models.Model):
title = models.CharField(max_length=250) title = models.CharField(max_length=250)
is_published = models.BooleanField(default=False) is_published = models.BooleanField(default=False)
class BlogPost(models.Model): class BlogPost(models.Model):
title = models.CharField(max_length=250) title = models.CharField(max_length=250)
is_published = models.BooleanField(default=False) is_published = models.BooleanField(default=False)

View File

@ -7,6 +7,7 @@ from django.test import TestCase
from .models import Book from .models import Book
class StubCheckModule(object): class StubCheckModule(object):
# Has no ``run_checks`` attribute & will trigger a warning. # Has no ``run_checks`` attribute & will trigger a warning.
__name__ = 'StubCheckModule' __name__ = 'StubCheckModule'

View File

@ -18,6 +18,7 @@ GENDER_CHOICES = (
('F', 'Female'), ('F', 'Female'),
) )
@python_2_unicode_compatible @python_2_unicode_compatible
class Person(models.Model): class Person(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)

View File

@ -58,6 +58,7 @@ class TestRouter(object):
def allow_migrate(self, db, model): def allow_migrate(self, db, model):
return False return False
class SQLCommandsRouterTestCase(TestCase): class SQLCommandsRouterTestCase(TestCase):
def setUp(self): def setUp(self):
self._old_routers = router.routers self._old_routers = router.routers

View File

@ -15,6 +15,7 @@ EXPIRED_LAST_MODIFIED_STR = 'Sat, 20 Oct 2007 23:21:47 GMT'
ETAG = 'b4246ffc4f62314ca13147c9d4f76974' ETAG = 'b4246ffc4f62314ca13147c9d4f76974'
EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6' EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6'
class ConditionalGet(TestCase): class ConditionalGet(TestCase):
urls = 'conditional_processing.urls' urls = 'conditional_processing.urls'

View File

@ -8,18 +8,22 @@ def index(request):
return HttpResponse(FULL_RESPONSE) return HttpResponse(FULL_RESPONSE)
index = condition(lambda r: ETAG, lambda r: LAST_MODIFIED)(index) index = condition(lambda r: ETAG, lambda r: LAST_MODIFIED)(index)
def last_modified_view1(request): def last_modified_view1(request):
return HttpResponse(FULL_RESPONSE) return HttpResponse(FULL_RESPONSE)
last_modified_view1 = condition(last_modified_func=lambda r: LAST_MODIFIED)(last_modified_view1) last_modified_view1 = condition(last_modified_func=lambda r: LAST_MODIFIED)(last_modified_view1)
def last_modified_view2(request): def last_modified_view2(request):
return HttpResponse(FULL_RESPONSE) return HttpResponse(FULL_RESPONSE)
last_modified_view2 = last_modified(lambda r: LAST_MODIFIED)(last_modified_view2) last_modified_view2 = last_modified(lambda r: LAST_MODIFIED)(last_modified_view2)
def etag_view1(request): def etag_view1(request):
return HttpResponse(FULL_RESPONSE) return HttpResponse(FULL_RESPONSE)
etag_view1 = condition(etag_func=lambda r: ETAG)(etag_view1) etag_view1 = condition(etag_func=lambda r: ETAG)(etag_view1)
def etag_view2(request): def etag_view2(request):
return HttpResponse(FULL_RESPONSE) return HttpResponse(FULL_RESPONSE)
etag_view2 = etag(lambda r: ETAG)(etag_view2) etag_view2 = etag(lambda r: ETAG)(etag_view2)

View File

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from django.db import models from django.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class Author(models.Model): class Author(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -13,6 +14,7 @@ class Author(models.Model):
def get_absolute_url(self): def get_absolute_url(self):
return '/views/authors/%s/' % self.id return '/views/authors/%s/' % self.id
@python_2_unicode_compatible @python_2_unicode_compatible
class Article(models.Model): class Article(models.Model):
title = models.CharField(max_length=100) title = models.CharField(max_length=100)

View File

@ -5,6 +5,7 @@ from django.test import TestCase
from .models import Author, Article from .models import Author, Article
class ContentTypesViewsTests(TestCase): class ContentTypesViewsTests(TestCase):
fixtures = ['testdata.json'] fixtures = ['testdata.json']
urls = 'contenttypes_tests.urls' urls = 'contenttypes_tests.urls'

View File

@ -19,10 +19,12 @@ def post_form_response():
""", mimetype="text/html") """, mimetype="text/html")
return resp return resp
def post_form_view(request): def post_form_view(request):
"""A view that returns a POST form (without a token)""" """A view that returns a POST form (without a token)"""
return post_form_response() return post_form_response()
# Response/views used for template tag tests # Response/views used for template tag tests
def token_view(request): def token_view(request):
@ -31,6 +33,7 @@ def token_view(request):
template = Template("{% csrf_token %}") template = Template("{% csrf_token %}")
return HttpResponse(template.render(context)) return HttpResponse(template.render(context))
def non_token_view_using_request_processor(request): def non_token_view_using_request_processor(request):
""" """
A view that doesn't use the token, but does use the csrf view processor. A view that doesn't use the token, but does use the csrf view processor.
@ -39,6 +42,7 @@ def non_token_view_using_request_processor(request):
template = Template("") template = Template("")
return HttpResponse(template.render(context)) return HttpResponse(template.render(context))
class TestingHttpRequest(HttpRequest): class TestingHttpRequest(HttpRequest):
""" """
A version of HttpRequest that allows us to change some things A version of HttpRequest that allows us to change some things
@ -47,6 +51,7 @@ class TestingHttpRequest(HttpRequest):
def is_secure(self): def is_secure(self):
return getattr(self, '_is_secure_override', False) return getattr(self, '_is_secure_override', False)
class CsrfViewMiddlewareTest(TestCase): class CsrfViewMiddlewareTest(TestCase):
# The csrf token is potentially from an untrusted source, so could have # The csrf token is potentially from an untrusted source, so could have
# characters that need dealing with. # characters that need dealing with.

View File

@ -33,6 +33,7 @@ class Author(models.Model):
db_table = 'my_author_table' db_table = 'my_author_table'
ordering = ('last_name', 'first_name') ordering = ('last_name', 'first_name')
@python_2_unicode_compatible @python_2_unicode_compatible
class Article(models.Model): class Article(models.Model):
headline = models.CharField(max_length=100) headline = models.CharField(max_length=100)

View File

@ -24,6 +24,7 @@ class Article(models.Model):
class Meta: class Meta:
ordering = ('headline',) ordering = ('headline',)
@python_2_unicode_compatible @python_2_unicode_compatible
class Author(models.Model): class Author(models.Model):
Author_ID = models.AutoField(primary_key=True, db_column='Author ID') Author_ID = models.AutoField(primary_key=True, db_column='Author ID')

View File

@ -10,6 +10,7 @@ def pks(objects):
""" Return pks to be able to compare lists""" """ Return pks to be able to compare lists"""
return [o.pk for o in objects] return [o.pk for o in objects]
class CustomColumnRegression(TestCase): class CustomColumnRegression(TestCase):
def setUp(self): def setUp(self):

View File

@ -17,18 +17,21 @@ from django.utils.encoding import python_2_unicode_compatible
# An example of a custom manager called "objects". # An example of a custom manager called "objects".
class PersonManager(models.Manager): class PersonManager(models.Manager):
def get_fun_people(self): def get_fun_people(self):
return self.filter(fun=True) return self.filter(fun=True)
# An example of a custom manager that sets get_queryset(). # An example of a custom manager that sets get_queryset().
class PublishedBookManager(models.Manager): class PublishedBookManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(PublishedBookManager, self).get_queryset().filter(is_published=True) return super(PublishedBookManager, self).get_queryset().filter(is_published=True)
# An example of a custom queryset that copies its methods onto the manager. # An example of a custom queryset that copies its methods onto the manager.
class CustomQuerySet(models.QuerySet): class CustomQuerySet(models.QuerySet):
def filter(self, *args, **kwargs): def filter(self, *args, **kwargs):
queryset = super(CustomQuerySet, self).filter(fun=True) queryset = super(CustomQuerySet, self).filter(fun=True)
@ -49,6 +52,7 @@ class CustomQuerySet(models.QuerySet):
return self.all() return self.all()
_optin_private_method.queryset_only = False _optin_private_method.queryset_only = False
class BaseCustomManager(models.Manager): class BaseCustomManager(models.Manager):
def __init__(self, arg): def __init__(self, arg):
super(BaseCustomManager, self).__init__() super(BaseCustomManager, self).__init__()
@ -64,14 +68,17 @@ class BaseCustomManager(models.Manager):
CustomManager = BaseCustomManager.from_queryset(CustomQuerySet) CustomManager = BaseCustomManager.from_queryset(CustomQuerySet)
class FunPeopleManager(models.Manager): class FunPeopleManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(FunPeopleManager, self).get_queryset().filter(fun=True) return super(FunPeopleManager, self).get_queryset().filter(fun=True)
class BoringPeopleManager(models.Manager): class BoringPeopleManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(BoringPeopleManager, self).get_queryset().filter(fun=False) return super(BoringPeopleManager, self).get_queryset().filter(fun=False)
@python_2_unicode_compatible @python_2_unicode_compatible
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(max_length=30) first_name = models.CharField(max_length=30)
@ -93,6 +100,7 @@ class Person(models.Model):
def __str__(self): def __str__(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)
@python_2_unicode_compatible @python_2_unicode_compatible
class Book(models.Model): class Book(models.Model):
title = models.CharField(max_length=50) title = models.CharField(max_length=50)
@ -109,10 +117,12 @@ class Book(models.Model):
# An example of providing multiple custom managers. # An example of providing multiple custom managers.
class FastCarManager(models.Manager): class FastCarManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(FastCarManager, self).get_queryset().filter(top_speed__gt=150) return super(FastCarManager, self).get_queryset().filter(top_speed__gt=150)
@python_2_unicode_compatible @python_2_unicode_compatible
class Car(models.Model): class Car(models.Model):
name = models.CharField(max_length=10) name = models.CharField(max_length=10)

View File

@ -13,6 +13,7 @@ class RestrictedManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(RestrictedManager, self).get_queryset().filter(is_public=True) return super(RestrictedManager, self).get_queryset().filter(is_public=True)
@python_2_unicode_compatible @python_2_unicode_compatible
class RelatedModel(models.Model): class RelatedModel(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
@ -20,6 +21,7 @@ class RelatedModel(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class RestrictedModel(models.Model): class RestrictedModel(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
@ -32,6 +34,7 @@ class RestrictedModel(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class OneToOneRestrictedModel(models.Model): class OneToOneRestrictedModel(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)

View File

@ -22,6 +22,7 @@ class MyWrapper(object):
return self.value == other.value return self.value == other.value
return self.value == other return self.value == other
class MyAutoField(six.with_metaclass(models.SubfieldBase, models.CharField)): class MyAutoField(six.with_metaclass(models.SubfieldBase, models.CharField)):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

View File

@ -16,7 +16,7 @@ from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class Employee(models.Model): class Employee(models.Model):
employee_code = models.IntegerField(primary_key=True, db_column = 'code') employee_code = models.IntegerField(primary_key=True, db_column='code')
first_name = models.CharField(max_length=20) first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20)
@ -26,6 +26,7 @@ class Employee(models.Model):
def __str__(self): def __str__(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)
@python_2_unicode_compatible @python_2_unicode_compatible
class Business(models.Model): class Business(models.Model):
name = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=20, primary_key=True)
@ -37,6 +38,7 @@ class Business(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Bar(models.Model): class Bar(models.Model):
id = MyAutoField(primary_key=True, db_index=True) id = MyAutoField(primary_key=True, db_index=True)

View File

@ -23,6 +23,7 @@ class Donut(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class RumBaba(models.Model): class RumBaba(models.Model):
baked_date = models.DateField(auto_now_add=True) baked_date = models.DateField(auto_now_add=True)
baked_timestamp = models.DateTimeField(auto_now_add=True) baked_timestamp = models.DateTimeField(auto_now_add=True)

View File

@ -14,6 +14,7 @@ class Article(models.Model):
def __str__(self): def __str__(self):
return self.title return self.title
@python_2_unicode_compatible @python_2_unicode_compatible
class Comment(models.Model): class Comment(models.Model):
article = models.ForeignKey(Article, related_name="comments") article = models.ForeignKey(Article, related_name="comments")
@ -24,5 +25,6 @@ class Comment(models.Model):
def __str__(self): def __str__(self):
return 'Comment to %s (%s)' % (self.article.title, self.pub_date) return 'Comment to %s (%s)' % (self.article.title, self.pub_date)
class Category(models.Model): class Category(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)

View File

@ -14,6 +14,7 @@ class Article(models.Model):
def __str__(self): def __str__(self):
return self.title return self.title
@python_2_unicode_compatible @python_2_unicode_compatible
class Comment(models.Model): class Comment(models.Model):
article = models.ForeignKey(Article, related_name="comments") article = models.ForeignKey(Article, related_name="comments")
@ -24,5 +25,6 @@ class Comment(models.Model):
def __str__(self): def __str__(self):
return 'Comment to %s (%s)' % (self.article.title, self.pub_date) return 'Comment to %s (%s)' % (self.article.title, self.pub_date)
class Category(models.Model): class Category(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)

View File

@ -48,6 +48,7 @@ TEST_CASES = {
), ),
} }
class DBTypeCasts(unittest.TestCase): class DBTypeCasts(unittest.TestCase):
def test_typeCasts(self): def test_typeCasts(self):
for k, v in six.iteritems(TEST_CASES): for k, v in six.iteritems(TEST_CASES):

View File

@ -245,6 +245,7 @@ class DeferRegressionTest(TestCase):
new_class.__name__, new_class.__name__,
'Item_Deferred_this_is_some_very_long_attribute_nac34b1f495507dad6b02e2cb235c875e') 'Item_Deferred_this_is_some_very_long_attribute_nac34b1f495507dad6b02e2cb235c875e')
class DeferAnnotateSelectRelatedTest(TestCase): class DeferAnnotateSelectRelatedTest(TestCase):
def test_defer_annotate_select_related(self): def test_defer_annotate_select_related(self):
location = Location.objects.create() location = Location.objects.create()

View File

@ -109,20 +109,26 @@ class HiddenUser(models.Model):
class HiddenUserProfile(models.Model): class HiddenUserProfile(models.Model):
user = models.ForeignKey(HiddenUser) user = models.ForeignKey(HiddenUser)
class M2MTo(models.Model): class M2MTo(models.Model):
pass pass
class M2MFrom(models.Model): class M2MFrom(models.Model):
m2m = models.ManyToManyField(M2MTo) m2m = models.ManyToManyField(M2MTo)
class Parent(models.Model): class Parent(models.Model):
pass pass
class Child(Parent): class Child(Parent):
pass pass
class Base(models.Model): class Base(models.Model):
pass pass
class RelToBase(models.Model): class RelToBase(models.Model):
base = models.ForeignKey(Base, on_delete=models.DO_NOTHING) base = models.ForeignKey(Base, on_delete=models.DO_NOTHING)

View File

@ -167,7 +167,7 @@ class DeletionTests(TestCase):
def test_bulk(self): def test_bulk(self):
from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE
s = S.objects.create(r=R.objects.create()) s = S.objects.create(r=R.objects.create())
for i in xrange(2*GET_ITERATOR_CHUNK_SIZE): for i in xrange(2 * GET_ITERATOR_CHUNK_SIZE):
T.objects.create(s=s) T.objects.create(s=s)
# 1 (select related `T` instances) # 1 (select related `T` instances)
# + 1 (select related `U` instances) # + 1 (select related `U` instances)
@ -311,6 +311,7 @@ class DeletionTests(TestCase):
r.delete() r.delete()
self.assertEqual(HiddenUserProfile.objects.count(), 0) self.assertEqual(HiddenUserProfile.objects.count(), 0)
class FastDeleteTests(TestCase): class FastDeleteTests(TestCase):
def test_fast_delete_fk(self): def test_fast_delete_fk(self):

View File

@ -2,51 +2,64 @@ from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.db import models from django.db import models
class Award(models.Model): class Award(models.Model):
name = models.CharField(max_length=25) name = models.CharField(max_length=25)
object_id = models.PositiveIntegerField() object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
content_object = generic.GenericForeignKey() content_object = generic.GenericForeignKey()
class AwardNote(models.Model): class AwardNote(models.Model):
award = models.ForeignKey(Award) award = models.ForeignKey(Award)
note = models.CharField(max_length=100) note = models.CharField(max_length=100)
class Person(models.Model): class Person(models.Model):
name = models.CharField(max_length=25) name = models.CharField(max_length=25)
awards = generic.GenericRelation(Award) awards = generic.GenericRelation(Award)
class Book(models.Model): class Book(models.Model):
pagecount = models.IntegerField() pagecount = models.IntegerField()
class Toy(models.Model): class Toy(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
class Child(models.Model): class Child(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
toys = models.ManyToManyField(Toy, through='PlayedWith') toys = models.ManyToManyField(Toy, through='PlayedWith')
class PlayedWith(models.Model): class PlayedWith(models.Model):
child = models.ForeignKey(Child) child = models.ForeignKey(Child)
toy = models.ForeignKey(Toy) toy = models.ForeignKey(Toy)
date = models.DateField(db_column='date_col') date = models.DateField(db_column='date_col')
class PlayedWithNote(models.Model): class PlayedWithNote(models.Model):
played = models.ForeignKey(PlayedWith) played = models.ForeignKey(PlayedWith)
note = models.TextField() note = models.TextField()
class Contact(models.Model): class Contact(models.Model):
label = models.CharField(max_length=100) label = models.CharField(max_length=100)
class Email(Contact): class Email(Contact):
email_address = models.EmailField(max_length=100) email_address = models.EmailField(max_length=100)
class Researcher(models.Model): class Researcher(models.Model):
contacts = models.ManyToManyField(Contact, related_name="research_contacts") contacts = models.ManyToManyField(Contact, related_name="research_contacts")
class Food(models.Model): class Food(models.Model):
name = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=20, unique=True)
class Eaten(models.Model): class Eaten(models.Model):
food = models.ForeignKey(Food, to_field="name") food = models.ForeignKey(Food, to_field="name")
meal = models.CharField(max_length=20) meal = models.CharField(max_length=20)
@ -54,55 +67,70 @@ class Eaten(models.Model):
# Models for #15776 # Models for #15776
class Policy(models.Model): class Policy(models.Model):
policy_number = models.CharField(max_length=10) policy_number = models.CharField(max_length=10)
class Version(models.Model): class Version(models.Model):
policy = models.ForeignKey(Policy) policy = models.ForeignKey(Policy)
class Location(models.Model): class Location(models.Model):
version = models.ForeignKey(Version, blank=True, null=True) version = models.ForeignKey(Version, blank=True, null=True)
class Item(models.Model): class Item(models.Model):
version = models.ForeignKey(Version) version = models.ForeignKey(Version)
location = models.ForeignKey(Location, blank=True, null=True) location = models.ForeignKey(Location, blank=True, null=True)
# Models for #16128 # Models for #16128
class File(models.Model): class File(models.Model):
pass pass
class Image(File): class Image(File):
class Meta: class Meta:
proxy = True proxy = True
class Photo(Image): class Photo(Image):
class Meta: class Meta:
proxy = True proxy = True
class FooImage(models.Model): class FooImage(models.Model):
my_image = models.ForeignKey(Image) my_image = models.ForeignKey(Image)
class FooFile(models.Model): class FooFile(models.Model):
my_file = models.ForeignKey(File) my_file = models.ForeignKey(File)
class FooPhoto(models.Model): class FooPhoto(models.Model):
my_photo = models.ForeignKey(Photo) my_photo = models.ForeignKey(Photo)
class FooFileProxy(FooFile): class FooFileProxy(FooFile):
class Meta: class Meta:
proxy = True proxy = True
class OrgUnit(models.Model): class OrgUnit(models.Model):
name = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=64, unique=True)
class Login(models.Model): class Login(models.Model):
description = models.CharField(max_length=32) description = models.CharField(max_length=32)
orgunit = models.ForeignKey(OrgUnit) orgunit = models.ForeignKey(OrgUnit)
class House(models.Model): class House(models.Model):
address = models.CharField(max_length=32) address = models.CharField(max_length=32)
class OrderedPerson(models.Model): class OrderedPerson(models.Model):
name = models.CharField(max_length=32) name = models.CharField(max_length=32)
lives_in = models.ForeignKey(House) lives_in = models.ForeignKey(House)

View File

@ -146,7 +146,7 @@ class LargeDeleteTests(TestCase):
def test_large_deletes(self): def test_large_deletes(self):
"Regression for #13309 -- if the number of objects > chunk size, deletion still occurs" "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs"
for x in range(300): for x in range(300):
Book.objects.create(pagecount=x+100) Book.objects.create(pagecount=x + 100)
# attach a signal to make sure we will not fast-delete # attach a signal to make sure we will not fast-delete
def noop(*args, **kwargs): def noop(*args, **kwargs):
@ -268,6 +268,7 @@ class ProxyDeleteTest(TestCase):
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
Image.objects.values_list().delete() Image.objects.values_list().delete()
class Ticket19102Tests(TestCase): class Ticket19102Tests(TestCase):
""" """
Test different queries which alter the SELECT clause of the query. We Test different queries which alter the SELECT clause of the query. We

View File

@ -23,9 +23,11 @@ else:
def garbage_collect(): def garbage_collect():
gc.collect() gc.collect()
def receiver_1_arg(val, **kwargs): def receiver_1_arg(val, **kwargs):
return val return val
class Callable(object): class Callable(object):
def __call__(self, val, **kwargs): def __call__(self, val, **kwargs):
return val return val
@ -116,10 +118,10 @@ class DispatcherTests(unittest.TestCase):
def uid_based_receiver_2(**kwargs): def uid_based_receiver_2(**kwargs):
pass pass
a_signal.connect(uid_based_receiver_1, dispatch_uid = "uid") a_signal.connect(uid_based_receiver_1, dispatch_uid="uid")
a_signal.connect(uid_based_receiver_2, dispatch_uid = "uid") a_signal.connect(uid_based_receiver_2, dispatch_uid="uid")
self.assertEqual(len(a_signal.receivers), 1) self.assertEqual(len(a_signal.receivers), 1)
a_signal.disconnect(dispatch_uid = "uid") a_signal.disconnect(dispatch_uid="uid")
self._testIsClean(a_signal) self._testIsClean(a_signal)
def testRobust(self): def testRobust(self):

View File

@ -3,17 +3,21 @@ import unittest
from django.dispatch.saferef import safeRef from django.dispatch.saferef import safeRef
from django.utils.six.moves import xrange from django.utils.six.moves import xrange
class Test1(object): class Test1(object):
def x(self): def x(self):
pass pass
def test2(obj): def test2(obj):
pass pass
class Test2(object): class Test2(object):
def __call__(self, obj): def __call__(self, obj):
pass pass
class SaferefTests(unittest.TestCase): class SaferefTests(unittest.TestCase):
def setUp(self): def setUp(self):
ts = [] ts = []

View File

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from django.db import models from django.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class Tag(models.Model): class Tag(models.Model):
name = models.CharField(max_length=10) name = models.CharField(max_length=10)
@ -15,6 +16,7 @@ class Tag(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Celebrity(models.Model): class Celebrity(models.Model):
name = models.CharField("Name", max_length=20) name = models.CharField("Name", max_length=20)
@ -23,9 +25,11 @@ class Celebrity(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class Fan(models.Model): class Fan(models.Model):
fan_of = models.ForeignKey(Celebrity) fan_of = models.ForeignKey(Celebrity)
@python_2_unicode_compatible @python_2_unicode_compatible
class Staff(models.Model): class Staff(models.Model):
id = models.IntegerField(primary_key=True) id = models.IntegerField(primary_key=True)
@ -37,6 +41,7 @@ class Staff(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class StaffTag(models.Model): class StaffTag(models.Model):
staff = models.ForeignKey(Staff) staff = models.ForeignKey(Staff)

View File

@ -6,6 +6,7 @@ from django.test.utils import str_prefix
from .models import Tag, Celebrity, Fan, Staff, StaffTag from .models import Tag, Celebrity, Fan, Staff, StaffTag
@skipUnlessDBFeature('can_distinct_on_fields') @skipUnlessDBFeature('can_distinct_on_fields')
class DistinctOnTests(TestCase): class DistinctOnTests(TestCase):
def setUp(self): def setUp(self):
@ -77,7 +78,7 @@ class DistinctOnTests(TestCase):
# Fetch the alphabetically first coworker for each worker # Fetch the alphabetically first coworker for each worker
( (
(Staff.objects.distinct('id').order_by('id', 'coworkers__name'). (Staff.objects.distinct('id').order_by('id', 'coworkers__name').
values_list('id', 'coworkers__name')), values_list('id', 'coworkers__name')),
[str_prefix("(1, %(_)s'p2')"), str_prefix("(2, %(_)s'p1')"), [str_prefix("(1, %(_)s'p2')"), str_prefix("(2, %(_)s'p1')"),
str_prefix("(3, %(_)s'p1')"), "(4, None)"] str_prefix("(3, %(_)s'p1')"), "(4, None)"]
), ),

View File

@ -15,6 +15,7 @@ class Employee(models.Model):
def __str__(self): def __str__(self):
return '%s %s' % (self.firstname, self.lastname) return '%s %s' % (self.firstname, self.lastname)
@python_2_unicode_compatible @python_2_unicode_compatible
class Company(models.Model): class Company(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)

View File

@ -14,6 +14,7 @@ class Number(models.Model):
def __str__(self): def __str__(self):
return '%i, %.3f' % (self.integer, self.float) return '%i, %.3f' % (self.integer, self.float)
class Experiment(models.Model): class Experiment(models.Model):
name = models.CharField(max_length=24) name = models.CharField(max_length=24)
assigned = models.DateField() assigned = models.DateField()

View File

@ -79,12 +79,12 @@ class ExpressionsRegressTests(TestCase):
""" """
n = Number.objects.create(integer=10, float=123.45) n = Number.objects.create(integer=10, float=123.45)
self.assertEqual(Number.objects.filter(pk=n.pk) self.assertEqual(Number.objects.filter(pk=n.pk)
.update(float=F('integer') + F('float') * 2), .update(float=F('integer') + F('float') * 2), 1)
1)
self.assertEqual(Number.objects.get(pk=n.pk).integer, 10) self.assertEqual(Number.objects.get(pk=n.pk).integer, 10)
self.assertEqual(Number.objects.get(pk=n.pk).float, Approximate(256.900, places=3)) self.assertEqual(Number.objects.get(pk=n.pk).float, Approximate(256.900, places=3))
class ExpressionOperatorTests(TestCase): class ExpressionOperatorTests(TestCase):
def setUp(self): def setUp(self):
self.n = Number.objects.create(integer=42, float=15.5) self.n = Number.objects.create(integer=42, float=15.5)
@ -220,13 +220,13 @@ class FTimeDeltaTests(TestCase):
self.days_long = [] self.days_long = []
# e0: started same day as assigned, zero duration # e0: started same day as assigned, zero duration
end = stime+delta0 end = stime + delta0
e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime, e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime,
end=end, completed=end.date()) end=end, completed=end.date())
self.deltas.append(delta0) self.deltas.append(delta0)
self.delays.append(e0.start - self.delays.append(e0.start -
datetime.datetime.combine(e0.assigned, midnight)) datetime.datetime.combine(e0.assigned, midnight))
self.days_long.append(e0.completed-e0.assigned) self.days_long.append(e0.completed - e0.assigned)
# e1: started one day after assigned, tiny duration, data # e1: started one day after assigned, tiny duration, data
# set so that end time has no fractional seconds, which # set so that end time has no fractional seconds, which
@ -237,86 +237,86 @@ class FTimeDeltaTests(TestCase):
delay = datetime.timedelta(1) delay = datetime.timedelta(1)
end = stime + delay + delta1 end = stime + delay + delta1
e1 = Experiment.objects.create(name='e1', assigned=sday, e1 = Experiment.objects.create(name='e1', assigned=sday,
start=stime+delay, end=end, completed=end.date()) start=stime + delay, end=end, completed=end.date())
self.deltas.append(delta1) self.deltas.append(delta1)
self.delays.append(e1.start - self.delays.append(e1.start -
datetime.datetime.combine(e1.assigned, midnight)) datetime.datetime.combine(e1.assigned, midnight))
self.days_long.append(e1.completed-e1.assigned) self.days_long.append(e1.completed - e1.assigned)
# e2: started three days after assigned, small duration # e2: started three days after assigned, small duration
end = stime+delta2 end = stime + delta2
e2 = Experiment.objects.create(name='e2', e2 = Experiment.objects.create(name='e2',
assigned=sday-datetime.timedelta(3), start=stime, end=end, assigned=sday - datetime.timedelta(3), start=stime, end=end,
completed=end.date()) completed=end.date())
self.deltas.append(delta2) self.deltas.append(delta2)
self.delays.append(e2.start - self.delays.append(e2.start -
datetime.datetime.combine(e2.assigned, midnight)) datetime.datetime.combine(e2.assigned, midnight))
self.days_long.append(e2.completed-e2.assigned) self.days_long.append(e2.completed - e2.assigned)
# e3: started four days after assigned, medium duration # e3: started four days after assigned, medium duration
delay = datetime.timedelta(4) delay = datetime.timedelta(4)
end = stime + delay + delta3 end = stime + delay + delta3
e3 = Experiment.objects.create(name='e3', e3 = Experiment.objects.create(name='e3',
assigned=sday, start=stime+delay, end=end, completed=end.date()) assigned=sday, start=stime + delay, end=end, completed=end.date())
self.deltas.append(delta3) self.deltas.append(delta3)
self.delays.append(e3.start - self.delays.append(e3.start -
datetime.datetime.combine(e3.assigned, midnight)) datetime.datetime.combine(e3.assigned, midnight))
self.days_long.append(e3.completed-e3.assigned) self.days_long.append(e3.completed - e3.assigned)
# e4: started 10 days after assignment, long duration # e4: started 10 days after assignment, long duration
end = stime + delta4 end = stime + delta4
e4 = Experiment.objects.create(name='e4', e4 = Experiment.objects.create(name='e4',
assigned=sday-datetime.timedelta(10), start=stime, end=end, assigned=sday - datetime.timedelta(10), start=stime, end=end,
completed=end.date()) completed=end.date())
self.deltas.append(delta4) self.deltas.append(delta4)
self.delays.append(e4.start - self.delays.append(e4.start -
datetime.datetime.combine(e4.assigned, midnight)) datetime.datetime.combine(e4.assigned, midnight))
self.days_long.append(e4.completed-e4.assigned) self.days_long.append(e4.completed - e4.assigned)
self.expnames = [e.name for e in Experiment.objects.all()] self.expnames = [e.name for e in Experiment.objects.all()]
def test_delta_add(self): def test_delta_add(self):
for i in range(len(self.deltas)): for i in range(len(self.deltas)):
delta = self.deltas[i] delta = self.deltas[i]
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(end__lt=F('start')+delta)] Experiment.objects.filter(end__lt=F('start') + delta)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(end__lte=F('start')+delta)] Experiment.objects.filter(end__lte=F('start') + delta)]
self.assertEqual(test_set, self.expnames[:i+1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_delta_subtract(self): def test_delta_subtract(self):
for i in range(len(self.deltas)): for i in range(len(self.deltas)):
delta = self.deltas[i] delta = self.deltas[i]
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(start__gt=F('end')-delta)] Experiment.objects.filter(start__gt=F('end') - delta)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(start__gte=F('end')-delta)] Experiment.objects.filter(start__gte=F('end') - delta)]
self.assertEqual(test_set, self.expnames[:i+1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_exclude(self): def test_exclude(self):
for i in range(len(self.deltas)): for i in range(len(self.deltas)):
delta = self.deltas[i] delta = self.deltas[i]
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.exclude(end__lt=F('start')+delta)] Experiment.objects.exclude(end__lt=F('start') + delta)]
self.assertEqual(test_set, self.expnames[i:]) self.assertEqual(test_set, self.expnames[i:])
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.exclude(end__lte=F('start')+delta)] Experiment.objects.exclude(end__lte=F('start') + delta)]
self.assertEqual(test_set, self.expnames[i+1:]) self.assertEqual(test_set, self.expnames[i + 1:])
def test_date_comparison(self): def test_date_comparison(self):
for i in range(len(self.days_long)): for i in range(len(self.days_long)):
days = self.days_long[i] days = self.days_long[i]
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(completed__lt=F('assigned')+days)] Experiment.objects.filter(completed__lt=F('assigned') + days)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(completed__lte=F('assigned')+days)] Experiment.objects.filter(completed__lte=F('assigned') + days)]
self.assertEqual(test_set, self.expnames[:i+1]) self.assertEqual(test_set, self.expnames[:i + 1])
@skipUnlessDBFeature("supports_mixed_date_datetime_comparisons") @skipUnlessDBFeature("supports_mixed_date_datetime_comparisons")
def test_mixed_comparisons1(self): def test_mixed_comparisons1(self):
@ -325,35 +325,35 @@ class FTimeDeltaTests(TestCase):
if not connection.features.supports_microsecond_precision: if not connection.features.supports_microsecond_precision:
delay = datetime.timedelta(delay.days, delay.seconds) delay = datetime.timedelta(delay.days, delay.seconds)
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(assigned__gt=F('start')-delay)] Experiment.objects.filter(assigned__gt=F('start') - delay)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(assigned__gte=F('start')-delay)] Experiment.objects.filter(assigned__gte=F('start') - delay)]
self.assertEqual(test_set, self.expnames[:i+1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_mixed_comparisons2(self): def test_mixed_comparisons2(self):
delays = [datetime.timedelta(delay.days) for delay in self.delays] delays = [datetime.timedelta(delay.days) for delay in self.delays]
for i in range(len(delays)): for i in range(len(delays)):
delay = delays[i] delay = delays[i]
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(start__lt=F('assigned')+delay)] Experiment.objects.filter(start__lt=F('assigned') + delay)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in
Experiment.objects.filter(start__lte=F('assigned') + delay + Experiment.objects.filter(start__lte=F('assigned') + delay +
datetime.timedelta(1))] datetime.timedelta(1))]
self.assertEqual(test_set, self.expnames[:i+1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_delta_update(self): def test_delta_update(self):
for i in range(len(self.deltas)): for i in range(len(self.deltas)):
delta = self.deltas[i] delta = self.deltas[i]
exps = Experiment.objects.all() exps = Experiment.objects.all()
expected_durations = [e.duration() for e in exps] expected_durations = [e.duration() for e in exps]
expected_starts = [e.start+delta for e in exps] expected_starts = [e.start + delta for e in exps]
expected_ends = [e.end+delta for e in exps] expected_ends = [e.end + delta for e in exps]
Experiment.objects.update(start=F('start')+delta, end=F('end')+delta) Experiment.objects.update(start=F('start') + delta, end=F('end') + delta)
exps = Experiment.objects.all() exps = Experiment.objects.all()
new_starts = [e.start for e in exps] new_starts = [e.start for e in exps]
new_ends = [e.end for e in exps] new_ends = [e.end for e in exps]
@ -365,7 +365,7 @@ class FTimeDeltaTests(TestCase):
def test_delta_invalid_op_mult(self): def test_delta_invalid_op_mult(self):
raised = False raised = False
try: try:
repr(Experiment.objects.filter(end__lt=F('start')*self.deltas[0])) repr(Experiment.objects.filter(end__lt=F('start') * self.deltas[0]))
except TypeError: except TypeError:
raised = True raised = True
self.assertTrue(raised, "TypeError not raised on attempt to multiply datetime by timedelta.") self.assertTrue(raised, "TypeError not raised on attempt to multiply datetime by timedelta.")
@ -373,7 +373,7 @@ class FTimeDeltaTests(TestCase):
def test_delta_invalid_op_div(self): def test_delta_invalid_op_div(self):
raised = False raised = False
try: try:
repr(Experiment.objects.filter(end__lt=F('start')/self.deltas[0])) repr(Experiment.objects.filter(end__lt=F('start') / self.deltas[0]))
except TypeError: except TypeError:
raised = True raised = True
self.assertTrue(raised, "TypeError not raised on attempt to divide datetime by timedelta.") self.assertTrue(raised, "TypeError not raised on attempt to divide datetime by timedelta.")

View File

@ -30,10 +30,12 @@ class RevisionableModel(models.Model):
new_revision.pk = None new_revision.pk = None
return new_revision return new_revision
class Order(models.Model): class Order(models.Model):
created_by = models.ForeignKey(User) created_by = models.ForeignKey(User)
text = models.TextField() text = models.TextField()
@python_2_unicode_compatible @python_2_unicode_compatible
class TestObject(models.Model): class TestObject(models.Model):
first = models.CharField(max_length=20) first = models.CharField(max_length=20)

View File

@ -20,6 +20,7 @@ class Small(object):
def __str__(self): def __str__(self):
return '%s%s' % (force_text(self.first), force_text(self.second)) return '%s%s' % (force_text(self.first), force_text(self.second))
class SmallField(six.with_metaclass(models.SubfieldBase, models.Field)): class SmallField(six.with_metaclass(models.SubfieldBase, models.Field)):
""" """
Turns the "Small" class into a Django field. Because of the similarities Turns the "Small" class into a Django field. Because of the similarities
@ -51,6 +52,7 @@ class SmallField(six.with_metaclass(models.SubfieldBase, models.Field)):
return [] return []
raise TypeError('Invalid lookup type: %r' % lookup_type) raise TypeError('Invalid lookup type: %r' % lookup_type)
class SmallerField(SmallField): class SmallerField(SmallField):
pass pass

View File

@ -17,8 +17,10 @@ class MyModel(models.Model):
def __str__(self): def __str__(self):
return force_text(self.name) return force_text(self.name)
class OtherModel(models.Model): class OtherModel(models.Model):
data = SmallerField() data = SmallerField()
class DataModel(models.Model): class DataModel(models.Model):
data = JSONField() data = JSONField()

View File

@ -15,6 +15,7 @@ from django.core.files.storage import FileSystemStorage
temp_storage_location = tempfile.mkdtemp() temp_storage_location = tempfile.mkdtemp()
temp_storage = FileSystemStorage(location=temp_storage_location) temp_storage = FileSystemStorage(location=temp_storage_location)
class Storage(models.Model): class Storage(models.Model):
def custom_upload_to(self, filename): def custom_upload_to(self, filename):
return 'foo' return 'foo'

View File

@ -69,6 +69,7 @@ class GetStorageClassTests(SimpleTestCase):
get_storage_class( get_storage_class(
'django.core.files.non_existing_storage.NonExistingStorage') 'django.core.files.non_existing_storage.NonExistingStorage')
class FileStorageTests(unittest.TestCase): class FileStorageTests(unittest.TestCase):
storage_class = FileSystemStorage storage_class = FileSystemStorage
@ -379,6 +380,7 @@ class CustomStorage(FileSystemStorage):
return name return name
class CustomStorageTests(FileStorageTests): class CustomStorageTests(FileStorageTests):
storage_class = CustomStorage storage_class = CustomStorage
@ -531,6 +533,7 @@ class SlowFile(ContentFile):
time.sleep(1) time.sleep(1)
return super(ContentFile, self).chunks() return super(ContentFile, self).chunks()
class FileSaveRaceConditionTest(unittest.TestCase): class FileSaveRaceConditionTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.storage_dir = tempfile.mkdtemp() self.storage_dir = tempfile.mkdtemp()
@ -552,6 +555,7 @@ class FileSaveRaceConditionTest(unittest.TestCase):
self.storage.delete('conflict') self.storage.delete('conflict')
self.storage.delete('conflict_1') self.storage.delete('conflict_1')
@unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.") @unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.")
class FileStoragePermissions(unittest.TestCase): class FileStoragePermissions(unittest.TestCase):
def setUp(self): def setUp(self):
@ -591,6 +595,7 @@ class FileStoragePermissions(unittest.TestCase):
dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777 dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777
self.assertEqual(dir_mode, 0o777 & ~self.umask) self.assertEqual(dir_mode, 0o777 & ~self.umask)
class FileStoragePathParsing(unittest.TestCase): class FileStoragePathParsing(unittest.TestCase):
def setUp(self): def setUp(self):
self.storage_dir = tempfile.mkdtemp() self.storage_dir = tempfile.mkdtemp()

View File

@ -397,6 +397,7 @@ class FileUploadTests(TestCase):
# shouldn't differ. # shouldn't differ.
self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt') self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt')
@override_settings(MEDIA_ROOT=MEDIA_ROOT) @override_settings(MEDIA_ROOT=MEDIA_ROOT)
class DirectoryCreationTests(TestCase): class DirectoryCreationTests(TestCase):
""" """
@ -436,7 +437,7 @@ class DirectoryCreationTests(TestCase):
# The test needs to be done on a specific string as IOError # The test needs to be done on a specific string as IOError
# is raised even without the patch (just not early enough) # is raised even without the patch (just not early enough)
self.assertEqual(exc_info.exception.args[0], self.assertEqual(exc_info.exception.args[0],
"%s exists and is not a directory." % UPLOAD_TO) "%s exists and is not a directory." % UPLOAD_TO)
class MultiParserTests(unittest.TestCase): class MultiParserTests(unittest.TestCase):

View File

@ -11,7 +11,7 @@ class QuotaUploadHandler(FileUploadHandler):
(5MB) is uploaded. (5MB) is uploaded.
""" """
QUOTA = 5 * 2**20 # 5 MB QUOTA = 5 * 2 ** 20 # 5 MB
def __init__(self, request=None): def __init__(self, request=None):
super(QuotaUploadHandler, self).__init__(request) super(QuotaUploadHandler, self).__init__(request)
@ -26,9 +26,11 @@ class QuotaUploadHandler(FileUploadHandler):
def file_complete(self, file_size): def file_complete(self, file_size):
return None return None
class CustomUploadError(Exception): class CustomUploadError(Exception):
pass pass
class ErroringUploadHandler(FileUploadHandler): class ErroringUploadHandler(FileUploadHandler):
"""A handler that raises an exception.""" """A handler that raises an exception."""
def receive_data_chunk(self, raw_data, start): def receive_data_chunk(self, raw_data, start):

View File

@ -30,6 +30,7 @@ def file_upload_view(request):
else: else:
return HttpResponseServerError() return HttpResponseServerError()
def file_upload_view_verify(request): def file_upload_view_verify(request):
""" """
Use the sha digest hash to verify the uploaded contents. Use the sha digest hash to verify the uploaded contents.
@ -57,6 +58,7 @@ def file_upload_view_verify(request):
return HttpResponse('') return HttpResponse('')
def file_upload_unicode_name(request): def file_upload_unicode_name(request):
# Check to see if unicode name came through properly. # Check to see if unicode name came through properly.
@ -85,6 +87,7 @@ def file_upload_unicode_name(request):
else: else:
return HttpResponse('') return HttpResponse('')
def file_upload_echo(request): def file_upload_echo(request):
""" """
Simple view to echo back info about uploaded files for tests. Simple view to echo back info about uploaded files for tests.
@ -92,6 +95,7 @@ def file_upload_echo(request):
r = dict((k, f.name) for k, f in request.FILES.items()) r = dict((k, f.name) for k, f in request.FILES.items())
return HttpResponse(json.dumps(r)) return HttpResponse(json.dumps(r))
def file_upload_echo_content(request): def file_upload_echo_content(request):
""" """
Simple view to echo back the content of uploaded files for tests. Simple view to echo back the content of uploaded files for tests.
@ -99,6 +103,7 @@ def file_upload_echo_content(request):
r = dict((k, f.read().decode('utf-8')) for k, f in request.FILES.items()) r = dict((k, f.read().decode('utf-8')) for k, f in request.FILES.items())
return HttpResponse(json.dumps(r)) return HttpResponse(json.dumps(r))
def file_upload_quota(request): def file_upload_quota(request):
""" """
Dynamically add in an upload handler. Dynamically add in an upload handler.
@ -106,6 +111,7 @@ def file_upload_quota(request):
request.upload_handlers.insert(0, QuotaUploadHandler()) request.upload_handlers.insert(0, QuotaUploadHandler())
return file_upload_echo(request) return file_upload_echo(request)
def file_upload_quota_broken(request): def file_upload_quota_broken(request):
""" """
You can't change handlers after reading FILES; this view shouldn't work. You can't change handlers after reading FILES; this view shouldn't work.
@ -114,6 +120,7 @@ def file_upload_quota_broken(request):
request.upload_handlers.insert(0, QuotaUploadHandler()) request.upload_handlers.insert(0, QuotaUploadHandler())
return response return response
def file_upload_getlist_count(request): def file_upload_getlist_count(request):
""" """
Check the .getlist() function to ensure we receive the correct number of files. Check the .getlist() function to ensure we receive the correct number of files.
@ -124,10 +131,12 @@ def file_upload_getlist_count(request):
file_counts[key] = len(request.FILES.getlist(key)) file_counts[key] = len(request.FILES.getlist(key))
return HttpResponse(json.dumps(file_counts)) return HttpResponse(json.dumps(file_counts))
def file_upload_errors(request): def file_upload_errors(request):
request.upload_handlers.insert(0, ErroringUploadHandler()) request.upload_handlers.insert(0, ErroringUploadHandler())
return file_upload_echo(request) return file_upload_echo(request)
def file_upload_filename_case_view(request): def file_upload_filename_case_view(request):
""" """
Check adding the file to the database will preserve the filename case. Check adding the file to the database will preserve the filename case.
@ -137,6 +146,7 @@ def file_upload_filename_case_view(request):
obj.testfile.save(file.name, file) obj.testfile.save(file.name, file)
return HttpResponse('%d' % obj.pk) return HttpResponse('%d' % obj.pk)
def file_upload_content_type_extra(request): def file_upload_content_type_extra(request):
""" """
Simple view to echo back extra content-type parameters. Simple view to echo back extra content-type parameters.

View File

@ -26,6 +26,7 @@ class Category(models.Model):
class Meta: class Meta:
ordering = ('title',) ordering = ('title',)
@python_2_unicode_compatible @python_2_unicode_compatible
class Article(models.Model): class Article(models.Model):
headline = models.CharField(max_length=100, default='Default headline') headline = models.CharField(max_length=100, default='Default headline')
@ -37,6 +38,7 @@ class Article(models.Model):
class Meta: class Meta:
ordering = ('-pub_date', 'headline') ordering = ('-pub_date', 'headline')
@python_2_unicode_compatible @python_2_unicode_compatible
class Blog(models.Model): class Blog(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -60,10 +62,12 @@ class Tag(models.Model):
return '<%s: %s> tagged "%s"' % (self.tagged.__class__.__name__, return '<%s: %s> tagged "%s"' % (self.tagged.__class__.__name__,
self.tagged, self.name) self.tagged, self.name)
class PersonManager(models.Manager): class PersonManager(models.Manager):
def get_by_natural_key(self, name): def get_by_natural_key(self, name):
return self.get(name=name) return self.get(name=name)
@python_2_unicode_compatible @python_2_unicode_compatible
class Person(models.Model): class Person(models.Model):
objects = PersonManager() objects = PersonManager()
@ -78,14 +82,17 @@ class Person(models.Model):
def natural_key(self): def natural_key(self):
return (self.name,) return (self.name,)
class SpyManager(PersonManager): class SpyManager(PersonManager):
def get_queryset(self): def get_queryset(self):
return super(SpyManager, self).get_queryset().filter(cover_blown=False) return super(SpyManager, self).get_queryset().filter(cover_blown=False)
class Spy(Person): class Spy(Person):
objects = SpyManager() objects = SpyManager()
cover_blown = models.BooleanField(default=False) cover_blown = models.BooleanField(default=False)
@python_2_unicode_compatible @python_2_unicode_compatible
class Visa(models.Model): class Visa(models.Model):
person = models.ForeignKey(Person) person = models.ForeignKey(Person)
@ -95,6 +102,7 @@ class Visa(models.Model):
return '%s %s' % (self.person.name, return '%s %s' % (self.person.name,
', '.join(p.name for p in self.permissions.all())) ', '.join(p.name for p in self.permissions.all()))
@python_2_unicode_compatible @python_2_unicode_compatible
class Book(models.Model): class Book(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)

View File

@ -14,6 +14,7 @@ class Article(models.Model):
app_label = 'fixtures_model_package' app_label = 'fixtures_model_package'
ordering = ('-pub_date', 'headline') ordering = ('-pub_date', 'headline')
class Book(models.Model): class Book(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)

View File

@ -27,6 +27,7 @@ class Plant(models.Model):
# For testing when upper case letter in app name; regression for #4057 # For testing when upper case letter in app name; regression for #4057
db_table = "Fixtures_regress_plant" db_table = "Fixtures_regress_plant"
@python_2_unicode_compatible @python_2_unicode_compatible
class Stuff(models.Model): class Stuff(models.Model):
name = models.CharField(max_length=20, null=True) name = models.CharField(max_length=20, null=True)

View File

@ -9,16 +9,20 @@ class Counter(models.Model):
name = models.CharField(max_length = 10) name = models.CharField(max_length = 10)
value = models.IntegerField() value = models.IntegerField()
class InheritedCounter(Counter): class InheritedCounter(Counter):
tag = models.CharField(max_length=10) tag = models.CharField(max_length=10)
class ProxyCounter(Counter): class ProxyCounter(Counter):
class Meta: class Meta:
proxy = True proxy = True
class SubCounter(Counter): class SubCounter(Counter):
pass pass
class WithCustomPK(models.Model): class WithCustomPK(models.Model):
name = models.IntegerField(primary_key=True) name = models.IntegerField(primary_key=True)
value = models.IntegerField() value = models.IntegerField()

View File

@ -5,6 +5,7 @@ from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import get_language from django.utils.translation import get_language
@python_2_unicode_compatible @python_2_unicode_compatible
class Country(models.Model): class Country(models.Model):
# Table Column Fields # Table Column Fields
@ -13,6 +14,7 @@ class Country(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Person(models.Model): class Person(models.Model):
# Table Column Fields # Table Column Fields
@ -30,6 +32,7 @@ class Person(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Group(models.Model): class Group(models.Model):
# Table Column Fields # Table Column Fields
@ -96,6 +99,7 @@ class Friendship(models.Model):
to_fields=['person_country_id', 'id'], to_fields=['person_country_id', 'id'],
related_name='to_friend') related_name='to_friend')
class ArticleTranslationDescriptor(ReverseSingleRelatedObjectDescriptor): class ArticleTranslationDescriptor(ReverseSingleRelatedObjectDescriptor):
""" """
The set of articletranslation should not set any local fields. The set of articletranslation should not set any local fields.
@ -107,6 +111,7 @@ class ArticleTranslationDescriptor(ReverseSingleRelatedObjectDescriptor):
if value is not None and not self.field.rel.multiple: if value is not None and not self.field.rel.multiple:
setattr(value, self.field.related.get_cache_name(), instance) setattr(value, self.field.related.get_cache_name(), instance)
class ColConstraint(object): class ColConstraint(object):
# Antyhing with as_sql() method works in get_extra_restriction(). # Antyhing with as_sql() method works in get_extra_restriction().
def __init__(self, alias, col, value): def __init__(self, alias, col, value):
@ -115,6 +120,7 @@ class ColConstraint(object):
def as_sql(self, qn, connection): def as_sql(self, qn, connection):
return '%s.%s = %%s' % (qn(self.alias), qn(self.col)), [self.value] return '%s.%s = %%s' % (qn(self.alias), qn(self.col)), [self.value]
class ActiveTranslationField(models.ForeignObject): class ActiveTranslationField(models.ForeignObject):
""" """
This field will allow querying and fetching the currently active translation This field will allow querying and fetching the currently active translation
@ -132,6 +138,7 @@ class ActiveTranslationField(models.ForeignObject):
super(ActiveTranslationField, self).contribute_to_class(cls, name) super(ActiveTranslationField, self).contribute_to_class(cls, name)
setattr(cls, self.name, ArticleTranslationDescriptor(self)) setattr(cls, self.name, ArticleTranslationDescriptor(self))
@python_2_unicode_compatible @python_2_unicode_compatible
class Article(models.Model): class Article(models.Model):
active_translation = ActiveTranslationField( active_translation = ActiveTranslationField(
@ -148,9 +155,11 @@ class Article(models.Model):
except ArticleTranslation.DoesNotExist: except ArticleTranslation.DoesNotExist:
return '[No translation found]' return '[No translation found]'
class NewsArticle(Article): class NewsArticle(Article):
pass pass
class ArticleTranslation(models.Model): class ArticleTranslation(models.Model):
article = models.ForeignKey(Article) article = models.ForeignKey(Article)
lang = models.CharField(max_length='2') lang = models.CharField(max_length='2')
@ -162,10 +171,12 @@ class ArticleTranslation(models.Model):
unique_together = ('article', 'lang') unique_together = ('article', 'lang')
ordering = ('active_translation__title',) ordering = ('active_translation__title',)
class ArticleTag(models.Model): class ArticleTag(models.Model):
article = models.ForeignKey(Article, related_name="tags", related_query_name="tag") article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
class ArticleIdea(models.Model): class ArticleIdea(models.Model):
articles = models.ManyToManyField(Article, related_name="ideas", articles = models.ManyToManyField(Article, related_name="ideas",
related_query_name="idea_things") related_query_name="idea_things")

View File

@ -12,6 +12,7 @@ from django import forms
# Note that these tests are testing internal implementation details. # Note that these tests are testing internal implementation details.
# ForeignObject is not part of public API. # ForeignObject is not part of public API.
class MultiColumnFKTests(TestCase): class MultiColumnFKTests(TestCase):
def setUp(self): def setUp(self):
# Creating countries # Creating countries
@ -379,6 +380,7 @@ class MultiColumnFKTests(TestCase):
'active_translation')[0].active_translation.title, 'active_translation')[0].active_translation.title,
"foo") "foo")
class FormsTests(TestCase): class FormsTests(TestCase):
# ForeignObjects should not have any form fields, currently the user needs # ForeignObjects should not have any form fields, currently the user needs
# to manually deal with the foreignobject relation. # to manually deal with the foreignobject relation.

View File

@ -19,6 +19,8 @@ class BoundaryModel(models.Model):
callable_default_value = 0 callable_default_value = 0
def callable_default(): def callable_default():
global callable_default_value global callable_default_value
callable_default_value = callable_default_value + 1 callable_default_value = callable_default_value + 1
@ -27,7 +29,7 @@ def callable_default():
class Defaults(models.Model): class Defaults(models.Model):
name = models.CharField(max_length=255, default='class default value') name = models.CharField(max_length=255, default='class default value')
def_date = models.DateField(default = datetime.date(1980, 1, 1)) def_date = models.DateField(default=datetime.date(1980, 1, 1))
value = models.IntegerField(default=42) value = models.IntegerField(default=42)
callable_default = models.IntegerField(default=callable_default) callable_default = models.IntegerField(default=callable_default)
@ -86,6 +88,7 @@ class ChoiceFieldModel(models.Model):
multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int', multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int',
default=lambda: [1]) default=lambda: [1])
class OptionalMultiChoiceModel(models.Model): class OptionalMultiChoiceModel(models.Model):
multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='not_relevant', multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='not_relevant',
default=lambda: ChoiceOptionModel.objects.filter(name='default')) default=lambda: ChoiceOptionModel.objects.filter(name='default'))

View File

@ -24,6 +24,7 @@ class AssertFormErrorsMixin(object):
except ValidationError as e: except ValidationError as e:
self.assertEqual(e.messages, expected) self.assertEqual(e.messages, expected)
class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
def test_charfield(self): def test_charfield(self):
e = { e = {

View File

@ -25,12 +25,15 @@ from .test_error_messages import AssertFormErrorsMixin
class GetDate(Form): class GetDate(Form):
mydate = DateField(widget=SelectDateWidget) mydate = DateField(widget=SelectDateWidget)
class GetNotRequiredDate(Form): class GetNotRequiredDate(Form):
mydate = DateField(widget=SelectDateWidget, required=False) mydate = DateField(widget=SelectDateWidget, required=False)
class GetDateShowHiddenInitial(Form): class GetDateShowHiddenInitial(Form):
mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True) mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True)
class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
############### ###############
# Extra stuff # # Extra stuff #

View File

@ -57,7 +57,7 @@ SplitDateTimeFormSet = formset_factory(SplitDateTimeForm)
class FormsFormsetTestCase(TestCase): class FormsFormsetTestCase(TestCase):
def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet, def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet,
total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs): total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs):
""" """
Make a ChoiceFormset from the given formset_data. Make a ChoiceFormset from the given formset_data.
The data should be given as a list of (choice, votes) tuples. The data should be given as a list of (choice, votes) tuples.
@ -1097,12 +1097,14 @@ data = {
'choices-0-votes': '100', 'choices-0-votes': '100',
} }
class Choice(Form): class Choice(Form):
choice = CharField() choice = CharField()
votes = IntegerField() votes = IntegerField()
ChoiceFormSet = formset_factory(Choice) ChoiceFormSet = formset_factory(Choice)
class FormsetAsFooTests(TestCase): class FormsetAsFooTests(TestCase):
def test_as_table(self): def test_as_table(self):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices') formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
@ -1130,6 +1132,7 @@ class ArticleForm(Form):
ArticleFormSet = formset_factory(ArticleForm) ArticleFormSet = formset_factory(ArticleForm)
class TestIsBoundBehavior(TestCase): class TestIsBoundBehavior(TestCase):
def test_no_data_raises_validation_error(self): def test_no_data_raises_validation_error(self):
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
@ -1184,6 +1187,7 @@ class TestIsBoundBehavior(TestCase):
# The empty forms should be equal. # The empty forms should be equal.
self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p()) self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p())
class TestEmptyFormSet(TestCase): class TestEmptyFormSet(TestCase):
def test_empty_formset_is_valid(self): def test_empty_formset_is_valid(self):
"""Test that an empty formset still calls clean()""" """Test that an empty formset still calls clean()"""

View File

@ -490,6 +490,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
text = f.widget._format_value(result) text = f.widget._format_value(result)
self.assertEqual(text, "21.12.2010") self.assertEqual(text, "21.12.2010")
class SimpleDateFormatTests(SimpleTestCase): class SimpleDateFormatTests(SimpleTestCase):
def test_dateField(self): def test_dateField(self):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
@ -776,6 +777,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
text = f.widget._format_value(result) text = f.widget._format_value(result)
self.assertEqual(text, "01:30:00 PM 21/12/2010") self.assertEqual(text, "01:30:00 PM 21/12/2010")
class SimpleDateTimeFormatTests(SimpleTestCase): class SimpleDateTimeFormatTests(SimpleTestCase):
def test_dateTimeField(self): def test_dateTimeField(self):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"

View File

@ -286,7 +286,7 @@ class FormsWidgetTestCase(TestCase):
things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'}) things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'})
class SomeForm(Form): class SomeForm(Form):
somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things])) somechoice = ChoiceField(choices=chain((('', '-' * 9),), [(thing['id'], thing['name']) for thing in things]))
f = SomeForm() f = SomeForm()
self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>') self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>') self.assertHTMLEqual(f.as_table(), '<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>')
@ -1003,6 +1003,7 @@ class NullBooleanSelectLazyForm(Form):
"""Form to test for lazy evaluation. Refs #17190""" """Form to test for lazy evaluation. Refs #17190"""
bool = BooleanField(widget=NullBooleanSelect()) bool = BooleanField(widget=NullBooleanSelect())
@override_settings(USE_L10N=True) @override_settings(USE_L10N=True)
class FormsI18NWidgetsTestCase(TestCase): class FormsI18NWidgetsTestCase(TestCase):
def setUp(self): def setUp(self):
@ -1136,6 +1137,7 @@ class FakeFieldFile(object):
def __str__(self): def __str__(self):
return self.url return self.url
class ClearableFileInputTests(TestCase): class ClearableFileInputTests(TestCase):
def test_clear_input_renders(self): def test_clear_input_renders(self):
""" """

View File

@ -217,6 +217,7 @@ class FormsModelTestCase(TestCase):
self.assertEqual(obj.value, 99) self.assertEqual(obj.value, 99)
self.assertEqual(obj.def_date, datetime.date(1999, 3, 2)) self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
class RelatedModelFormTests(TestCase): class RelatedModelFormTests(TestCase):
def test_invalid_loading_order(self): def test_invalid_loading_order(self):
""" """

View File

@ -7,6 +7,7 @@ from .models import (Media, PhoneNumber, Episode, EpisodeExtra, Contact,
site = admin.AdminSite(name="admin") site = admin.AdminSite(name="admin")
class MediaInline(generic.GenericTabularInline): class MediaInline(generic.GenericTabularInline):
model = Media model = Media

View File

@ -34,6 +34,7 @@ class Media(models.Model):
# Generic inline with extra = 0 # Generic inline with extra = 0
# #
class EpisodeExtra(Episode): class EpisodeExtra(Episode):
pass pass
@ -67,6 +68,7 @@ class Contact(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
phone_numbers = generic.GenericRelation(PhoneNumber) phone_numbers = generic.GenericRelation(PhoneNumber)
# #
# Generic inline with can_delete=False # Generic inline with can_delete=False
# #

View File

@ -129,6 +129,7 @@ class GenericAdminViewTest(TestCase):
formset = inline_formset(instance=e) formset = inline_formset(instance=e)
self.assertTrue(formset.get_queryset().ordered) self.assertTrue(formset.get_queryset().ordered)
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class GenericInlineAdminParametersTest(TestCase): class GenericInlineAdminParametersTest(TestCase):
urls = "generic_inline_admin.urls" urls = "generic_inline_admin.urls"
@ -210,6 +211,7 @@ class GenericInlineAdminWithUniqueTogetherTest(TestCase):
response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data) response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data)
self.assertEqual(response.status_code, 302) # redirect somewhere self.assertEqual(response.status_code, 302) # redirect somewhere
class NoInlineDeletionTest(TestCase): class NoInlineDeletionTest(TestCase):
urls = "generic_inline_admin.urls" urls = "generic_inline_admin.urls"
@ -224,6 +226,7 @@ class NoInlineDeletionTest(TestCase):
class MockRequest(object): class MockRequest(object):
pass pass
class MockSuperUser(object): class MockSuperUser(object):
def has_perm(self, perm): def has_perm(self, perm):
return True return True

View File

@ -290,12 +290,14 @@ class GenericRelationsTests(TestCase):
class CustomWidget(forms.TextInput): class CustomWidget(forms.TextInput):
pass pass
class TaggedItemForm(forms.ModelForm): class TaggedItemForm(forms.ModelForm):
class Meta: class Meta:
model = TaggedItem model = TaggedItem
fields = '__all__' fields = '__all__'
widgets = {'tag': CustomWidget} widgets = {'tag': CustomWidget}
class GenericInlineFormsetTest(TestCase): class GenericInlineFormsetTest(TestCase):
def test_generic_inlineformset_factory(self): def test_generic_inlineformset_factory(self):
""" """

View File

@ -8,6 +8,7 @@ __all__ = ('Link', 'Place', 'Restaurant', 'Person', 'Address',
'CharLink', 'TextLink', 'OddRelation1', 'OddRelation2', 'CharLink', 'TextLink', 'OddRelation1', 'OddRelation2',
'Contact', 'Organization', 'Note', 'Company') 'Contact', 'Organization', 'Note', 'Company')
@python_2_unicode_compatible @python_2_unicode_compatible
class Link(models.Model): class Link(models.Model):
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
@ -17,6 +18,7 @@ class Link(models.Model):
def __str__(self): def __str__(self):
return "Link to %s id=%s" % (self.content_type, self.object_id) return "Link to %s id=%s" % (self.content_type, self.object_id)
@python_2_unicode_compatible @python_2_unicode_compatible
class Place(models.Model): class Place(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -25,11 +27,13 @@ class Place(models.Model):
def __str__(self): def __str__(self):
return "Place: %s" % self.name return "Place: %s" % self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Restaurant(Place): class Restaurant(Place):
def __str__(self): def __str__(self):
return "Restaurant: %s" % self.name return "Restaurant: %s" % self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Address(models.Model): class Address(models.Model):
street = models.CharField(max_length=80) street = models.CharField(max_length=80)
@ -43,6 +47,7 @@ class Address(models.Model):
def __str__(self): def __str__(self):
return '%s %s, %s %s' % (self.street, self.city, self.state, self.zipcode) return '%s %s, %s %s' % (self.street, self.city, self.state, self.zipcode)
@python_2_unicode_compatible @python_2_unicode_compatible
class Person(models.Model): class Person(models.Model):
account = models.IntegerField(primary_key=True) account = models.IntegerField(primary_key=True)
@ -52,24 +57,29 @@ class Person(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class CharLink(models.Model): class CharLink(models.Model):
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
object_id = models.CharField(max_length=100) object_id = models.CharField(max_length=100)
content_object = generic.GenericForeignKey() content_object = generic.GenericForeignKey()
class TextLink(models.Model): class TextLink(models.Model):
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
object_id = models.TextField() object_id = models.TextField()
content_object = generic.GenericForeignKey() content_object = generic.GenericForeignKey()
class OddRelation1(models.Model): class OddRelation1(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
clinks = generic.GenericRelation(CharLink) clinks = generic.GenericRelation(CharLink)
class OddRelation2(models.Model): class OddRelation2(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
tlinks = generic.GenericRelation(TextLink) tlinks = generic.GenericRelation(TextLink)
# models for test_q_object_or: # models for test_q_object_or:
class Note(models.Model): class Note(models.Model):
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
@ -77,13 +87,16 @@ class Note(models.Model):
content_object = generic.GenericForeignKey() content_object = generic.GenericForeignKey()
note = models.TextField() note = models.TextField()
class Contact(models.Model): class Contact(models.Model):
notes = generic.GenericRelation(Note) notes = generic.GenericRelation(Note)
class Organization(models.Model): class Organization(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
contacts = models.ManyToManyField(Contact, related_name='organizations') contacts = models.ManyToManyField(Contact, related_name='organizations')
@python_2_unicode_compatible @python_2_unicode_compatible
class Company(models.Model): class Company(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -92,10 +105,12 @@ class Company(models.Model):
def __str__(self): def __str__(self):
return "Company: %s" % self.name return "Company: %s" % self.name
# For testing #13085 fix, we also use Note model defined above # For testing #13085 fix, we also use Note model defined above
class Developer(models.Model): class Developer(models.Model):
name = models.CharField(max_length=15) name = models.CharField(max_length=15)
@python_2_unicode_compatible @python_2_unicode_compatible
class Team(models.Model): class Team(models.Model):
name = models.CharField(max_length=15) name = models.CharField(max_length=15)
@ -107,49 +122,59 @@ class Team(models.Model):
def __len__(self): def __len__(self):
return self.members.count() return self.members.count()
class Guild(models.Model): class Guild(models.Model):
name = models.CharField(max_length=15) name = models.CharField(max_length=15)
members = models.ManyToManyField(Developer) members = models.ManyToManyField(Developer)
def __nonzero__(self): def __nonzero__(self):
return self.members.count() return self.members.count()
class Tag(models.Model): class Tag(models.Model):
content_type = models.ForeignKey(ContentType, related_name='g_r_r_tags') content_type = models.ForeignKey(ContentType, related_name='g_r_r_tags')
object_id = models.CharField(max_length=15) object_id = models.CharField(max_length=15)
content_object = generic.GenericForeignKey() content_object = generic.GenericForeignKey()
label = models.CharField(max_length=15) label = models.CharField(max_length=15)
class Board(models.Model): class Board(models.Model):
name = models.CharField(primary_key=True, max_length=15) name = models.CharField(primary_key=True, max_length=15)
class HasLinks(models.Model): class HasLinks(models.Model):
links = generic.GenericRelation(Link) links = generic.GenericRelation(Link)
class Meta: class Meta:
abstract = True abstract = True
class HasLinkThing(HasLinks): class HasLinkThing(HasLinks):
pass pass
class A(models.Model): class A(models.Model):
flag = models.NullBooleanField() flag = models.NullBooleanField()
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField() object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id') content_object = generic.GenericForeignKey('content_type', 'object_id')
class B(models.Model): class B(models.Model):
a = generic.GenericRelation(A) a = generic.GenericRelation(A)
class Meta: class Meta:
ordering = ('id',) ordering = ('id',)
class C(models.Model): class C(models.Model):
b = models.ForeignKey(B) b = models.ForeignKey(B)
class Meta: class Meta:
ordering = ('id',) ordering = ('id',)
class D(models.Model): class D(models.Model):
b = models.ForeignKey(B, null=True) b = models.ForeignKey(B, null=True)

View File

@ -18,6 +18,7 @@ class Artist(models.Model):
def get_absolute_url(self): def get_absolute_url(self):
return reverse('artist_detail', kwargs={'pk': self.id}) return reverse('artist_detail', kwargs={'pk': self.id})
@python_2_unicode_compatible @python_2_unicode_compatible
class Author(models.Model): class Author(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -29,6 +30,7 @@ class Author(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Book(models.Model): class Book(models.Model):
name = models.CharField(max_length=300) name = models.CharField(max_length=300)
@ -43,9 +45,11 @@ class Book(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class Page(models.Model): class Page(models.Model):
content = models.TextField() content = models.TextField()
template = models.CharField(max_length=300) template = models.CharField(max_length=300)
class BookSigning(models.Model): class BookSigning(models.Model):
event_date = models.DateTimeField() event_date = models.DateTimeField()

View File

@ -10,6 +10,7 @@ from django.views.generic import View, TemplateView, RedirectView
from . import views from . import views
class SimpleView(View): class SimpleView(View):
""" """
A simple view with a docstring. A simple view with a docstring.

View File

@ -15,9 +15,10 @@ def _make_books(n, base_date):
Book.objects.create( Book.objects.create(
name='Book %d' % i, name='Book %d' % i,
slug='book-%d' % i, slug='book-%d' % i,
pages=100+i, pages=100 + i,
pubdate=base_date - datetime.timedelta(days=i)) pubdate=base_date - datetime.timedelta(days=i))
class ArchiveIndexViewTests(TestCase): class ArchiveIndexViewTests(TestCase):
fixtures = ['generic-views-test-data.json'] fixtures = ['generic-views-test-data.json']
urls = 'generic_views.urls' urls = 'generic_views.urls'

View File

@ -65,6 +65,7 @@ class CustomPaginator(Paginator):
orphans=2, orphans=2,
allow_empty_first_page=allow_empty_first_page) allow_empty_first_page=allow_empty_first_page)
class AuthorListCustomPaginator(AuthorList): class AuthorListCustomPaginator(AuthorList):
paginate_by = 5 paginate_by = 5
@ -176,33 +177,42 @@ class BookConfig(object):
queryset = Book.objects.all() queryset = Book.objects.all()
date_field = 'pubdate' date_field = 'pubdate'
class BookArchive(BookConfig, generic.ArchiveIndexView): class BookArchive(BookConfig, generic.ArchiveIndexView):
pass pass
class BookYearArchive(BookConfig, generic.YearArchiveView): class BookYearArchive(BookConfig, generic.YearArchiveView):
pass pass
class BookMonthArchive(BookConfig, generic.MonthArchiveView): class BookMonthArchive(BookConfig, generic.MonthArchiveView):
pass pass
class BookWeekArchive(BookConfig, generic.WeekArchiveView): class BookWeekArchive(BookConfig, generic.WeekArchiveView):
pass pass
class BookDayArchive(BookConfig, generic.DayArchiveView): class BookDayArchive(BookConfig, generic.DayArchiveView):
pass pass
class BookTodayArchive(BookConfig, generic.TodayArchiveView): class BookTodayArchive(BookConfig, generic.TodayArchiveView):
pass pass
class BookDetail(BookConfig, generic.DateDetailView): class BookDetail(BookConfig, generic.DateDetailView):
pass pass
class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin): class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin):
fields = '__all__' fields = '__all__'
def get_queryset(self): def get_queryset(self):
return Author.objects.all() return Author.objects.all()
class BookDetailGetObjectCustomQueryset(BookDetail): class BookDetailGetObjectCustomQueryset(BookDetail):
def get_object(self, queryset=None): def get_object(self, queryset=None):
return super(BookDetailGetObjectCustomQueryset, self).get_object( return super(BookDetailGetObjectCustomQueryset, self).get_object(
@ -234,10 +244,12 @@ class CustomContextView(generic.detail.SingleObjectMixin, generic.View):
def get_context_object_name(self, obj): def get_context_object_name(self, obj):
return "test_name" return "test_name"
class CustomSingleObjectView(generic.detail.SingleObjectMixin, generic.View): class CustomSingleObjectView(generic.detail.SingleObjectMixin, generic.View):
model = Book model = Book
object = Book(name="dummy") object = Book(name="dummy")
class BookSigningConfig(object): class BookSigningConfig(object):
model = BookSigning model = BookSigning
date_field = 'event_date' date_field = 'event_date'
@ -246,24 +258,31 @@ class BookSigningConfig(object):
def get_template_names(self): def get_template_names(self):
return ['generic_views/book%s.html' % self.template_name_suffix] return ['generic_views/book%s.html' % self.template_name_suffix]
class BookSigningArchive(BookSigningConfig, generic.ArchiveIndexView): class BookSigningArchive(BookSigningConfig, generic.ArchiveIndexView):
pass pass
class BookSigningYearArchive(BookSigningConfig, generic.YearArchiveView): class BookSigningYearArchive(BookSigningConfig, generic.YearArchiveView):
pass pass
class BookSigningMonthArchive(BookSigningConfig, generic.MonthArchiveView): class BookSigningMonthArchive(BookSigningConfig, generic.MonthArchiveView):
pass pass
class BookSigningWeekArchive(BookSigningConfig, generic.WeekArchiveView): class BookSigningWeekArchive(BookSigningConfig, generic.WeekArchiveView):
pass pass
class BookSigningDayArchive(BookSigningConfig, generic.DayArchiveView): class BookSigningDayArchive(BookSigningConfig, generic.DayArchiveView):
pass pass
class BookSigningTodayArchive(BookSigningConfig, generic.TodayArchiveView): class BookSigningTodayArchive(BookSigningConfig, generic.TodayArchiveView):
pass pass
class BookSigningDetail(BookSigningConfig, generic.DateDetailView): class BookSigningDetail(BookSigningConfig, generic.DateDetailView):
context_object_name = 'book' context_object_name = 'book'

View File

@ -21,10 +21,12 @@ class Author(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class ArticleManager(models.Manager): class ArticleManager(models.Manager):
def get_queryset(self): def get_queryset(self):
return super(ArticleManager, self).get_queryset().filter(authors__name__icontains='sir') return super(ArticleManager, self).get_queryset().filter(authors__name__icontains='sir')
@python_2_unicode_compatible @python_2_unicode_compatible
class Article(models.Model): class Article(models.Model):
authors = models.ManyToManyField(Author) authors = models.ManyToManyField(Author)

View File

@ -4,9 +4,11 @@ from django.db import models
class Publisher(models.Model): class Publisher(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Author(models.Model): class Author(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Book(models.Model): class Book(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, related_name='books') authors = models.ManyToManyField(Author, related_name='books')

View File

@ -4,18 +4,23 @@ from django.core.exceptions import SuspiciousOperation
from django.db import connection, transaction from django.db import connection, transaction
from django.http import HttpResponse, StreamingHttpResponse from django.http import HttpResponse, StreamingHttpResponse
def regular(request): def regular(request):
return HttpResponse(b"regular content") return HttpResponse(b"regular content")
def streaming(request): def streaming(request):
return StreamingHttpResponse([b"streaming", b" ", b"content"]) return StreamingHttpResponse([b"streaming", b" ", b"content"])
def in_transaction(request): def in_transaction(request):
return HttpResponse(str(connection.in_atomic_block)) return HttpResponse(str(connection.in_atomic_block))
@transaction.non_atomic_requests @transaction.non_atomic_requests
def not_in_transaction(request): def not_in_transaction(request):
return HttpResponse(str(connection.in_atomic_block)) return HttpResponse(str(connection.in_atomic_block))
def suspicious(request): def suspicious(request):
raise SuspiciousOperation('dubious') raise SuspiciousOperation('dubious')

View File

@ -239,6 +239,7 @@ class QueryDictTests(unittest.TestCase):
self.assertEqual(copy.copy(q).encoding, 'iso-8859-15') self.assertEqual(copy.copy(q).encoding, 'iso-8859-15')
self.assertEqual(copy.deepcopy(q).encoding, 'iso-8859-15') self.assertEqual(copy.deepcopy(q).encoding, 'iso-8859-15')
class HttpResponseTests(unittest.TestCase): class HttpResponseTests(unittest.TestCase):
def test_headers_type(self): def test_headers_type(self):
@ -414,6 +415,7 @@ class HttpResponseTests(unittest.TestCase):
self.assertRaises(SuspiciousOperation, self.assertRaises(SuspiciousOperation,
HttpResponsePermanentRedirect, url) HttpResponsePermanentRedirect, url)
class HttpResponseSubclassesTests(TestCase): class HttpResponseSubclassesTests(TestCase):
def test_redirect(self): def test_redirect(self):
response = HttpResponseRedirect('/redirected/') response = HttpResponseRedirect('/redirected/')
@ -448,6 +450,7 @@ class HttpResponseSubclassesTests(TestCase):
content_type='text/html') content_type='text/html')
self.assertContains(response, 'Only the GET method is allowed', status_code=405) self.assertContains(response, 'Only the GET method is allowed', status_code=405)
class StreamingHttpResponseTests(TestCase): class StreamingHttpResponseTests(TestCase):
def test_streaming_response(self): def test_streaming_response(self):
r = StreamingHttpResponse(iter(['hello', 'world'])) r = StreamingHttpResponse(iter(['hello', 'world']))
@ -501,6 +504,7 @@ class StreamingHttpResponseTests(TestCase):
with self.assertRaises(Exception): with self.assertRaises(Exception):
r.tell() r.tell()
class FileCloseTests(TestCase): class FileCloseTests(TestCase):
def setUp(self): def setUp(self):
@ -566,6 +570,7 @@ class FileCloseTests(TestCase):
self.assertTrue(file1.closed) self.assertTrue(file1.closed)
self.assertTrue(file2.closed) self.assertTrue(file2.closed)
class CookieTests(unittest.TestCase): class CookieTests(unittest.TestCase):
def test_encode(self): def test_encode(self):
""" """

View File

@ -12,9 +12,11 @@ class I18nForm(forms.Form):
time_field = forms.TimeField(localize=True) time_field = forms.TimeField(localize=True)
integer_field = forms.IntegerField(localize=True) integer_field = forms.IntegerField(localize=True)
class SelectDateForm(forms.Form): class SelectDateForm(forms.Form):
date_field = forms.DateField(widget=SelectDateWidget) date_field = forms.DateField(widget=SelectDateWidget)
class CompanyForm(forms.ModelForm): class CompanyForm(forms.ModelForm):
cents_paid = forms.DecimalField(max_digits=4, decimal_places=2, localize=True) cents_paid = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)
products_delivered = forms.IntegerField(localize=True) products_delivered = forms.IntegerField(localize=True)

View File

@ -7,6 +7,7 @@ from django.utils.translation import ugettext_lazy as _
class TestModel(models.Model): class TestModel(models.Model):
text = models.CharField(max_length=10, default=_('Anything')) text = models.CharField(max_length=10, default=_('Anything'))
class Company(models.Model): class Company(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
date_added = models.DateTimeField(default=datetime(1799, 1, 31, 23, 59, 59, 0)) date_added = models.DateTimeField(default=datetime(1799, 1, 31, 23, 59, 59, 0))

View File

@ -21,6 +21,7 @@ from django.utils.translation import TranslatorCommentWarning
LOCALE = 'de' LOCALE = 'de'
has_xgettext = find_command('xgettext') has_xgettext = find_command('xgettext')
@skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests') @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
class ExtractorTests(SimpleTestCase): class ExtractorTests(SimpleTestCase):
@ -130,9 +131,10 @@ class BasicExtractorTests(ExtractorTests):
self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0) self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0)
with self.assertRaises(SyntaxError) as context_manager: with self.assertRaises(SyntaxError) as context_manager:
management.call_command('makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0) management.call_command('makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0)
six.assertRegex(self, str(context_manager.exception), six.assertRegex(
r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)' self, str(context_manager.exception),
) r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)'
)
# Check that the temporary file was cleaned up # Check that the temporary file was cleaned up
self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py')) self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py'))
@ -210,13 +212,16 @@ class BasicExtractorTests(ExtractorTests):
self.assertEqual(len(ws), 3) self.assertEqual(len(ws), 3)
for w in ws: for w in ws:
self.assertTrue(issubclass(w.category, TranslatorCommentWarning)) self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
six.assertRegex(self, str(ws[0].message), six.assertRegex(
self, str(ws[0].message),
r"The translator-targeted comment 'Translators: ignored i18n comment #1' \(file templates[/\\]comments.thtml, line 4\) was ignored, because it wasn't the last item on the line\." r"The translator-targeted comment 'Translators: ignored i18n comment #1' \(file templates[/\\]comments.thtml, line 4\) was ignored, because it wasn't the last item on the line\."
) )
six.assertRegex(self, str(ws[1].message), six.assertRegex(
self, str(ws[1].message),
r"The translator-targeted comment 'Translators: ignored i18n comment #3' \(file templates[/\\]comments.thtml, line 6\) was ignored, because it wasn't the last item on the line\." r"The translator-targeted comment 'Translators: ignored i18n comment #3' \(file templates[/\\]comments.thtml, line 6\) was ignored, because it wasn't the last item on the line\."
) )
six.assertRegex(self, str(ws[2].message), six.assertRegex(
self, str(ws[2].message),
r"The translator-targeted comment 'Translators: ignored i18n comment #4' \(file templates[/\\]comments.thtml, line 8\) was ignored, because it wasn't the last item on the line\." r"The translator-targeted comment 'Translators: ignored i18n comment #4' \(file templates[/\\]comments.thtml, line 8\) was ignored, because it wasn't the last item on the line\."
) )
# Now test .po file contents # Now test .po file contents
@ -281,6 +286,7 @@ class JavascriptExtractorTests(ExtractorTests):
self.assertMsgId("quz", po_contents) self.assertMsgId("quz", po_contents)
self.assertMsgId("foobar", po_contents) self.assertMsgId("foobar", po_contents)
class IgnoredExtractorTests(ExtractorTests): class IgnoredExtractorTests(ExtractorTests):
def test_ignore_option(self): def test_ignore_option(self):

View File

@ -956,12 +956,14 @@ class ResolutionOrderI18NTests(TransRealMixin, TestCase):
self.assertTrue(msgstr in result, ("The string '%s' isn't in the " self.assertTrue(msgstr in result, ("The string '%s' isn't in the "
"translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result))) "translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result)))
@override_settings(INSTALLED_APPS=['i18n.resolution'] + list(settings.INSTALLED_APPS)) @override_settings(INSTALLED_APPS=['i18n.resolution'] + list(settings.INSTALLED_APPS))
class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): class AppResolutionOrderI18NTests(ResolutionOrderI18NTests):
def test_app_translation(self): def test_app_translation(self):
self.assertUgettext('Date/time', 'APP') self.assertUgettext('Date/time', 'APP')
@override_settings(LOCALE_PATHS=extended_locale_paths) @override_settings(LOCALE_PATHS=extended_locale_paths)
class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
@ -973,6 +975,7 @@ class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
with self.settings(INSTALLED_APPS=extended_apps): with self.settings(INSTALLED_APPS=extended_apps):
self.assertUgettext('Time', 'LOCALE_PATHS') self.assertUgettext('Time', 'LOCALE_PATHS')
class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests):
def test_django_fallback(self): def test_django_fallback(self):

View File

@ -6,15 +6,18 @@ from django.utils.encoding import python_2_unicode_compatible
class School(models.Model): class School(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Parent(models.Model): class Parent(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Child(models.Model): class Child(models.Model):
mother = models.ForeignKey(Parent, related_name='mothers_children') mother = models.ForeignKey(Parent, related_name='mothers_children')
father = models.ForeignKey(Parent, related_name='fathers_children') father = models.ForeignKey(Parent, related_name='fathers_children')
school = models.ForeignKey(School) school = models.ForeignKey(School)
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@python_2_unicode_compatible @python_2_unicode_compatible
class Poet(models.Model): class Poet(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
@ -22,6 +25,7 @@ class Poet(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Poem(models.Model): class Poem(models.Model):
poet = models.ForeignKey(Poet) poet = models.ForeignKey(Poet)

Some files were not shown because too many files have changed in this diff Show More