Fixed E225 pep8 warnings.

This commit is contained in:
Tim Graham 2013-10-23 06:09:29 -04:00
parent 51d2e1fb23
commit ae48d77ef8
43 changed files with 102 additions and 91 deletions

View File

@ -456,7 +456,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
def exactly_two(np):
return np == 2
def two_to_three(np):
return np >= 2 and np <=3
return np >= 2 and np <= 3
if (lookup_type in self.distance_functions and
lookup_type != 'dwithin'):
return two_to_three(num_param)

View File

@ -32,7 +32,7 @@ class GeometryProxy(object):
if isinstance(geom_value, self._klass):
geom = geom_value
elif (geom_value is None) or (geom_value==''):
elif (geom_value is None) or (geom_value == ''):
geom = None
else:
# Otherwise, a Geometry object is built using the field's contents,

View File

@ -37,7 +37,7 @@ class OGRGeomType(object):
elif isinstance(type_input, six.string_types):
type_input = type_input.lower()
if type_input == 'geometry':
type_input='unknown'
type_input = 'unknown'
num = self._str_types.get(type_input, None)
if num is None:
raise OGRException('Invalid OGR String Type "%s"' % type_input)

View File

@ -67,5 +67,5 @@ islocal = int_output(lgdal.OSRIsLocal, [c_void_p])
isprojected = int_output(lgdal.OSRIsProjected, [c_void_p])
# Coordinate transformation
new_ct= srs_output(std_call('OCTNewCoordinateTransformation'), [c_void_p, c_void_p])
new_ct = srs_output(std_call('OCTNewCoordinateTransformation'), [c_void_p, c_void_p])
destroy_ct = void_output(std_call('OCTDestroyCoordinateTransformation'), [c_void_p], errcheck=False)

View File

@ -58,7 +58,7 @@ class LineString(GEOSGeometry):
# Creating a coordinate sequence object because it is easier to
# set the points using GEOSCoordSeq.__setitem__().
cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim==3))
cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim == 3))
for i in xrange(ncoords):
if numpy_coords:

View File

@ -14,7 +14,7 @@ prepared_destroy.restype = None
# Prepared geometry binary predicate support.
def prepared_predicate(func):
func.argtypes= [PREPGEOM_PTR, GEOM_PTR]
func.argtypes = [PREPGEOM_PTR, GEOM_PTR]
func.restype = c_char
func.errcheck = check_predicate
return func

View File

@ -12,7 +12,7 @@ class GoogleMapException(Exception):
# The default Google Maps URL (for the API javascript)
# TODO: Internationalize for Japan, UK, etc.
GOOGLE_MAPS_URL='http://maps.google.com/maps?file=api&v=%s&key='
GOOGLE_MAPS_URL = 'http://maps.google.com/maps?file=api&v=%s&key='
class GoogleMap(object):

View File

@ -52,7 +52,7 @@ class GEvent(object):
def __str__(self):
"Returns the parameter part of a GEvent."
return mark_safe('"%s", %s' %(self.event, self.action))
return mark_safe('"%s", %s' % (self.event, self.action))
@python_2_unicode_compatible
class GOverlayBase(object):
@ -303,7 +303,7 @@ class GMarker(GOverlayBase):
super(GMarker, self).__init__()
def latlng_from_coords(self, coords):
return 'new GLatLng(%s,%s)' %(coords[1], coords[0])
return 'new GLatLng(%s,%s)' % (coords[1], coords[0])
def options(self):
result = []

View File

@ -95,7 +95,7 @@ class GoogleZoom(object):
lon = (px[0] - npix) / self._degpp[zoom]
# Calculating the latitude value.
lat = RTOD * (2 * atan(exp((px[1] - npix)/ (-1.0 * self._radpp[zoom]))) - 0.5 * pi)
lat = RTOD * (2 * atan(exp((px[1] - npix) / (-1.0 * self._radpp[zoom]))) - 0.5 * pi)
# Returning the longitude, latitude coordinate pair.
return (lon, lat)

View File

@ -163,7 +163,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertFalse(invalid.is_valid())
self.assertTrue('Invalid geometry value' in str(invalid.errors))
for invalid in [geo for key, geo in self.geometries.items() if key!='point']:
for invalid in [geo for key, geo in self.geometries.items() if key != 'point']:
self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid())
def test_multipointfield(self):
@ -176,7 +176,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertMapWidget(form)
self.assertFalse(PointForm().is_valid())
for invalid in [geo for key, geo in self.geometries.items() if key!='multipoint']:
for invalid in [geo for key, geo in self.geometries.items() if key != 'multipoint']:
self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid())
def test_linestringfield(self):
@ -189,7 +189,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertMapWidget(form)
self.assertFalse(LineStringForm().is_valid())
for invalid in [geo for key, geo in self.geometries.items() if key!='linestring']:
for invalid in [geo for key, geo in self.geometries.items() if key != 'linestring']:
self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid())
def test_multilinestringfield(self):
@ -202,7 +202,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertMapWidget(form)
self.assertFalse(LineStringForm().is_valid())
for invalid in [geo for key, geo in self.geometries.items() if key!='multilinestring']:
for invalid in [geo for key, geo in self.geometries.items() if key != 'multilinestring']:
self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid())
def test_polygonfield(self):
@ -215,7 +215,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertMapWidget(form)
self.assertFalse(PolygonForm().is_valid())
for invalid in [geo for key, geo in self.geometries.items() if key!='polygon']:
for invalid in [geo for key, geo in self.geometries.items() if key != 'polygon']:
self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid())
def test_multipolygonfield(self):
@ -228,7 +228,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertMapWidget(form)
self.assertFalse(PolygonForm().is_valid())
for invalid in [geo for key, geo in self.geometries.items() if key!='multipolygon']:
for invalid in [geo for key, geo in self.geometries.items() if key != 'multipolygon']:
self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid())
def test_geometrycollectionfield(self):
@ -241,7 +241,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertMapWidget(form)
self.assertFalse(GeometryForm().is_valid())
for invalid in [geo for key, geo in self.geometries.items() if key!='geometrycollection']:
for invalid in [geo for key, geo in self.geometries.items() if key != 'geometrycollection']:
self.assertFalse(GeometryForm(data={'g': invalid.wkt}).is_valid())
def test_osm_widget(self):

View File

@ -272,5 +272,5 @@ def suite():
def run(verbosity=2):
unittest.TextTestRunner(verbosity=verbosity).run(suite())
if __name__=="__main__":
if __name__ == "__main__":
run()

View File

@ -214,11 +214,11 @@ class BaseTests(object):
@override_settings(
INSTALLED_APPS=filter(
lambda app:app!='django.contrib.messages', settings.INSTALLED_APPS),
lambda app: app != 'django.contrib.messages', settings.INSTALLED_APPS),
MIDDLEWARE_CLASSES=filter(
lambda m:'MessageMiddleware' not in m, settings.MIDDLEWARE_CLASSES),
lambda m: 'MessageMiddleware' not in m, settings.MIDDLEWARE_CLASSES),
TEMPLATE_CONTEXT_PROCESSORS=filter(
lambda p:'context_processors.messages' not in p,
lambda p: 'context_processors.messages' not in p,
settings.TEMPLATE_CONTEXT_PROCESSORS),
MESSAGE_LEVEL=constants.DEBUG
)
@ -239,11 +239,11 @@ class BaseTests(object):
@override_settings(
INSTALLED_APPS=filter(
lambda app:app!='django.contrib.messages', settings.INSTALLED_APPS),
lambda app: app != 'django.contrib.messages', settings.INSTALLED_APPS),
MIDDLEWARE_CLASSES=filter(
lambda m:'MessageMiddleware' not in m, settings.MIDDLEWARE_CLASSES),
lambda m: 'MessageMiddleware' not in m, settings.MIDDLEWARE_CLASSES),
TEMPLATE_CONTEXT_PROCESSORS=filter(
lambda p:'context_processors.messages' not in p,
lambda p: 'context_processors.messages' not in p,
settings.TEMPLATE_CONTEXT_PROCESSORS),
MESSAGE_LEVEL=constants.DEBUG
)

View File

@ -15,7 +15,7 @@ class Redirect(models.Model):
verbose_name = _('redirect')
verbose_name_plural = _('redirects')
db_table = 'django_redirect'
unique_together=(('site', 'old_path'),)
unique_together = (('site', 'old_path'),)
ordering = ('old_path',)
def __str__(self):

View File

@ -29,7 +29,7 @@ class CurrentSiteManager(models.Manager):
try:
field = self.model._meta.get_field(self.__field_name)
if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
raise TypeError("%s must be a ForeignKey or ManyToManyField." %self.__field_name)
raise TypeError("%s must be a ForeignKey or ManyToManyField." % self.__field_name)
except FieldDoesNotExist:
raise ValueError("%s couldn't find a field named %s in %s." %
(self.__class__.__name__, self.__field_name, self.model._meta.object_name))

View File

@ -138,7 +138,7 @@ class TranslatableFile(object):
if msgs:
if is_templatized:
# Remove '.py' suffix
if os.name =='nt':
if os.name == 'nt':
# Preserve '.\' prefix on Windows to respect gettext behavior
old = '#: ' + work_file
new = '#: ' + orig_file

View File

@ -83,7 +83,7 @@ class BoundMethodWeakref(object):
of already-referenced methods.
"""
key = cls.calculateKey(target)
current =cls._allInstances.get(key)
current = cls._allInstances.get(key)
if current is not None:
current.deletionMethods.append(onDelete)
return current

View File

@ -274,7 +274,7 @@ class PasswordInput(TextInput):
def render(self, name, value, attrs=None):
if not self.render_value:
value=None
value = None
return super(PasswordInput, self).render(name, value, attrs)
class HiddenInput(Input):

View File

@ -500,7 +500,7 @@ class ImmutableList(tuple):
extend = complain
insert = complain
pop = complain
remove= complain
remove = complain
sort = complain
reverse = complain

View File

@ -170,7 +170,7 @@ class TimeFormat(Formatter):
def u(self):
"Microseconds; i.e. '000000' to '999999'"
return '%06d' %self.data.microsecond
return '%06d' % self.data.microsecond
def Z(self):
"""

View File

@ -54,7 +54,7 @@ def _findall(text, substr):
if j == -1:
break
sites.append(j)
i=j+1
i = j + 1
return sites
def strftime(dt, fmt):

View File

@ -264,7 +264,7 @@ man_pages = [
# List of tuples (startdocname, targetname, title, author, dir_entry,
# description, category, toctree_only)
texinfo_documents=[(
texinfo_documents = [(
master_doc, "django", "", "", "Django",
"Documentation of the Django framework", "Web development", False
)]

View File

@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh
[flake8]
exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py
ignore=E124,E125,E127,E128,E225,E226,E241,E251,E302,E501,E203,E231,E261,E301,F401,F403,W601
ignore=E124,E125,E127,E128,E226,E241,E251,E302,E501,E203,E231,E261,E301,F401,F403,W601
[metadata]
license-file = LICENSE

View File

@ -107,7 +107,7 @@ class InlineWeakness(admin.TabularInline):
class QuestionInline(admin.TabularInline):
model = Question
readonly_fields=['call_me']
readonly_fields = ['call_me']
def call_me(self, obj):
return 'Callable in QuestionInline'
@ -122,7 +122,7 @@ class PollAdmin(admin.ModelAdmin):
class ChapterInline(admin.TabularInline):
model = Chapter
readonly_fields=['call_me']
readonly_fields = ['call_me']
def call_me(self, obj):
return 'Callable in ChapterInline'

View File

@ -193,7 +193,7 @@ class ValidationTestCase(TestCase):
def test_nonexistant_field_on_inline(self):
class CityInline(admin.TabularInline):
model = City
readonly_fields=['i_dont_exist'] # Missing attribute
readonly_fields = ['i_dont_exist'] # Missing attribute
self.assertRaisesMessage(ImproperlyConfigured,
str_prefix("CityInline.readonly_fields[0], %(_)s'i_dont_exist' is not a callable "

View File

@ -47,7 +47,7 @@ class ArticleInline(admin.TabularInline):
prepopulated_fields = {
'title' : ('content',)
}
fieldsets=(
fieldsets = (
('Some fields', {
'classes': ('collapse',),
'fields': ('title', 'content')
@ -74,7 +74,7 @@ class ChapterXtra1Admin(admin.ModelAdmin):
class ArticleAdmin(admin.ModelAdmin):
list_display = ('content', 'date', callable_year, 'model_year', 'modeladmin_year')
list_filter = ('date', 'section')
fieldsets=(
fieldsets = (
('Some fields', {
'classes': ('collapse',),
'fields': ('title', 'content')
@ -465,7 +465,7 @@ class WorkHourAdmin(admin.ModelAdmin):
class FoodDeliveryAdmin(admin.ModelAdmin):
list_display=('reference', 'driver', 'restaurant')
list_display = ('reference', 'driver', 'restaurant')
list_editable = ('driver', 'restaurant')

View File

@ -166,7 +166,7 @@ class AdminFormfieldForDBFieldTests(TestCase):
def test_m2m_widgets(self):
"""m2m fields help text as it applies to admin app (#9321)."""
class AdvisorAdmin(admin.ModelAdmin):
filter_vertical=['companies']
filter_vertical = ['companies']
self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple,
filter_vertical=['companies'])

View File

@ -496,9 +496,9 @@ class BackendTestCase(TestCase):
tbl = connection.introspection.table_name_converter(opts.db_table)
f1 = connection.ops.quote_name(opts.get_field('root').column)
f2 = connection.ops.quote_name(opts.get_field('square').column)
if paramstyle=='format':
if paramstyle == 'format':
query = 'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (tbl, f1, f2)
elif paramstyle=='pyformat':
elif paramstyle == 'pyformat':
query = 'INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)' % (tbl, f1, f2)
else:
raise ValueError("unsupported paramstyle in test")

View File

@ -1527,8 +1527,8 @@ class CacheI18nTest(TestCase):
self.assertEqual(get_cache_data, None)
# i18n tests
en_message ="Hello world!"
es_message ="Hola mundo!"
en_message = "Hello world!"
es_message = "Hola mundo!"
request = self._get_request_cache()
set_cache(request, 'en', en_message)

View File

@ -27,4 +27,4 @@ class BigChild(Primary):
class ChildProxy(Child):
class Meta:
proxy=True
proxy = True

View File

@ -69,4 +69,4 @@ class SaferefTests(unittest.TestCase):
def _closure(self, ref):
"""Dumb utility mechanism to increment deletion counter"""
self.closureCount +=1
self.closureCount += 1

View File

@ -57,8 +57,8 @@ class DistinctOnTests(TestCase):
# Does combining querysets work?
(
(Celebrity.objects.filter(fan__in=[self.fan1, self.fan2]).
distinct('name').order_by('name')
|Celebrity.objects.filter(fan__in=[self.fan3]).
distinct('name').order_by('name') |
Celebrity.objects.filter(fan__in=[self.fan3]).
distinct('name').order_by('name')),
['<Celebrity: c1>', '<Celebrity: c2>'],
),

View File

@ -224,7 +224,7 @@ class FTimeDeltaTests(TestCase):
e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime,
end=end, completed=end.date())
self.deltas.append(delta0)
self.delays.append(e0.start-
self.delays.append(e0.start -
datetime.datetime.combine(e0.assigned, midnight))
self.days_long.append(e0.completed-e0.assigned)
@ -239,7 +239,7 @@ class FTimeDeltaTests(TestCase):
e1 = Experiment.objects.create(name='e1', assigned=sday,
start=stime+delay, end=end, completed=end.date())
self.deltas.append(delta1)
self.delays.append(e1.start-
self.delays.append(e1.start -
datetime.datetime.combine(e1.assigned, midnight))
self.days_long.append(e1.completed-e1.assigned)
@ -249,7 +249,7 @@ class FTimeDeltaTests(TestCase):
assigned=sday-datetime.timedelta(3), start=stime, end=end,
completed=end.date())
self.deltas.append(delta2)
self.delays.append(e2.start-
self.delays.append(e2.start -
datetime.datetime.combine(e2.assigned, midnight))
self.days_long.append(e2.completed-e2.assigned)
@ -259,7 +259,7 @@ class FTimeDeltaTests(TestCase):
e3 = Experiment.objects.create(name='e3',
assigned=sday, start=stime+delay, end=end, completed=end.date())
self.deltas.append(delta3)
self.delays.append(e3.start-
self.delays.append(e3.start -
datetime.datetime.combine(e3.assigned, midnight))
self.days_long.append(e3.completed-e3.assigned)
@ -269,7 +269,7 @@ class FTimeDeltaTests(TestCase):
assigned=sday-datetime.timedelta(10), start=stime, end=end,
completed=end.date())
self.deltas.append(delta4)
self.delays.append(e4.start-
self.delays.append(e4.start -
datetime.datetime.combine(e4.assigned, midnight))
self.days_long.append(e4.completed-e4.assigned)
self.expnames = [e.name for e in Experiment.objects.all()]
@ -341,7 +341,7 @@ class FTimeDeltaTests(TestCase):
self.assertEqual(test_set, self.expnames[:i])
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))]
self.assertEqual(test_set, self.expnames[:i+1])

View File

@ -340,7 +340,10 @@ class FormsWidgetTestCase(TestCase):
</select>""")
# Choices can be nested one level in order to create HTML optgroups:
w.choices=(('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))))
w.choices = (
('outer1', 'Outer 1'),
('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2'))),
)
self.assertHTMLEqual(w.render('nestchoice', None), """<select name="nestchoice">
<option value="outer1">Outer 1</option>
<optgroup label="Group &quot;1&quot;">
@ -706,7 +709,11 @@ beatle J R Ringo False""")
def test_nested_choices(self):
# Choices can be nested for radio buttons:
w = RadioSelect()
w.choices=(('unknown', 'Unknown'), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))))
w.choices = (
('unknown', 'Unknown'),
('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))),
('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))),
)
self.assertHTMLEqual(w.render('nestchoice', 'dvd', attrs={'id':'media'}), """<ul id="media">
<li><label for="media_0"><input id="media_0" name="nestchoice" type="radio" value="unknown" /> Unknown</label></li>
<li>Audio<ul id="media_1">
@ -721,7 +728,11 @@ beatle J R Ringo False""")
# Choices can be nested for checkboxes:
w = CheckboxSelectMultiple()
w.choices=(('unknown', 'Unknown'), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))))
w.choices = (
('unknown', 'Unknown'),
('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))),
('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))),
)
self.assertHTMLEqual(w.render('nestchoice', ('vinyl', 'dvd'), attrs={'id':'media'}), """<ul id="media">
<li><label for="media_0"><input id="media_0" name="nestchoice" type="checkbox" value="unknown" /> Unknown</label></li>
<li>Audio<ul id="media_1">

View File

@ -37,8 +37,8 @@ class PoFileTests(MessageCompilationTests):
class PoFileContentsTests(MessageCompilationTests):
# Ticket #11240
LOCALE='fr'
MO_FILE='locale/%s/LC_MESSAGES/django.mo' % LOCALE
LOCALE = 'fr'
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def setUp(self):
super(PoFileContentsTests, self).setUp()
@ -53,8 +53,8 @@ class PercentRenderingTests(MessageCompilationTests):
# Ticket #11240 -- Testing rendering doesn't belong here but we are trying
# to keep tests for all the stack together
LOCALE='it'
MO_FILE='locale/%s/LC_MESSAGES/django.mo' % LOCALE
LOCALE = 'it'
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def setUp(self):
super(PercentRenderingTests, self).setUp()
@ -101,8 +101,8 @@ class MultipleLocaleCompilationTests(MessageCompilationTests):
class CompilationErrorHandling(MessageCompilationTests):
LOCALE='ja'
MO_FILE='locale/%s/LC_MESSAGES/django.mo' % LOCALE
LOCALE = 'ja'
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def setUp(self):
super(CompilationErrorHandling, self).setUp()

View File

@ -17,11 +17,11 @@ from django.utils.six import StringIO
from django.utils.translation import TranslatorCommentWarning
LOCALE='de'
LOCALE = 'de'
class ExtractorTests(SimpleTestCase):
PO_FILE='locale/%s/LC_MESSAGES/django.po' % LOCALE
PO_FILE = 'locale/%s/LC_MESSAGES/django.po' % LOCALE
def setUp(self):
self._cwd = os.getcwd()
@ -255,7 +255,7 @@ class BasicExtractorTests(ExtractorTests):
class JavascriptExtractorTests(ExtractorTests):
PO_FILE='locale/%s/LC_MESSAGES/djangojs.po' % LOCALE
PO_FILE = 'locale/%s/LC_MESSAGES/djangojs.po' % LOCALE
def test_javascript_literals(self):
os.chdir(self.test_dir)
@ -426,7 +426,7 @@ class LocationCommentsTests(ExtractorTests):
class KeepPotFileExtractorTests(ExtractorTests):
POT_FILE='locale/django.pot'
POT_FILE = 'locale/django.pot'
def setUp(self):
super(KeepPotFileExtractorTests, self).setUp()

View File

@ -80,8 +80,8 @@ class RelatedObjectUnicodeTests(TestCase):
Regression test for #6045: references to other models can be unicode
strings, providing they are directly convertible to ASCII.
"""
m1=UnicodeReferenceModel.objects.create()
m2=UnicodeReferenceModel.objects.create()
m1 = UnicodeReferenceModel.objects.create()
m2 = UnicodeReferenceModel.objects.create()
m2.others.add(m1) # used to cause an error (see ticket #6045)
m2.save()
list(m2.others.all()) # Force retrieval.

View File

@ -68,7 +68,7 @@ class M2MThroughTestCase(TestCase):
p = Person.objects.create(name="Bob")
g = Group.objects.create(name="Roll")
m =Membership.objects.create(person=p, group=g)
m = Membership.objects.create(person=p, group=g)
pks = {"p_pk": p.pk, "g_pk": g.pk, "m_pk": m.pk}

View File

@ -791,7 +791,7 @@ class ModelToDictTests(TestCase):
Tests for forms.models.model_to_dict
"""
def test_model_to_dict_many_to_many(self):
categories=[
categories = [
Category(name='TestName1', slug='TestName1', url='url1'),
Category(name='TestName2', slug='TestName2', url='url2'),
Category(name='TestName3', slug='TestName3', url='url3')

View File

@ -82,7 +82,7 @@ class ModelInheritanceTest(TestCase):
italian_restaurant.serves_gnocchi = False
italian_restaurant.save_base(raw=True)
place2.name='Derelict lot'
place2.name = 'Derelict lot'
place2.save_base(raw=True)
park.capacity = 50

View File

@ -39,7 +39,7 @@ class QueryTestCase(TestCase):
# Create a book on the default database using a save
dive = Book()
dive.title="Dive into Python"
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save()
@ -74,7 +74,7 @@ class QueryTestCase(TestCase):
# Create a book on the default database using a save
dive = Book()
dive.title="Dive into Python"
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save(using='other')
@ -1794,7 +1794,7 @@ class RouterAttributeErrorTestCase(TestCase):
def test_attribute_error_save(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up"
dive = Book()
dive.title="Dive into Python"
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
self.assertRaises(AttributeError, dive.save)

View File

@ -579,7 +579,7 @@ class Queries1Tests(BaseQuerysetTest):
['datetime.datetime(2007, 12, 19, 0, 0)', 'datetime.datetime(2007, 12, 20, 0, 0)']
)
name="one"
name = "one"
self.assertQuerysetEqual(
Item.objects.datetimes('created', 'day').extra(where=['name=%s'], params=[name]),
['datetime.datetime(2007, 12, 19, 0, 0)']
@ -2670,8 +2670,8 @@ class NullJoinPromotionOrTest(TestCase):
# b__c__name generates join to c, which the ORM tried to promote but
# failed as that join isn't nullable.
q_obj = (
Q(d__name='foo')|
Q(b__name='foo')|
Q(d__name='foo') |
Q(b__name='foo') |
Q(b__c__name='foo')
)
qset = ModelA.objects.filter(q_obj)

View File

@ -23,21 +23,21 @@ class SelectRelatedRegressTests(TestCase):
and include some unnecessary bonus joins).
"""
b=Building.objects.create(name='101')
dev1=Device.objects.create(name="router", building=b)
dev2=Device.objects.create(name="switch", building=b)
dev3=Device.objects.create(name="server", building=b)
port1=Port.objects.create(port_number='4',device=dev1)
port2=Port.objects.create(port_number='7',device=dev2)
port3=Port.objects.create(port_number='1',device=dev3)
c1=Connection.objects.create(start=port1, end=port2)
c2=Connection.objects.create(start=port2, end=port3)
b = Building.objects.create(name='101')
dev1 = Device.objects.create(name="router", building=b)
dev2 = Device.objects.create(name="switch", building=b)
dev3 = Device.objects.create(name="server", building=b)
port1 = Port.objects.create(port_number='4',device=dev1)
port2 = Port.objects.create(port_number='7',device=dev2)
port3 = Port.objects.create(port_number='1',device=dev3)
c1 = Connection.objects.create(start=port1, end=port2)
c2 = Connection.objects.create(start=port2, end=port3)
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id')
connections = Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id')
self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections],
[(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')])
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id')
connections = Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id')
self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections],
[(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')])

View File

@ -24,7 +24,7 @@ class BaseModelValidationTests(ValidationTestCase):
self.assertFailsValidation(mtv.full_clean, [NON_FIELD_ERRORS, 'name'])
def test_wrong_FK_value_raises_error(self):
mtv=ModelToValidate(number=10, name='Some Name', parent_id=3)
mtv = ModelToValidate(number=10, name='Some Name', parent_id=3)
self.assertFailsValidation(mtv.full_clean, ['parent'])
def test_correct_FK_value_validates(self):