From d89ba464dde14abc3aaf6d1e02202721f5fd2b3f Mon Sep 17 00:00:00 2001 From: Gary Wilson Jr Date: Thu, 28 May 2009 05:46:09 +0000 Subject: [PATCH 01/66] Changes to `ImageFileDescriptor` and `ImageField` to fix a few cases of setting image dimension fields. * Moved dimension field update logic out of `ImageFileDescriptor.__set__` and into its own method on `ImageField`. * New `ImageField.update_dimension_fields` method is attached to model instance's `post_init` signal so that: * Dimension fields are set when defined before the ImageField. * Dimension fields are set when the field is assigned in the model constructor (fixes #11196), but only if the dimension fields don't already have values, so we avoid updating the dimensions every time an object is loaded from the database (fixes #11084). * Clear dimension fields when the ImageField is set to None, which also causes dimension fields to be cleared when `ImageFieldFile.delete()` is used. * Added many more tests for ImageField that test edge cases we weren't testing before, and moved the ImageField tests out of `file_storage` and into their own module within `model_fields`. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10858 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/files.py | 133 ++++-- tests/modeltests/model_forms/models.py | 21 +- tests/regressiontests/file_storage/models.py | 93 ---- tests/regressiontests/model_fields/4x8.png | Bin 0 -> 87 bytes tests/regressiontests/model_fields/8x4.png | Bin 0 -> 87 bytes .../model_fields/imagefield.py | 403 ++++++++++++++++++ tests/regressiontests/model_fields/models.py | 107 ++++- tests/regressiontests/model_fields/tests.py | 16 +- 8 files changed, 621 insertions(+), 152 deletions(-) create mode 100644 tests/regressiontests/model_fields/4x8.png create mode 100644 tests/regressiontests/model_fields/8x4.png create mode 100644 tests/regressiontests/model_fields/imagefield.py diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py index 61a903e36c..aab4f3789f 100644 --- a/django/db/models/fields/files.py +++ b/django/db/models/fields/files.py @@ -142,13 +142,13 @@ class FileDescriptor(object): """ The descriptor for the file attribute on the model instance. Returns a FieldFile when accessed so you can do stuff like:: - + >>> instance.file.size - + Assigns a file object on assignment so you can do:: - + >>> instance.file = File(...) - + """ def __init__(self, field): self.field = field @@ -156,9 +156,9 @@ class FileDescriptor(object): def __get__(self, instance=None, owner=None): if instance is None: raise AttributeError( - "The '%s' attribute can only be accessed from %s instances." + "The '%s' attribute can only be accessed from %s instances." % (self.field.name, owner.__name__)) - + # This is slightly complicated, so worth an explanation. # instance.file`needs to ultimately return some instance of `File`, # probably a subclass. Additionally, this returned object needs to have @@ -168,8 +168,8 @@ class FileDescriptor(object): # peek below you can see that we're not. So depending on the current # value of the field we have to dynamically construct some sort of # "thing" to return. - - # The instance dict contains whatever was originally assigned + + # The instance dict contains whatever was originally assigned # in __set__. file = instance.__dict__[self.field.name] @@ -186,14 +186,14 @@ class FileDescriptor(object): # Other types of files may be assigned as well, but they need to have # the FieldFile interface added to the. Thus, we wrap any other type of - # File inside a FieldFile (well, the field's attr_class, which is + # File inside a FieldFile (well, the field's attr_class, which is # usually FieldFile). elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.name] = file_copy - + # Finally, because of the (some would say boneheaded) way pickle works, # the underlying FieldFile might not actually itself have an associated # file. So we need to reset the details of the FieldFile in those cases. @@ -201,7 +201,7 @@ class FileDescriptor(object): file.instance = instance file.field = self.field file.storage = self.field.storage - + # That was fun, wasn't it? return instance.__dict__[self.field.name] @@ -212,7 +212,7 @@ class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile - + # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor @@ -300,40 +300,20 @@ class ImageFileDescriptor(FileDescriptor): assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): + previous_file = instance.__dict__.get(self.field.name) super(ImageFileDescriptor, self).__set__(instance, value) - - # The rest of this method deals with width/height fields, so we can - # bail early if neither is used. - if not self.field.width_field and not self.field.height_field: - return - - # We need to call the descriptor's __get__ to coerce this assigned - # value into an instance of the right type (an ImageFieldFile, in this - # case). - value = self.__get__(instance) - - if not value: - return - - # Get the image dimensions, making sure to leave the file in the same - # state (opened or closed) that we got it in. However, we *don't* rewind - # the file pointer if the file is already open. This is in keeping with - # most Python standard library file operations that leave it up to the - # user code to reset file pointers after operations that move it. - from django.core.files.images import get_image_dimensions - close = value.closed - value.open() - try: - width, height = get_image_dimensions(value) - finally: - if close: - value.close() - - # Update the width and height fields - if self.field.width_field: - setattr(value.instance, self.field.width_field, width) - if self.field.height_field: - setattr(value.instance, self.field.height_field, height) + + # To prevent recalculating image dimensions when we are instantiating + # an object from the database (bug #11084), only update dimensions if + # the field had a value before this assignment. Since the default + # value for FileField subclasses is an instance of field.attr_class, + # previous_file will only be None when we are called from + # Model.__init__(). The ImageField.update_dimension_fields method + # hooked up to the post_init signal handles the Model.__init__() cases. + # Assignment happening outside of Model.__init__() will trigger the + # update right here. + if previous_file is not None: + self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): @@ -350,6 +330,69 @@ class ImageField(FileField): self.width_field, self.height_field = width_field, height_field FileField.__init__(self, verbose_name, name, **kwargs) + def contribute_to_class(self, cls, name): + super(ImageField, self).contribute_to_class(cls, name) + # Attach update_dimension_fields so that dimension fields declared + # after their corresponding image field don't stay cleared by + # Model.__init__, see bug #11196. + signals.post_init.connect(self.update_dimension_fields, sender=cls) + + def update_dimension_fields(self, instance, force=False, *args, **kwargs): + """ + Updates field's width and height fields, if defined. + + This method is hooked up to model's post_init signal to update + dimensions after instantiating a model instance. However, dimensions + won't be updated if the dimensions fields are already populated. This + avoids unnecessary recalculation when loading an object from the + database. + + Dimensions can be forced to update with force=True, which is how + ImageFileDescriptor.__set__ calls this method. + """ + # Nothing to update if the field doesn't have have dimension fields. + has_dimension_fields = self.width_field or self.height_field + if not has_dimension_fields: + return + + # getattr will call the ImageFileDescriptor's __get__ method, which + # coerces the assigned value into an instance of self.attr_class + # (ImageFieldFile in this case). + file = getattr(instance, self.attname) + + # Nothing to update if we have no file and not being forced to update. + if not file and not force: + return + + dimension_fields_filled = not( + (self.width_field and not getattr(instance, self.width_field)) + or (self.height_field and not getattr(instance, self.height_field)) + ) + # When both dimension fields have values, we are most likely loading + # data from the database or updating an image field that already had + # an image stored. In the first case, we don't want to update the + # dimension fields because we are already getting their values from the + # database. In the second case, we do want to update the dimensions + # fields and will skip this return because force will be True since we + # were called from ImageFileDescriptor.__set__. + if dimension_fields_filled and not force: + return + + # file should be an instance of ImageFieldFile or should be None. + if file: + width = file.width + height = file.height + else: + # No file, so clear dimensions fields. + width = None + height = None + + # Update the width and height fields. + if self.width_field: + setattr(instance, self.width_field, width) + if self.height_field: + setattr(instance, self.height_field, height) + def formfield(self, **kwargs): defaults = {'form_class': forms.ImageField} defaults.update(kwargs) diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index 95fda273f0..0fd24c18ad 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -1175,8 +1175,9 @@ True >>> instance.height 16 -# Delete the current file since this is not done by Django. ->>> instance.image.delete() +# Delete the current file since this is not done by Django, but don't save +# because the dimension fields are not null=True. +>>> instance.image.delete(save=False) >>> f = ImageFileForm(data={'description': u'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}) >>> f.is_valid() @@ -1207,9 +1208,9 @@ True >>> instance.width 16 -# Delete the current image since this is not done by Django. - ->>> instance.image.delete() +# Delete the current file since this is not done by Django, but don't save +# because the dimension fields are not null=True. +>>> instance.image.delete(save=False) # Override the file by uploading a new one. @@ -1224,8 +1225,9 @@ True >>> instance.width 48 -# Delete the current file since this is not done by Django. ->>> instance.image.delete() +# Delete the current file since this is not done by Django, but don't save +# because the dimension fields are not null=True. +>>> instance.image.delete(save=False) >>> instance.delete() >>> f = ImageFileForm(data={'description': u'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}) @@ -1239,8 +1241,9 @@ True >>> instance.width 48 -# Delete the current file since this is not done by Django. ->>> instance.image.delete() +# Delete the current file since this is not done by Django, but don't save +# because the dimension fields are not null=True. +>>> instance.image.delete(save=False) >>> instance.delete() # Test the non-required ImageField diff --git a/tests/regressiontests/file_storage/models.py b/tests/regressiontests/file_storage/models.py index 32af5d7588..e69de29bb2 100644 --- a/tests/regressiontests/file_storage/models.py +++ b/tests/regressiontests/file_storage/models.py @@ -1,93 +0,0 @@ -import os -import tempfile -import shutil -from django.db import models -from django.core.files.storage import FileSystemStorage -from django.core.files.base import ContentFile - -# Test for correct behavior of width_field/height_field. -# Of course, we can't run this without PIL. - -try: - # Checking for the existence of Image is enough for CPython, but - # for PyPy, you need to check for the underlying modules - from PIL import Image, _imaging -except ImportError: - Image = None - -# If we have PIL, do these tests -if Image: - temp_storage_dir = tempfile.mkdtemp() - temp_storage = FileSystemStorage(temp_storage_dir) - - class Person(models.Model): - name = models.CharField(max_length=50) - mugshot = models.ImageField(storage=temp_storage, upload_to='tests', - height_field='mug_height', - width_field='mug_width') - mug_height = models.PositiveSmallIntegerField() - mug_width = models.PositiveSmallIntegerField() - - __test__ = {'API_TESTS': """ ->>> from django.core.files import File ->>> image_data = open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb').read() ->>> p = Person(name="Joe") ->>> p.mugshot.save("mug", ContentFile(image_data)) ->>> p.mugshot.width -16 ->>> p.mugshot.height -16 ->>> p.mug_height -16 ->>> p.mug_width -16 - -# Bug #9786: Ensure '==' and '!=' work correctly. ->>> image_data = open(os.path.join(os.path.dirname(__file__), "test1.png"), 'rb').read() ->>> p1 = Person(name="Bob") ->>> p1.mugshot.save("mug", ContentFile(image_data)) ->>> p2 = Person.objects.get(name="Joe") ->>> p.mugshot == p2.mugshot -True ->>> p.mugshot != p2.mugshot -False ->>> p.mugshot != p1.mugshot -True - -Bug #9508: Similarly to the previous test, make sure hash() works as expected -(equal items must hash to the same value). ->>> hash(p.mugshot) == hash(p2.mugshot) -True - -# Bug #8175: correctly delete files that have been removed off the file system. ->>> import os ->>> p2 = Person(name="Fred") ->>> p2.mugshot.save("shot", ContentFile(image_data)) ->>> os.remove(p2.mugshot.path) ->>> p2.delete() - -# Bug #8534: FileField.size should not leave the file open. ->>> p3 = Person(name="Joan") ->>> p3.mugshot.save("shot", ContentFile(image_data)) - -# Get a "clean" model instance ->>> p3 = Person.objects.get(name="Joan") - -# It won't have an opened file. ->>> p3.mugshot.closed -True - -# After asking for the size, the file should still be closed. ->>> _ = p3.mugshot.size ->>> p3.mugshot.closed -True - -# Make sure that wrapping the file in a file still works ->>> p3.mugshot.file.open() ->>> p = Person.objects.create(name="Bob The Builder", mugshot=File(p3.mugshot.file)) ->>> p.save() ->>> p3.mugshot.file.close() - -# Delete all test files ->>> shutil.rmtree(temp_storage_dir) -"""} diff --git a/tests/regressiontests/model_fields/4x8.png b/tests/regressiontests/model_fields/4x8.png new file mode 100644 index 0000000000000000000000000000000000000000..ffce444d487d9c39a6c060b200e5bf7a1b18c9c0 GIT binary patch literal 87 zcmeAS@N?(olHy`uVBq!ia0vp^EI`b`!2~1&15bhk7>k44ofy`glX(f`2zt6WhHzX@ i{&T*8!H37>F#|)EBO|}3Wal!VB!j1`pUXO@geCyuc@ypc literal 0 HcmV?d00001 diff --git a/tests/regressiontests/model_fields/8x4.png b/tests/regressiontests/model_fields/8x4.png new file mode 100644 index 0000000000000000000000000000000000000000..60e6d69ee1da4a154ab87c29e347e76cdb76169c GIT binary patch literal 87 zcmeAS@N?(olHy`uVBq!ia0vp^96-#%!2~32*1ud1q!^2X+?^QKos)S9 Date: Thu, 28 May 2009 16:03:28 +0000 Subject: [PATCH 02/66] Updated Argentinian spanish translation, 100% complete as of r10858. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10859 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- .../conf/locale/es_AR/LC_MESSAGES/django.mo | Bin 63078 -> 66901 bytes .../conf/locale/es_AR/LC_MESSAGES/django.po | 774 +++++++++++------- 2 files changed, 499 insertions(+), 275 deletions(-) diff --git a/django/conf/locale/es_AR/LC_MESSAGES/django.mo b/django/conf/locale/es_AR/LC_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>!yKsGe zUr1C-KX1=A%Y2>NX7uy@+wQWz_g2R`zUrM``FlrpJ@304-7vs=AU4!HIrgP*Uyqjo zzLR|(`1#KF>lEZIo6z64En&F7uh+0&{Jecel=p2Lk>KyGI(lMY`H1*I5fyz$M=$pG z4)pkZWydA@`2r_A4)DF6e9-UT9A3vyPw0GIe zMZRvcCI^Z-j_SC z`UdR|OXjV*FU0rP-u!;P?)&E?^A0~8>dX60Yk%+6#5BHLiPwXY)fzH5#=G#uUGLFr_Jv7>##QWg+b>H>BYWsOB zy`1bj_i|#OdbaP~uXkLu)4m@k7||qtQ1sB4SntUHmdtD9S7zR1zr-(^`uPPV`#*R4 BCA$Cs diff --git a/django/conf/locale/es_AR/LC_MESSAGES/django.po b/django/conf/locale/es_AR/LC_MESSAGES/django.po index f92735adc6..d6726ab57b 100644 --- a/django/conf/locale/es_AR/LC_MESSAGES/django.po +++ b/django/conf/locale/es_AR/LC_MESSAGES/django.po @@ -6,8 +6,8 @@ msgid "" msgstr "" "Project-Id-Version: Django\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2008-11-13 18:20-0200\n" -"PO-Revision-Date: 2008-11-13 18:27-0200\n" +"POT-Creation-Date: 2009-05-28 12:30-0300\n" +"PO-Revision-Date: 2009-05-05 20:35-0300\n" "Last-Translator: Ramiro Morales \n" "Language-Team: Django-I18N \n" "MIME-Version: 1.0\n" @@ -100,121 +100,139 @@ msgid "Hebrew" msgstr "hebreo" #: conf/global_settings.py:65 +msgid "Hindi" +msgstr "Hindi" + +#: conf/global_settings.py:66 msgid "Croatian" msgstr "croata" -#: conf/global_settings.py:66 +#: conf/global_settings.py:67 msgid "Icelandic" msgstr "islandés" -#: conf/global_settings.py:67 +#: conf/global_settings.py:68 msgid "Italian" msgstr "italiano" -#: conf/global_settings.py:68 +#: conf/global_settings.py:69 msgid "Japanese" msgstr "japonés" -#: conf/global_settings.py:69 +#: conf/global_settings.py:70 msgid "Georgian" msgstr "georgiano" -#: conf/global_settings.py:70 +#: conf/global_settings.py:71 msgid "Korean" msgstr "koreano" -#: conf/global_settings.py:71 +#: conf/global_settings.py:72 msgid "Khmer" msgstr "jémer" -#: conf/global_settings.py:72 +#: conf/global_settings.py:73 msgid "Kannada" msgstr "canarés" -#: conf/global_settings.py:73 +#: conf/global_settings.py:74 msgid "Latvian" msgstr "letón" -#: conf/global_settings.py:74 +#: conf/global_settings.py:75 msgid "Lithuanian" msgstr "lituano" -#: conf/global_settings.py:75 +#: conf/global_settings.py:76 msgid "Macedonian" msgstr "macedonio" -#: conf/global_settings.py:76 +#: conf/global_settings.py:77 msgid "Dutch" msgstr "holandés" -#: conf/global_settings.py:77 +#: conf/global_settings.py:78 msgid "Norwegian" msgstr "noruego" -#: conf/global_settings.py:78 +#: conf/global_settings.py:79 msgid "Polish" msgstr "polaco" -#: conf/global_settings.py:79 +#: conf/global_settings.py:80 msgid "Portuguese" msgstr "portugués" -#: conf/global_settings.py:80 +#: conf/global_settings.py:81 msgid "Brazilian Portuguese" msgstr "portugués de Brasil" -#: conf/global_settings.py:81 +#: conf/global_settings.py:82 msgid "Romanian" msgstr "rumano" -#: conf/global_settings.py:82 +#: conf/global_settings.py:83 msgid "Russian" msgstr "ruso" -#: conf/global_settings.py:83 +#: conf/global_settings.py:84 msgid "Slovak" msgstr "eslovaco" -#: conf/global_settings.py:84 +#: conf/global_settings.py:85 msgid "Slovenian" msgstr "esloveno" -#: conf/global_settings.py:85 +#: conf/global_settings.py:86 msgid "Serbian" msgstr "serbio" -#: conf/global_settings.py:86 +#: conf/global_settings.py:87 msgid "Swedish" msgstr "sueco" -#: conf/global_settings.py:87 +#: conf/global_settings.py:88 msgid "Tamil" msgstr "tamil" -#: conf/global_settings.py:88 +#: conf/global_settings.py:89 msgid "Telugu" msgstr "telugu" -#: conf/global_settings.py:89 +#: conf/global_settings.py:90 msgid "Thai" msgstr "tailandés" -#: conf/global_settings.py:90 +#: conf/global_settings.py:91 msgid "Turkish" msgstr "turco" -#: conf/global_settings.py:91 +#: conf/global_settings.py:92 msgid "Ukrainian" msgstr "ucraniano" -#: conf/global_settings.py:92 +#: conf/global_settings.py:93 msgid "Simplified Chinese" msgstr "chino simplificado" -#: conf/global_settings.py:93 +#: conf/global_settings.py:94 msgid "Traditional Chinese" msgstr "chino tradicional" +#: contrib/admin/actions.py:60 +#, python-format +msgid "Successfully deleted %(count)d %(items)s." +msgstr "Se eliminaron con éxito %(count)d %(items)s." + +#: contrib/admin/actions.py:67 contrib/admin/options.py:1025 +msgid "Are you sure?" +msgstr "¿Está seguro?" + +#: contrib/admin/actions.py:85 +#, python-format +msgid "Delete selected %(verbose_name_plural)s" +msgstr "Eliminar %(verbose_name_plural)s seleccionados/as" + #: contrib/admin/filterspecs.py:44 #, python-format msgid "" @@ -224,43 +242,47 @@ msgstr "" "

Por %s:

\n" "
    \n" -#: contrib/admin/filterspecs.py:74 contrib/admin/filterspecs.py:91 -#: contrib/admin/filterspecs.py:146 contrib/admin/filterspecs.py:172 +#: contrib/admin/filterspecs.py:75 contrib/admin/filterspecs.py:92 +#: contrib/admin/filterspecs.py:147 contrib/admin/filterspecs.py:173 msgid "All" msgstr "Todos/as" -#: contrib/admin/filterspecs.py:112 +#: contrib/admin/filterspecs.py:113 msgid "Any date" msgstr "Cualquier fecha" -#: contrib/admin/filterspecs.py:113 +#: contrib/admin/filterspecs.py:114 msgid "Today" msgstr "Hoy" -#: contrib/admin/filterspecs.py:116 +#: contrib/admin/filterspecs.py:117 msgid "Past 7 days" msgstr "Últimos 7 días" -#: contrib/admin/filterspecs.py:118 +#: contrib/admin/filterspecs.py:119 msgid "This month" msgstr "Este mes" -#: contrib/admin/filterspecs.py:120 +#: contrib/admin/filterspecs.py:121 msgid "This year" msgstr "Este año" -#: contrib/admin/filterspecs.py:146 forms/widgets.py:390 +#: contrib/admin/filterspecs.py:147 forms/widgets.py:434 msgid "Yes" msgstr "Sí" -#: contrib/admin/filterspecs.py:146 forms/widgets.py:390 +#: contrib/admin/filterspecs.py:147 forms/widgets.py:434 msgid "No" msgstr "No" -#: contrib/admin/filterspecs.py:153 forms/widgets.py:390 +#: contrib/admin/filterspecs.py:154 forms/widgets.py:434 msgid "Unknown" msgstr "Desconocido" +#: contrib/admin/helpers.py:14 +msgid "Action:" +msgstr "Acción:" + #: contrib/admin/models.py:19 msgid "action time" msgstr "hora de la acción" @@ -289,60 +311,61 @@ msgstr "entrada de registro" msgid "log entries" msgstr "entradas de registro" -#: contrib/admin/options.py:60 contrib/admin/options.py:121 +#: contrib/admin/options.py:133 contrib/admin/options.py:147 msgid "None" msgstr "Ninguno" -#: contrib/admin/options.py:338 +#: contrib/admin/options.py:519 #, python-format msgid "Changed %s." msgstr "Modifica %s." -#: contrib/admin/options.py:338 contrib/admin/options.py:348 -#: contrib/comments/templates/comments/preview.html:15 forms/models.py:288 +#: contrib/admin/options.py:519 contrib/admin/options.py:529 +#: contrib/comments/templates/comments/preview.html:16 forms/models.py:388 +#: forms/models.py:587 msgid "and" msgstr "y" -#: contrib/admin/options.py:343 +#: contrib/admin/options.py:524 #, python-format msgid "Added %(name)s \"%(object)s\"." msgstr "Se agregó %(name)s \"%(object)s\"." -#: contrib/admin/options.py:347 +#: contrib/admin/options.py:528 #, python-format msgid "Changed %(list)s for %(name)s \"%(object)s\"." msgstr "Se modificaron %(list)s en %(name)s \"%(object)s\"." -#: contrib/admin/options.py:352 +#: contrib/admin/options.py:533 #, python-format msgid "Deleted %(name)s \"%(object)s\"." msgstr "Se eliminó %(name)s \"%(object)s\"." -#: contrib/admin/options.py:356 +#: contrib/admin/options.py:537 msgid "No fields changed." msgstr "No ha modificado ningún campo." -#: contrib/admin/options.py:417 contrib/auth/admin.py:51 +#: contrib/admin/options.py:598 contrib/auth/admin.py:67 #, python-format msgid "The %(name)s \"%(obj)s\" was added successfully." msgstr "Se agregó con éxito %(name)s \"%(obj)s\"." -#: contrib/admin/options.py:421 contrib/admin/options.py:454 -#: contrib/auth/admin.py:59 +#: contrib/admin/options.py:602 contrib/admin/options.py:635 +#: contrib/auth/admin.py:75 msgid "You may edit it again below." msgstr "Puede modificarlo/a nuevamente abajo." -#: contrib/admin/options.py:431 contrib/admin/options.py:464 +#: contrib/admin/options.py:612 contrib/admin/options.py:645 #, python-format msgid "You may add another %s below." msgstr "Puede agregar otro/a %s abajo." -#: contrib/admin/options.py:452 +#: contrib/admin/options.py:633 #, python-format msgid "The %(name)s \"%(obj)s\" was changed successfully." msgstr "Se modificó con éxito %(name)s \"%(obj)s\"." -#: contrib/admin/options.py:460 +#: contrib/admin/options.py:641 #, python-format msgid "" "The %(name)s \"%(obj)s\" was added successfully. You may edit it again below." @@ -350,40 +373,43 @@ msgstr "" "Se agregó con éxito %(name)s \"%(obj)s\". Puede modificarlo/a nuevamente " "abajo." -#: contrib/admin/options.py:528 +#: contrib/admin/options.py:772 #, python-format msgid "Add %s" msgstr "Agregar %s" -#: contrib/admin/options.py:559 contrib/admin/options.py:673 +#: contrib/admin/options.py:803 contrib/admin/options.py:1003 #, python-format msgid "%(name)s object with primary key %(key)r does not exist." msgstr "No existe un objeto %(name)s con una clave primaria %(key)r." -#: contrib/admin/options.py:606 +#: contrib/admin/options.py:860 #, python-format msgid "Change %s" msgstr "Modificar %s" -#: contrib/admin/options.py:638 +#: contrib/admin/options.py:904 msgid "Database error" msgstr "Error de base de datos" -#: contrib/admin/options.py:688 +#: contrib/admin/options.py:940 +#, python-format +msgid "%(count)s %(name)s was changed successfully." +msgid_plural "%(count)s %(name)s were changed successfully." +msgstr[0] "Se ha modificado con éxito %(count)s %(name)s." +msgstr[1] "Se han modificado con éxito %(count)s %(name)s." + +#: contrib/admin/options.py:1018 #, python-format msgid "The %(name)s \"%(obj)s\" was deleted successfully." msgstr "Se eliminó con éxito %(name)s \"%(obj)s\"." -#: contrib/admin/options.py:695 -msgid "Are you sure?" -msgstr "¿Está seguro?" - -#: contrib/admin/options.py:724 +#: contrib/admin/options.py:1054 #, python-format msgid "Change history: %s" msgstr "Historia de modificaciones: %s" -#: contrib/admin/sites.py:16 contrib/admin/views/decorators.py:14 +#: contrib/admin/sites.py:20 contrib/admin/views/decorators.py:14 #: contrib/auth/forms.py:80 msgid "" "Please enter a correct username and password. Note that both fields are case-" @@ -392,11 +418,11 @@ msgstr "" "Por favor introduzca un nombre de usuario y una contraseña correctos. Note " "que ambos campos son sensibles a mayúsculas/minúsculas." -#: contrib/admin/sites.py:226 contrib/admin/views/decorators.py:40 +#: contrib/admin/sites.py:278 contrib/admin/views/decorators.py:40 msgid "Please log in again, because your session has expired." msgstr "Por favor, identifíquese de nuevo porque su sesión ha caducado." -#: contrib/admin/sites.py:233 contrib/admin/views/decorators.py:47 +#: contrib/admin/sites.py:285 contrib/admin/views/decorators.py:47 msgid "" "Looks like your browser isn't configured to accept cookies. Please enable " "cookies, reload this page, and try again." @@ -404,64 +430,64 @@ msgstr "" "Parece que su navegador no está configurado para aceptar cookies. Por favor " "actívelas, recargue esta página, e inténtelo de nuevo." -#: contrib/admin/sites.py:249 contrib/admin/sites.py:255 +#: contrib/admin/sites.py:301 contrib/admin/sites.py:307 #: contrib/admin/views/decorators.py:66 msgid "Usernames cannot contain the '@' character." msgstr "Los nombres de usuario no pueden contener el carácter '@'." -#: contrib/admin/sites.py:252 contrib/admin/views/decorators.py:62 +#: contrib/admin/sites.py:304 contrib/admin/views/decorators.py:62 #, python-format msgid "Your e-mail address is not your username. Try '%s' instead." msgstr "" "Su dirección de correo electrónico no es su nombre de usuario. Intente " "nuevamente usando '%s'." -#: contrib/admin/sites.py:312 +#: contrib/admin/sites.py:360 msgid "Site administration" msgstr "Administración de sitio" -#: contrib/admin/sites.py:325 contrib/admin/templates/admin/login.html:26 +#: contrib/admin/sites.py:373 contrib/admin/templates/admin/login.html:26 #: contrib/admin/templates/registration/password_reset_complete.html:14 #: contrib/admin/views/decorators.py:20 msgid "Log in" msgstr "Identificarse" -#: contrib/admin/sites.py:372 +#: contrib/admin/sites.py:417 #, python-format msgid "%s administration" msgstr "Administración de %s" -#: contrib/admin/util.py:138 +#: contrib/admin/util.py:168 #, python-format msgid "One or more %(fieldname)s in %(name)s: %(obj)s" msgstr "Uno o más %(fieldname)s en %(name)s: %(obj)s" -#: contrib/admin/util.py:143 +#: contrib/admin/util.py:173 #, python-format msgid "One or more %(fieldname)s in %(name)s:" msgstr "Uno o más %(fieldname)s en %(name)s:" -#: contrib/admin/widgets.py:70 +#: contrib/admin/widgets.py:71 msgid "Date:" msgstr "Fecha:" -#: contrib/admin/widgets.py:70 +#: contrib/admin/widgets.py:71 msgid "Time:" msgstr "Hora:" -#: contrib/admin/widgets.py:94 +#: contrib/admin/widgets.py:95 msgid "Currently:" msgstr "Actualmente" -#: contrib/admin/widgets.py:94 +#: contrib/admin/widgets.py:95 msgid "Change:" msgstr "Modificar:" -#: contrib/admin/widgets.py:123 +#: contrib/admin/widgets.py:124 msgid "Lookup" msgstr "Buscar" -#: contrib/admin/widgets.py:230 +#: contrib/admin/widgets.py:236 msgid "Add Another" msgstr "Agregar otro/a" @@ -478,8 +504,9 @@ msgstr "Lo sentimos, pero no se encuentra la página solicitada." #: contrib/admin/templates/admin/app_index.html:8 #: contrib/admin/templates/admin/base.html:31 #: contrib/admin/templates/admin/change_form.html:17 -#: contrib/admin/templates/admin/change_list.html:8 +#: contrib/admin/templates/admin/change_list.html:25 #: contrib/admin/templates/admin/delete_confirmation.html:6 +#: contrib/admin/templates/admin/delete_selected_confirmation.html:6 #: contrib/admin/templates/admin/invalid_setup.html:4 #: contrib/admin/templates/admin/object_history.html:6 #: contrib/admin/templates/admin/auth/user/change_password.html:10 @@ -515,6 +542,14 @@ msgstr "" "mediante correo electrónico y debería ser solucionado en breve. Gracias por " "su paciencia." +#: contrib/admin/templates/admin/actions.html:4 +msgid "Run the selected action" +msgstr "Ejecutar la acción seleccionada" + +#: contrib/admin/templates/admin/actions.html:4 +msgid "Go" +msgstr "Ejecutar" + #: contrib/admin/templates/admin/app_index.html:10 #: contrib/admin/templates/admin/index.html:19 #, python-format @@ -533,8 +568,8 @@ msgid "Documentation" msgstr "Documentación" #: contrib/admin/templates/admin/base.html:26 -#: contrib/admin/templates/admin/auth/user/change_password.html:13 -#: contrib/admin/templates/admin/auth/user/change_password.html:46 +#: contrib/admin/templates/admin/auth/user/change_password.html:14 +#: contrib/admin/templates/admin/auth/user/change_password.html:47 #: contrib/admin/templates/registration/password_change_done.html:3 #: contrib/admin/templates/registration/password_change_form.html:3 msgid "Change password" @@ -571,23 +606,24 @@ msgid "View on site" msgstr "Ver en el sitio" #: contrib/admin/templates/admin/change_form.html:38 -#: contrib/admin/templates/admin/auth/user/change_password.html:22 +#: contrib/admin/templates/admin/change_list.html:54 +#: contrib/admin/templates/admin/auth/user/change_password.html:23 msgid "Please correct the error below." msgid_plural "Please correct the errors below." msgstr[0] "Por favor, corrija el siguiente error." msgstr[1] "Por favor, corrija los siguientes errores." -#: contrib/admin/templates/admin/change_list.html:16 +#: contrib/admin/templates/admin/change_list.html:46 #, python-format msgid "Add %(name)s" msgstr "Agregar %(name)s" -#: contrib/admin/templates/admin/change_list.html:26 +#: contrib/admin/templates/admin/change_list.html:65 msgid "Filter" msgstr "Filtrar" #: contrib/admin/templates/admin/delete_confirmation.html:10 -#: contrib/admin/templates/admin/submit_line.html:4 forms/formsets.py:246 +#: contrib/admin/templates/admin/submit_line.html:4 forms/formsets.py:275 msgid "Delete" msgstr "Eliminar" @@ -612,9 +648,34 @@ msgstr "" "\"? Se eliminarán los siguientes objetos relacionados:" #: contrib/admin/templates/admin/delete_confirmation.html:28 +#: contrib/admin/templates/admin/delete_selected_confirmation.html:33 msgid "Yes, I'm sure" msgstr "Sí, estoy seguro" +#: contrib/admin/templates/admin/delete_selected_confirmation.html:9 +msgid "Delete multiple objects" +msgstr "Eliminar múltiples objetos" + +#: contrib/admin/templates/admin/delete_selected_confirmation.html:15 +#, python-format +msgid "" +"Deleting the %(object_name)s would result in deleting related objects, but " +"your account doesn't have permission to delete the following types of " +"objects:" +msgstr "" +"El eliminar %(object_name)s provocaría la eliminación de objetos " +"relacionados, pero su cuenta no tiene permiso para eliminar los siguientes " +"tipos de objetos:" + +#: contrib/admin/templates/admin/delete_selected_confirmation.html:22 +#, python-format +msgid "" +"Are you sure you want to delete the selected %(object_name)s objects? All of " +"the following objects and it's related items will be deleted:" +msgstr "" +"¿Está seguro de que quiere eliminar los objetos %(object_name)s? Se " +"eliminarán todos los siguientes objetos relacionados:" + #: contrib/admin/templates/admin/filter.html:2 #, python-format msgid " By %(filter_title)s " @@ -645,6 +706,10 @@ msgstr "Mis acciones" msgid "None available" msgstr "Ninguna disponible" +#: contrib/admin/templates/admin/index.html:72 +msgid "Unknown content" +msgstr "COntenido desconocido" + #: contrib/admin/templates/admin/invalid_setup.html:7 msgid "" "Something's wrong with your database installation. Make sure the appropriate " @@ -677,7 +742,7 @@ msgid "Action" msgstr "Acción" #: contrib/admin/templates/admin/object_history.html:30 -#: utils/translation/trans_real.py:404 +#: utils/translation/trans_real.py:400 msgid "DATETIME_FORMAT" msgstr "j N Y P" @@ -694,7 +759,7 @@ msgid "Show all" msgstr "Mostrar todos/as" #: contrib/admin/templates/admin/search_form.html:8 -msgid "Go" +msgid "Search" msgstr "Buscar" #: contrib/admin/templates/admin/search_form.html:10 @@ -739,24 +804,24 @@ msgid "Username" msgstr "Nombre de usuario:" #: contrib/admin/templates/admin/auth/user/add_form.html:20 -#: contrib/admin/templates/admin/auth/user/change_password.html:33 -#: contrib/auth/forms.py:17 contrib/auth/forms.py:60 contrib/auth/forms.py:184 +#: contrib/admin/templates/admin/auth/user/change_password.html:34 +#: contrib/auth/forms.py:17 contrib/auth/forms.py:60 contrib/auth/forms.py:185 msgid "Password" msgstr "Contraseña:" #: contrib/admin/templates/admin/auth/user/add_form.html:26 -#: contrib/admin/templates/admin/auth/user/change_password.html:39 -#: contrib/auth/forms.py:185 +#: contrib/admin/templates/admin/auth/user/change_password.html:40 +#: contrib/auth/forms.py:186 msgid "Password (again)" msgstr "Contraseña (de nuevo)" #: contrib/admin/templates/admin/auth/user/add_form.html:27 -#: contrib/admin/templates/admin/auth/user/change_password.html:40 +#: contrib/admin/templates/admin/auth/user/change_password.html:41 msgid "Enter the same password as above, for verification." msgstr "" "Para verificación, introduzca la misma contraseña que introdujo arriba." -#: contrib/admin/templates/admin/auth/user/change_password.html:26 +#: contrib/admin/templates/admin/auth/user/change_password.html:27 #, python-format msgid "Enter a new password for the user %(username)s." msgstr "" @@ -925,166 +990,166 @@ msgstr "Dirección de correo electrónico:" msgid "Reset my password" msgstr "Recuperar mi contraseña" -#: contrib/admin/templatetags/admin_list.py:284 +#: contrib/admin/templatetags/admin_list.py:299 msgid "All dates" msgstr "Todas las fechas" -#: contrib/admin/views/main.py:69 +#: contrib/admin/views/main.py:70 #, python-format msgid "Select %s" msgstr "Seleccione %s" -#: contrib/admin/views/main.py:69 +#: contrib/admin/views/main.py:70 #, python-format msgid "Select %s to change" msgstr "Seleccione %s a modificar" -#: contrib/admin/views/template.py:36 contrib/sites/models.py:38 +#: contrib/admin/views/template.py:37 contrib/sites/models.py:38 msgid "site" msgstr "sitio" -#: contrib/admin/views/template.py:38 +#: contrib/admin/views/template.py:39 msgid "template" msgstr "plantilla" -#: contrib/admindocs/views.py:57 contrib/admindocs/views.py:59 -#: contrib/admindocs/views.py:61 +#: contrib/admindocs/views.py:58 contrib/admindocs/views.py:60 +#: contrib/admindocs/views.py:62 msgid "tag:" msgstr "etiqueta:" -#: contrib/admindocs/views.py:90 contrib/admindocs/views.py:92 -#: contrib/admindocs/views.py:94 +#: contrib/admindocs/views.py:91 contrib/admindocs/views.py:93 +#: contrib/admindocs/views.py:95 msgid "filter:" msgstr "filtrar:" -#: contrib/admindocs/views.py:154 contrib/admindocs/views.py:156 -#: contrib/admindocs/views.py:158 +#: contrib/admindocs/views.py:155 contrib/admindocs/views.py:157 +#: contrib/admindocs/views.py:159 msgid "view:" msgstr "ver:" -#: contrib/admindocs/views.py:186 +#: contrib/admindocs/views.py:187 #, python-format msgid "App %r not found" msgstr "Aplicación %r no encontrada" -#: contrib/admindocs/views.py:193 +#: contrib/admindocs/views.py:194 #, python-format msgid "Model %(model_name)r not found in app %(app_label)r" msgstr "Modelo %(model_name)r no encontrado en aplicación %(app_label)r" -#: contrib/admindocs/views.py:205 +#: contrib/admindocs/views.py:206 #, python-format msgid "the related `%(app_label)s.%(data_type)s` object" msgstr "el objeto `%(app_label)s.%(data_type)s` relacionado" -#: contrib/admindocs/views.py:205 contrib/admindocs/views.py:227 -#: contrib/admindocs/views.py:241 contrib/admindocs/views.py:246 +#: contrib/admindocs/views.py:206 contrib/admindocs/views.py:228 +#: contrib/admindocs/views.py:242 contrib/admindocs/views.py:247 msgid "model:" msgstr "modelo:" -#: contrib/admindocs/views.py:236 +#: contrib/admindocs/views.py:237 #, python-format msgid "related `%(app_label)s.%(object_name)s` objects" msgstr "objetos `%(app_label)s.%(object_name)s` relacionados" -#: contrib/admindocs/views.py:241 +#: contrib/admindocs/views.py:242 #, python-format msgid "all %s" msgstr "todos los %s" -#: contrib/admindocs/views.py:246 +#: contrib/admindocs/views.py:247 #, python-format msgid "number of %s" msgstr "número de %s" -#: contrib/admindocs/views.py:251 +#: contrib/admindocs/views.py:252 #, python-format msgid "Fields on %s objects" msgstr "Campos en objetos %s" -#: contrib/admindocs/views.py:314 contrib/admindocs/views.py:325 -#: contrib/admindocs/views.py:327 contrib/admindocs/views.py:333 -#: contrib/admindocs/views.py:334 contrib/admindocs/views.py:336 +#: contrib/admindocs/views.py:315 contrib/admindocs/views.py:326 +#: contrib/admindocs/views.py:328 contrib/admindocs/views.py:334 +#: contrib/admindocs/views.py:335 contrib/admindocs/views.py:337 msgid "Integer" msgstr "Entero" -#: contrib/admindocs/views.py:315 +#: contrib/admindocs/views.py:316 msgid "Boolean (Either True or False)" msgstr "Booleano (Verdadero o Falso)" -#: contrib/admindocs/views.py:316 contrib/admindocs/views.py:335 +#: contrib/admindocs/views.py:317 contrib/admindocs/views.py:336 #, python-format msgid "String (up to %(max_length)s)" msgstr "Cadena (máximo %(max_length)s)" -#: contrib/admindocs/views.py:317 +#: contrib/admindocs/views.py:318 msgid "Comma-separated integers" msgstr "Enteros separados por comas" -#: contrib/admindocs/views.py:318 +#: contrib/admindocs/views.py:319 msgid "Date (without time)" msgstr "Fecha (sin hora)" -#: contrib/admindocs/views.py:319 +#: contrib/admindocs/views.py:320 msgid "Date (with time)" msgstr "Fecha (con hora)" -#: contrib/admindocs/views.py:320 +#: contrib/admindocs/views.py:321 msgid "Decimal number" msgstr "Número decimal" -#: contrib/admindocs/views.py:321 +#: contrib/admindocs/views.py:322 msgid "E-mail address" msgstr "Dirección de correo electrónico" -#: contrib/admindocs/views.py:322 contrib/admindocs/views.py:323 -#: contrib/admindocs/views.py:326 +#: contrib/admindocs/views.py:323 contrib/admindocs/views.py:324 +#: contrib/admindocs/views.py:327 msgid "File path" msgstr "Ruta de archivo" -#: contrib/admindocs/views.py:324 +#: contrib/admindocs/views.py:325 msgid "Floating point number" msgstr "Número de punto flotante" -#: contrib/admindocs/views.py:328 contrib/comments/models.py:58 +#: contrib/admindocs/views.py:329 contrib/comments/models.py:60 msgid "IP address" msgstr "Dirección IP" -#: contrib/admindocs/views.py:330 +#: contrib/admindocs/views.py:331 msgid "Boolean (Either True, False or None)" msgstr "Booleano (Verdadero, Falso o Nulo)" -#: contrib/admindocs/views.py:331 +#: contrib/admindocs/views.py:332 msgid "Relation to parent model" msgstr "Relación con el modelo padre" -#: contrib/admindocs/views.py:332 +#: contrib/admindocs/views.py:333 msgid "Phone number" msgstr "Número de teléfono" -#: contrib/admindocs/views.py:337 +#: contrib/admindocs/views.py:338 msgid "Text" msgstr "Texto" -#: contrib/admindocs/views.py:338 +#: contrib/admindocs/views.py:339 msgid "Time" msgstr "Hora" -#: contrib/admindocs/views.py:339 contrib/comments/forms.py:21 +#: contrib/admindocs/views.py:340 contrib/comments/forms.py:95 #: contrib/comments/templates/comments/moderation_queue.html:37 #: contrib/flatpages/admin.py:8 contrib/flatpages/models.py:7 msgid "URL" msgstr "URL" -#: contrib/admindocs/views.py:340 +#: contrib/admindocs/views.py:341 msgid "U.S. state (two uppercase letters)" msgstr "Estado de los EE.UU. (dos letras mayúsculas)" -#: contrib/admindocs/views.py:341 +#: contrib/admindocs/views.py:342 msgid "XML text" msgstr "Texto XML" -#: contrib/admindocs/views.py:367 +#: contrib/admindocs/views.py:368 #, python-format msgid "%s does not appear to be a urlpattern object" msgstr "%s no parece ser un objeto urlpattern" @@ -1174,21 +1239,21 @@ msgstr "Fechas importantes" msgid "Groups" msgstr "Grupos" -#: contrib/auth/admin.py:64 +#: contrib/auth/admin.py:80 msgid "Add user" msgstr "Agregar usuario" -#: contrib/auth/admin.py:90 +#: contrib/auth/admin.py:106 msgid "Password changed successfully." msgstr "Cambio de contraseña exitoso" -#: contrib/auth/admin.py:96 +#: contrib/auth/admin.py:112 #, python-format msgid "Change password: %s" msgstr "Cambiar contraseña: %s" #: contrib/auth/forms.py:15 contrib/auth/forms.py:48 -#: contrib/auth/models.py:127 +#: contrib/auth/models.py:128 msgid "" "Required. 30 characters or fewer. Alphanumeric characters only (letters, " "digits and underscores)." @@ -1208,8 +1273,8 @@ msgstr "Confirmación de contraseña" msgid "A user with that username already exists." msgstr "Ya existe un usuario con ese nombre." -#: contrib/auth/forms.py:36 contrib/auth/forms.py:154 -#: contrib/auth/forms.py:196 +#: contrib/auth/forms.py:36 contrib/auth/forms.py:155 +#: contrib/auth/forms.py:197 msgid "The two password fields didn't match." msgstr "Los dos campos de contraseñas no coinciden entre si." @@ -1237,24 +1302,24 @@ msgstr "" "Esa dirección de e-mail no está asociada a ninguna cuenta de usuario. ¿Está " "seguro de que ya se ha registrado?" -#: contrib/auth/forms.py:134 +#: contrib/auth/forms.py:135 #, python-format msgid "Password reset on %s" msgstr "Reinicialización de contraseña en %s" -#: contrib/auth/forms.py:142 +#: contrib/auth/forms.py:143 msgid "New password" msgstr "Contraseña nueva" -#: contrib/auth/forms.py:143 +#: contrib/auth/forms.py:144 msgid "New password confirmation" msgstr "Confirmación de contraseña nueva" -#: contrib/auth/forms.py:168 +#: contrib/auth/forms.py:169 msgid "Old password" msgstr "Contraseña antigua" -#: contrib/auth/forms.py:176 +#: contrib/auth/forms.py:177 msgid "Your old password was entered incorrectly. Please enter it again." msgstr "" "La antigua contraseña introducida es incorrecta. Por favor introdúzcala " @@ -1280,31 +1345,31 @@ msgstr "permisos" msgid "group" msgstr "grupo" -#: contrib/auth/models.py:91 contrib/auth/models.py:137 +#: contrib/auth/models.py:91 contrib/auth/models.py:138 msgid "groups" msgstr "grupos" -#: contrib/auth/models.py:127 +#: contrib/auth/models.py:128 msgid "username" msgstr "nombre de usuario" -#: contrib/auth/models.py:128 +#: contrib/auth/models.py:129 msgid "first name" msgstr "nombre" -#: contrib/auth/models.py:129 +#: contrib/auth/models.py:130 msgid "last name" msgstr "apellido" -#: contrib/auth/models.py:130 +#: contrib/auth/models.py:131 msgid "e-mail address" msgstr "dirección de correo electrónico" -#: contrib/auth/models.py:131 +#: contrib/auth/models.py:132 msgid "password" msgstr "contraseña" -#: contrib/auth/models.py:131 +#: contrib/auth/models.py:132 msgid "" "Use '[algo]$[salt]$[hexdigest]' or use the change " "password form." @@ -1312,19 +1377,19 @@ msgstr "" "Use '[algo]$[salt]$[hexdigest]' o use el formulario de " "cambio de contraseña." -#: contrib/auth/models.py:132 +#: contrib/auth/models.py:133 msgid "staff status" msgstr "es staff" -#: contrib/auth/models.py:132 +#: contrib/auth/models.py:133 msgid "Designates whether the user can log into this admin site." msgstr "Indica si el usuario puede ingresar a este sitio de administración." -#: contrib/auth/models.py:133 +#: contrib/auth/models.py:134 msgid "active" msgstr "activo" -#: contrib/auth/models.py:133 +#: contrib/auth/models.py:134 msgid "" "Designates whether this user should be treated as active. Unselect this " "instead of deleting accounts." @@ -1332,11 +1397,11 @@ msgstr "" "Indica si el usuario debe ser tratado como un usuario activo. Desactive este " "campo en lugar de eliminar usuarios." -#: contrib/auth/models.py:134 +#: contrib/auth/models.py:135 msgid "superuser status" msgstr "es superusuario" -#: contrib/auth/models.py:134 +#: contrib/auth/models.py:135 msgid "" "Designates that this user has all permissions without explicitly assigning " "them." @@ -1344,15 +1409,15 @@ msgstr "" "Indica que este usuario posee todos los permisos sin que sea necesario " "asignarle los mismos en forma explícita." -#: contrib/auth/models.py:135 +#: contrib/auth/models.py:136 msgid "last login" msgstr "último ingreso" -#: contrib/auth/models.py:136 +#: contrib/auth/models.py:137 msgid "date joined" msgstr "fecha de creación" -#: contrib/auth/models.py:138 +#: contrib/auth/models.py:139 msgid "" "In addition to the permissions manually assigned, this user will also get " "all permissions granted to each group he/she is in." @@ -1360,27 +1425,28 @@ msgstr "" "Además de los permisos asignados manualmente, este usuario también poseerá " "todos los permisos de los grupos a los que pertenezca." -#: contrib/auth/models.py:139 +#: contrib/auth/models.py:140 msgid "user permissions" msgstr "permisos de usuario" -#: contrib/auth/models.py:143 +#: contrib/auth/models.py:144 contrib/comments/models.py:50 +#: contrib/comments/models.py:168 msgid "user" msgstr "usuario" -#: contrib/auth/models.py:144 +#: contrib/auth/models.py:145 msgid "users" msgstr "usuarios" -#: contrib/auth/models.py:300 +#: contrib/auth/models.py:301 msgid "message" msgstr "mensaje" -#: contrib/auth/views.py:50 +#: contrib/auth/views.py:56 msgid "Logged out" msgstr "Sesión cerrada" -#: contrib/auth/management/commands/createsuperuser.py:23 forms/fields.py:428 +#: contrib/auth/management/commands/createsuperuser.py:23 forms/fields.py:429 msgid "Enter a valid e-mail address." msgstr "Introduzca una dirección de correo electrónico válida" @@ -1392,71 +1458,86 @@ msgstr "Contenido" msgid "Metadata" msgstr "Metadatos" -#: contrib/comments/forms.py:19 +#: contrib/comments/feeds.py:13 +#, python-format +msgid "%(site_name)s comments" +msgstr "comentarios en %(site_name)s" + +#: contrib/comments/feeds.py:23 +#, python-format +msgid "Latest comments on %(site_name)s" +msgstr "Últimos comentarios en %(site_name)s." + +#: contrib/comments/forms.py:93 #: contrib/comments/templates/comments/moderation_queue.html:34 msgid "Name" msgstr "Nombre" -#: contrib/comments/forms.py:20 +#: contrib/comments/forms.py:94 msgid "Email address" msgstr "Dirección de correo electrónico" -#: contrib/comments/forms.py:22 +#: contrib/comments/forms.py:96 #: contrib/comments/templates/comments/moderation_queue.html:35 msgid "Comment" msgstr "Comentario" -#: contrib/comments/forms.py:25 -msgid "" -"If you enter anything in this field your comment will be treated as spam" -msgstr "Si introduce algo en este campo su comentario será tratado como spam" - -#: contrib/comments/forms.py:125 +#: contrib/comments/forms.py:173 #, python-format msgid "Watch your mouth! The word %s is not allowed here." msgid_plural "Watch your mouth! The words %s are not allowed here." msgstr[0] "¡Controla tu lenguaje! Aquí no admitimos la palabra %s." msgstr[1] "¡Controla tu lenguaje! Aquí no admitimos las palabras %s." -#: contrib/comments/models.py:23 +#: contrib/comments/forms.py:180 +msgid "" +"If you enter anything in this field your comment will be treated as spam" +msgstr "Si introduce algo en este campo su comentario será tratado como spam" + +#: contrib/comments/models.py:22 contrib/contenttypes/models.py:74 +msgid "content type" +msgstr "tipo de contenido" + +#: contrib/comments/models.py:24 msgid "object ID" msgstr "ID de objeto" -#: contrib/comments/models.py:50 +#: contrib/comments/models.py:52 msgid "user's name" msgstr "nombre de usuario" -#: contrib/comments/models.py:51 +#: contrib/comments/models.py:53 msgid "user's email address" msgstr "dirección de correo electrónico del usuario" -#: contrib/comments/models.py:52 +#: contrib/comments/models.py:54 msgid "user's URL" msgstr "URL del usuario" -#: contrib/comments/models.py:54 +#: contrib/comments/models.py:56 contrib/comments/models.py:76 +#: contrib/comments/models.py:169 msgid "comment" msgstr "comentario" -#: contrib/comments/models.py:57 +#: contrib/comments/models.py:59 msgid "date/time submitted" msgstr "fecha/hora de envío" -#: contrib/comments/models.py:59 +#: contrib/comments/models.py:61 msgid "is public" msgstr "es público" -#: contrib/comments/models.py:60 +#: contrib/comments/models.py:62 msgid "" "Uncheck this box to make the comment effectively disappear from the site." msgstr "" "deseleccione esta caja para lograr que el comentario desaparezca del sitio." -#: contrib/comments/models.py:62 +#: contrib/comments/models.py:64 msgid "is removed" msgstr "se ha eliminado" -#: contrib/comments/models.py:63 +#: contrib/comments/models.py:65 msgid "" "Check this box if the comment is inappropriate. A \"This comment has been " "removed\" message will be displayed instead." @@ -1464,7 +1545,11 @@ msgstr "" "Marque esta caja si el comentario es inapropiado. En su lugar se mostrará un " "mensaje \"Este comentario ha sido eliminado\"." -#: contrib/comments/models.py:115 +#: contrib/comments/models.py:77 +msgid "comments" +msgstr "comentarios" + +#: contrib/comments/models.py:119 msgid "" "This comment was posted by an authenticated user and thus the name is read-" "only." @@ -1472,7 +1557,7 @@ msgstr "" "Este comentario ha sido enviado por un usuario identificado, por lo tanto el " "nombre no puede modificarse.%(text)s" -#: contrib/comments/models.py:124 +#: contrib/comments/models.py:128 msgid "" "This comment was posted by an authenticated user and thus the email is read-" "only." @@ -1480,7 +1565,7 @@ msgstr "" "Este comentario ha sido enviado por un usuario identificado, por lo tanto la " "dirección de correo electrónico no puede modificarse.%(text)s" -#: contrib/comments/models.py:149 +#: contrib/comments/models.py:153 #, python-format msgid "" "Posted by %(user)s at %(date)s\n" @@ -1495,6 +1580,22 @@ msgstr "" "\n" "http://%(domain)s%(url)s" +#: contrib/comments/models.py:170 +msgid "flag" +msgstr "marca" + +#: contrib/comments/models.py:171 +msgid "date" +msgstr "fecha" + +#: contrib/comments/models.py:181 +msgid "comment flag" +msgstr "marca de comentario" + +#: contrib/comments/models.py:182 +msgid "comment flags" +msgstr "marcas de comentario" + #: contrib/comments/templates/comments/approve.html:4 msgid "Approve a comment" msgstr "Aprobar un comentario" @@ -1554,13 +1655,13 @@ msgstr "Marcar" msgid "Thanks for flagging" msgstr "¡Gracias por marcar!" -#: contrib/comments/templates/comments/form.html:16 -#: contrib/comments/templates/comments/preview.html:31 +#: contrib/comments/templates/comments/form.html:17 +#: contrib/comments/templates/comments/preview.html:32 msgid "Post" msgstr "Remitir" -#: contrib/comments/templates/comments/form.html:17 -#: contrib/comments/templates/comments/preview.html:32 +#: contrib/comments/templates/comments/form.html:18 +#: contrib/comments/templates/comments/preview.html:33 msgid "Preview" msgstr "Previsualización" @@ -1606,33 +1707,29 @@ msgid "Thank you for your comment" msgstr "Gracias por dejar su comentario" #: contrib/comments/templates/comments/preview.html:4 -#: contrib/comments/templates/comments/preview.html:12 +#: contrib/comments/templates/comments/preview.html:13 msgid "Preview your comment" msgstr "Ver una copia previa de su comentario" -#: contrib/comments/templates/comments/preview.html:10 +#: contrib/comments/templates/comments/preview.html:11 msgid "Please correct the error below" msgid_plural "Please correct the errors below" msgstr[0] "Por favor, corrija el siguiente error." msgstr[1] "Por favor, corrija los siguientes errores." -#: contrib/comments/templates/comments/preview.html:15 +#: contrib/comments/templates/comments/preview.html:16 msgid "Post your comment" msgstr "Enviar su comentario" -#: contrib/comments/templates/comments/preview.html:15 +#: contrib/comments/templates/comments/preview.html:16 msgid "or make changes" msgstr "o realice modificaciones" -#: contrib/contenttypes/models.py:67 +#: contrib/contenttypes/models.py:70 msgid "python model class name" msgstr "nombre de la clase python del modelo" -#: contrib/contenttypes/models.py:71 -msgid "content type" -msgstr "tipo de contenido" - -#: contrib/contenttypes/models.py:72 +#: contrib/contenttypes/models.py:75 msgid "content types" msgstr "tipos de contenido" @@ -1703,18 +1800,26 @@ msgstr "" "Lamentablemente su formulario ha caducado. Por favor continúe rellenando el " "formulario en esta página." -#: contrib/gis/forms/fields.py:14 +#: contrib/gis/forms/fields.py:17 msgid "No geometry value provided." msgstr "No se ha proporcionado un valor de geometría." -#: contrib/gis/forms/fields.py:15 +#: contrib/gis/forms/fields.py:18 msgid "Invalid geometry value." msgstr "Valor de geometría no válido." -#: contrib/gis/forms/fields.py:16 +#: contrib/gis/forms/fields.py:19 msgid "Invalid geometry type." msgstr "Tipo de geometría no válido." +#: contrib/gis/forms/fields.py:20 +msgid "" +"An error occurred when transforming the geometry to the SRID of the geometry " +"form field." +msgstr "" +"Ha ocurrido un error mientras se transformaba la geometría al SRID del campo " +"de formulario de la misma." + #: contrib/humanize/templatetags/humanize.py:19 msgid "th" msgstr "th" @@ -2037,6 +2142,83 @@ msgstr "Introduzca un RUT chileno válido. EL formato es XX.XXX.XXX-X." msgid "The Chilean RUT is not valid." msgstr "El RUT chileno no es válido." +#: contrib/localflavor/cz/cz_regions.py:8 +msgid "Prague" +msgstr "Praga" + +#: contrib/localflavor/cz/cz_regions.py:9 +msgid "Central Bohemian Region" +msgstr "región Bohemia Central" + +#: contrib/localflavor/cz/cz_regions.py:10 +msgid "South Bohemian Region" +msgstr "región Bohemian Meridional" + +#: contrib/localflavor/cz/cz_regions.py:11 +msgid "Pilsen Region" +msgstr "región Pilsen" + +#: contrib/localflavor/cz/cz_regions.py:12 +msgid "Carlsbad Region" +msgstr "región Karlovy Vary" + +#: contrib/localflavor/cz/cz_regions.py:13 +msgid "Usti Region" +msgstr "región Ústí nad Labem" + +#: contrib/localflavor/cz/cz_regions.py:14 +msgid "Liberec Region" +msgstr "región Liberec" + +#: contrib/localflavor/cz/cz_regions.py:15 +msgid "Hradec Region" +msgstr "región Hradec Králové" + +#: contrib/localflavor/cz/cz_regions.py:16 +msgid "Pardubice Region" +msgstr "región Pardubice" + +#: contrib/localflavor/cz/cz_regions.py:17 +msgid "Vysocina Region" +msgstr "región Vysočina" + +#: contrib/localflavor/cz/cz_regions.py:18 +msgid "South Moravian Region" +msgstr "región Moravia Meridional" + +#: contrib/localflavor/cz/cz_regions.py:19 +msgid "Olomouc Region" +msgstr "región Olomouc" + +#: contrib/localflavor/cz/cz_regions.py:20 +msgid "Zlin Region" +msgstr "región Zlín" + +#: contrib/localflavor/cz/cz_regions.py:21 +msgid "Moravian-Silesian Region" +msgstr "región Moravia-Silesia" + +#: contrib/localflavor/cz/forms.py:27 contrib/localflavor/sk/forms.py:30 +msgid "Enter a postal code in the format XXXXX or XXX XX." +msgstr "Introduzca un código postal en formato XXXXX o XXX XX." + +#: contrib/localflavor/cz/forms.py:47 +msgid "Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX." +msgstr "" +"Introduzca un número de nacimiento en formato XXXXXX/XXXX o XXXXXXXXXX." + +#: contrib/localflavor/cz/forms.py:48 +msgid "Invalid optional parameter Gender, valid values are 'f' and 'm'" +msgstr "Parámetro opcional Género inválido, valores válidos son 'f' y 'm'" + +#: contrib/localflavor/cz/forms.py:49 +msgid "Enter a valid birth number." +msgstr "Introduzca un número ide nacimiento válido." + +#: contrib/localflavor/cz/forms.py:106 +msgid "Enter a valid IC number." +msgstr "Introduzca un número IC válido." + #: contrib/localflavor/de/de_states.py:5 msgid "Baden-Wuerttemberg" msgstr "Baden-Wuerttemberg" @@ -2868,19 +3050,19 @@ msgstr "" msgid "Wrong checksum for the Tax Number (NIP)." msgstr "Código de verificación de Número Impostitivo (NIP) inválido." -#: contrib/localflavor/pl/forms.py:111 -msgid "National Business Register Number (REGON) consists of 7 or 9 digits." +#: contrib/localflavor/pl/forms.py:109 +msgid "National Business Register Number (REGON) consists of 9 or 14 digits." msgstr "" -"Los Números Nacionales de Registro de Negocios (REGON) constan de 7 o 9 " +"Los Números Nacionales de Registro de Negocios (REGON) constan de 9 o 14 " "dígitos." -#: contrib/localflavor/pl/forms.py:112 +#: contrib/localflavor/pl/forms.py:110 msgid "Wrong checksum for the National Business Register Number (REGON)." msgstr "" "Código de verificación de Número Nacional de Registro de negocios (REGON) " "inválido." -#: contrib/localflavor/pl/forms.py:155 +#: contrib/localflavor/pl/forms.py:148 msgid "Enter a postal code in the format XX-XXX." msgstr "Introduzca un código postal en formato XX-XXX." @@ -2968,10 +3150,6 @@ msgstr "Los números telefónicos deben respetar el formato XXXX-XXXXXX." msgid "Enter a valid postal code in the format XXXXXX" msgstr "Introduzca un código postal válido en formato XXXXXX" -#: contrib/localflavor/sk/forms.py:30 -msgid "Enter a postal code in the format XXXXX or XXX XX." -msgstr "Introduzca un código postal en formato XXXXX o XXX XX." - #: contrib/localflavor/sk/sk_districts.py:8 msgid "Banska Bystrica" msgstr "Banska Bystrica" @@ -3290,35 +3468,35 @@ msgstr "Zilina" #: contrib/localflavor/sk/sk_regions.py:8 msgid "Banska Bystrica region" -msgstr "region Banska Bystrica" +msgstr "región Banska Bystrica" #: contrib/localflavor/sk/sk_regions.py:9 msgid "Bratislava region" -msgstr "region Bratislava" +msgstr "región Bratislava" #: contrib/localflavor/sk/sk_regions.py:10 msgid "Kosice region" -msgstr "region Kosice" +msgstr "región Kosice" #: contrib/localflavor/sk/sk_regions.py:11 msgid "Nitra region" -msgstr "region Nitra" +msgstr "región Nitra" #: contrib/localflavor/sk/sk_regions.py:12 msgid "Presov region" -msgstr "region Presov" +msgstr "región Presov" #: contrib/localflavor/sk/sk_regions.py:13 msgid "Trencin region" -msgstr "region Trencin" +msgstr "región Trencin" #: contrib/localflavor/sk/sk_regions.py:14 msgid "Trnava region" -msgstr "region Trnava" +msgstr "región Trnava" #: contrib/localflavor/sk/sk_regions.py:15 msgid "Zilina region" -msgstr "region Zilina" +msgstr "región Zilina" #: contrib/localflavor/uk/forms.py:21 msgid "Enter a valid postcode." @@ -3720,57 +3898,61 @@ msgstr "nombre para visualizar" msgid "sites" msgstr "sitios" -#: db/models/fields/__init__.py:348 db/models/fields/__init__.py:683 +#: db/models/fields/__init__.py:356 db/models/fields/__init__.py:710 msgid "This value must be an integer." msgstr "Este valor debe ser un número entero." -#: db/models/fields/__init__.py:379 +#: db/models/fields/__init__.py:388 msgid "This value must be either True or False." msgstr "Este valor debe ser True o False." -#: db/models/fields/__init__.py:412 +#: db/models/fields/__init__.py:427 msgid "This field cannot be null." msgstr "Este campo no puede ser nulo." -#: db/models/fields/__init__.py:428 +#: db/models/fields/__init__.py:443 msgid "Enter only digits separated by commas." msgstr "Introduzca sólo dígitos separados por comas." -#: db/models/fields/__init__.py:459 +#: db/models/fields/__init__.py:474 msgid "Enter a valid date in YYYY-MM-DD format." msgstr "Introduzca una fecha válida en formato AAAA-MM-DD." -#: db/models/fields/__init__.py:468 +#: db/models/fields/__init__.py:483 #, python-format msgid "Invalid date: %s" msgstr "Fecha no válida: %s" -#: db/models/fields/__init__.py:532 db/models/fields/__init__.py:550 +#: db/models/fields/__init__.py:547 db/models/fields/__init__.py:565 msgid "Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." msgstr "" "Introduzca un valor de fecha/hora válido en formato AAAA-MM-DD HH:MM[:ss[." "uuuuuu]]." -#: db/models/fields/__init__.py:586 +#: db/models/fields/__init__.py:601 msgid "This value must be a decimal number." msgstr "Este valor debe ser un número decimal." -#: db/models/fields/__init__.py:719 +#: db/models/fields/__init__.py:686 +msgid "This value must be a float." +msgstr "Este valor debe ser un valor en representación de punto flotante." + +#: db/models/fields/__init__.py:746 msgid "This value must be either None, True or False." msgstr "Este valor debe ser None, True o False." -#: db/models/fields/__init__.py:817 db/models/fields/__init__.py:831 +#: db/models/fields/__init__.py:849 db/models/fields/__init__.py:863 msgid "Enter a valid time in HH:MM[:ss[.uuuuuu]] format." msgstr "Introduzca un valor de hora válido en formato HH:MM[:ss[.uuuuuu]]." -#: db/models/fields/related.py:761 +#: db/models/fields/related.py:792 msgid "" "Hold down \"Control\", or \"Command\" on a Mac, to select more than one." msgstr "" "Mantenga presionada \"Control\" (\"Command\" en una Mac) para seleccionar " "más de uno." -#: db/models/fields/related.py:838 +#: db/models/fields/related.py:870 #, python-format msgid "Please enter valid %(self)s IDs. The value %(value)r is invalid." msgid_plural "" @@ -3837,32 +4019,40 @@ msgstr "Asegúrese de que no existan mas de %s lugares decimales." msgid "Ensure that there are no more than %s digits before the decimal point." msgstr "Asegúrese de que no existan mas de %s dígitos antes del punto decimal." -#: forms/fields.py:287 forms/fields.py:849 +#: forms/fields.py:288 forms/fields.py:863 msgid "Enter a valid date." msgstr "Introduzca una fecha válida." -#: forms/fields.py:321 forms/fields.py:850 +#: forms/fields.py:322 forms/fields.py:864 msgid "Enter a valid time." msgstr "Introduzca un valor de hora válido." -#: forms/fields.py:360 +#: forms/fields.py:361 msgid "Enter a valid date/time." msgstr "Introduzca un valor de fecha/hora válido." -#: forms/fields.py:446 +#: forms/fields.py:447 msgid "No file was submitted. Check the encoding type on the form." msgstr "" "No se envió un archivo. Verifique el tipo de codificación en el formulario." -#: forms/fields.py:447 +#: forms/fields.py:448 msgid "No file was submitted." msgstr "No se envió ningún archivo." -#: forms/fields.py:448 +#: forms/fields.py:449 msgid "The submitted file is empty." msgstr "El archivo enviado está vacío." -#: forms/fields.py:477 +#: forms/fields.py:450 +#, python-format +msgid "" +"Ensure this filename has at most %(max)d characters (it has %(length)d)." +msgstr "" +"Asegúrese de que este nombre de archivo tenga como máximo %(max)d caracteres " +"(tiene %(length)d)." + +#: forms/fields.py:483 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." @@ -3870,107 +4060,141 @@ msgstr "" "Envíe una imagen válida. El archivo que ha enviado no era una imagen o se " "trataba de una imagen corrupta." -#: forms/fields.py:538 +#: forms/fields.py:544 msgid "Enter a valid URL." msgstr "Introduzca una URL válida." -#: forms/fields.py:539 +#: forms/fields.py:545 msgid "This URL appears to be a broken link." msgstr "La URL parece ser un enlace roto." -#: forms/fields.py:618 forms/fields.py:696 +#: forms/fields.py:625 forms/fields.py:703 #, python-format msgid "Select a valid choice. %(value)s is not one of the available choices." msgstr "" "Seleccione una opción válida. %(value)s no es una de las opciones " "disponibles." -#: forms/fields.py:697 forms/fields.py:758 forms/models.py:720 +#: forms/fields.py:704 forms/fields.py:765 forms/models.py:991 msgid "Enter a list of values." msgstr "Introduzca una lista de valores." -#: forms/fields.py:878 +#: forms/fields.py:892 msgid "Enter a valid IPv4 address." msgstr "Introduzca una dirección IPv4 válida" -#: forms/fields.py:888 +#: forms/fields.py:902 msgid "" "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens." msgstr "Introduzca un 'slug' válido consistente en letras, números o guiones." -#: forms/formsets.py:242 forms/formsets.py:244 +#: forms/formsets.py:271 forms/formsets.py:273 msgid "Order" msgstr "Ordenar" -#: forms/models.py:281 forms/models.py:290 +#: forms/models.py:367 +#, python-format +msgid "%(field_name)s must be unique for %(date_field)s %(lookup)s." +msgstr "" +"%(field_name)s debe ser único/a para un %(lookup)s %(date_field)s " +"determinado." + +#: forms/models.py:381 forms/models.py:389 #, python-format msgid "%(model_name)s with this %(field_label)s already exists." msgstr "Ya existe un/a %(model_name)s con este/a %(field_label)s." -#: forms/models.py:587 +#: forms/models.py:581 +#, fuzzy, python-format +msgid "Please correct the duplicate data for %(field)s." +msgstr "Por favor, corrija el siguiente error." + +#: forms/models.py:585 +#, python-format +msgid "Please correct the duplicate data for %(field)s, which must be unique." +msgstr "" + +#: forms/models.py:591 +#, python-format +msgid "" +"Please correct the duplicate data for %(field_name)s which must be unique " +"for the %(lookup)s in %(date_field)s." +msgstr "" + +#: forms/models.py:599 +#, fuzzy +msgid "Please correct the duplicate values below." +msgstr "Por favor, corrija el siguiente error." + +#: forms/models.py:855 msgid "The inline foreign key did not match the parent instance primary key." msgstr "" "La clave foránea del modelo inline no coincide con la de la instancia padre." -#: forms/models.py:650 +#: forms/models.py:918 msgid "Select a valid choice. That choice is not one of the available choices." msgstr "" "Seleccione una opción válida. Esa opción no es una de las opciones " "disponibles." -#: forms/models.py:721 +#: forms/models.py:992 #, python-format msgid "Select a valid choice. %s is not one of the available choices." msgstr "" "Seleccione una opción válida. %s no es una de las opciones disponibles." -#: template/defaultfilters.py:741 +#: forms/models.py:994 +#, python-format +msgid "\"%s\" is not a valid value for a primary key." +msgstr "\"%s\" no es un valor válido para una clave primaria." + +#: template/defaultfilters.py:767 msgid "yes,no,maybe" msgstr "si,no,talvez" -#: template/defaultfilters.py:772 +#: template/defaultfilters.py:798 #, python-format msgid "%(size)d byte" msgid_plural "%(size)d bytes" msgstr[0] "%(size)d byte" msgstr[1] "%(size)d bytes" -#: template/defaultfilters.py:774 +#: template/defaultfilters.py:800 #, python-format msgid "%.1f KB" msgstr "%.1f KB" -#: template/defaultfilters.py:776 +#: template/defaultfilters.py:802 #, python-format msgid "%.1f MB" msgstr "%.1f MB" -#: template/defaultfilters.py:777 +#: template/defaultfilters.py:803 #, python-format msgid "%.1f GB" msgstr "%.1f GB" -#: utils/dateformat.py:41 +#: utils/dateformat.py:42 msgid "p.m." msgstr "p.m." -#: utils/dateformat.py:42 +#: utils/dateformat.py:43 msgid "a.m." msgstr "a.m." -#: utils/dateformat.py:47 +#: utils/dateformat.py:48 msgid "PM" msgstr "PM" -#: utils/dateformat.py:48 +#: utils/dateformat.py:49 msgid "AM" msgstr "AM" -#: utils/dateformat.py:97 +#: utils/dateformat.py:98 msgid "midnight" msgstr "medianoche" -#: utils/dateformat.py:99 +#: utils/dateformat.py:100 msgid "noon" msgstr "mediodía" @@ -4194,33 +4418,33 @@ msgid_plural "minutes" msgstr[0] "minuto" msgstr[1] "minutos" -#: utils/timesince.py:43 +#: utils/timesince.py:45 msgid "minutes" msgstr "minutos" -#: utils/timesince.py:48 +#: utils/timesince.py:50 #, python-format msgid "%(number)d %(type)s" msgstr "%(number)d %(type)s" -#: utils/timesince.py:54 +#: utils/timesince.py:56 #, python-format msgid ", %(number)d %(type)s" msgstr ", %(number)d %(type)s" -#: utils/translation/trans_real.py:403 +#: utils/translation/trans_real.py:399 msgid "DATE_FORMAT" msgstr "j N Y" -#: utils/translation/trans_real.py:405 +#: utils/translation/trans_real.py:401 msgid "TIME_FORMAT" msgstr "P" -#: utils/translation/trans_real.py:421 +#: utils/translation/trans_real.py:417 msgid "YEAR_MONTH_FORMAT" msgstr "F Y" -#: utils/translation/trans_real.py:422 +#: utils/translation/trans_real.py:418 msgid "MONTH_DAY_FORMAT" msgstr "j \\de F" From c78554b2164b9b09fa30f93371fa6d89cf6b5e89 Mon Sep 17 00:00:00 2001 From: Gary Wilson Jr Date: Fri, 29 May 2009 04:06:09 +0000 Subject: [PATCH 03/66] Added test for pickling of a model with an `ImageField`, refs #11103. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10860 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- .../regressiontests/model_fields/imagefield.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/regressiontests/model_fields/imagefield.py b/tests/regressiontests/model_fields/imagefield.py index 09bda6bb2d..dd79e7aefa 100644 --- a/tests/regressiontests/model_fields/imagefield.py +++ b/tests/regressiontests/model_fields/imagefield.py @@ -150,6 +150,23 @@ if Image: _ = p.mugshot.size self.assertEqual(p.mugshot.closed, True) + def test_pickle(self): + """ + Tests that ImageField can be pickled, unpickled, and that the + image of the unpickled version is the same as the original. + """ + import pickle + + p = Person(name="Joe") + p.mugshot.save("mug", self.file1) + dump = pickle.dumps(p) + + p2 = Person(name="Bob") + p2.mugshot = self.file1 + + loaded_p = pickle.loads(dump) + self.assertEqual(p.mugshot, loaded_p.mugshot) + class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase): """ From bd58a3972b288aa335b87932ed3db72840215f6d Mon Sep 17 00:00:00 2001 From: Gary Wilson Jr Date: Fri, 29 May 2009 04:35:10 +0000 Subject: [PATCH 04/66] Fixed #11216 and #11218 -- Corrected a few typos, thanks buriy. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10861 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/utils/ogrinspect.py | 56 +++++++++++++------------- django/db/models/sql/query.py | 8 ++-- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/django/contrib/gis/utils/ogrinspect.py b/django/contrib/gis/utils/ogrinspect.py index c0c3c40a69..145bd221bb 100644 --- a/django/contrib/gis/utils/ogrinspect.py +++ b/django/contrib/gis/utils/ogrinspect.py @@ -12,12 +12,12 @@ from django.contrib.gis.gdal.field import OFTDate, OFTDateTime, OFTInteger, OFTR def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False): """ - Given a DataSource, generates a dictionary that may be used + Given a DataSource, generates a dictionary that may be used for invoking the LayerMapping utility. Keyword Arguments: `geom_name` => The name of the geometry field to use for the model. - + `layer_key` => The key for specifying which layer in the DataSource to use; defaults to 0 (the first layer). May be an integer index or a string identifier for the layer. @@ -31,7 +31,7 @@ def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False): pass else: raise TypeError('Data source parameter must be a string or a DataSource object.') - + # Creating the dictionary. _mapping = {} @@ -52,32 +52,32 @@ def ogrinspect(*args, **kwargs): model name this function will generate a GeoDjango model. Usage: - + >>> from django.contrib.gis.utils import ogrinspect >>> ogrinspect('/path/to/shapefile.shp','NewModel') - + ...will print model definition to stout - + or put this in a python script and use to redirect the output to a new model like: - + $ python generate_model.py > myapp/models.py - - # generate_model.py + + # generate_model.py from django.contrib.gis.utils import ogrinspect shp_file = 'data/mapping_hacks/world_borders.shp' model_name = 'WorldBorders' print ogrinspect(shp_file, model_name, multi_geom=True, srid=4326, geom_name='shapes', blank=True) - + Required Arguments `datasource` => string or DataSource object to file pointer - + `model name` => string of name of new model class to create - + Optional Keyword Arguments - `geom_name` => For specifying the model name for the Geometry Field. + `geom_name` => For specifying the model name for the Geometry Field. Otherwise will default to `geom` `layer_key` => The key for specifying which layer in the DataSource to use; @@ -86,24 +86,24 @@ def ogrinspect(*args, **kwargs): `srid` => The SRID to use for the Geometry Field. If it can be determined, the SRID of the datasource is used. - + `multi_geom` => Boolean (default: False) - specify as multigeometry. - + `name_field` => String - specifies a field name to return for the `__unicode__` function (which will be generated if specified). - - `imports` => Boolean (default: True) - set to False to omit the - `from django.contrib.gis.db import models` code from the + + `imports` => Boolean (default: True) - set to False to omit the + `from django.contrib.gis.db import models` code from the autogenerated models thus avoiding duplicated imports when building more than one model by batching ogrinspect() - + `decimal` => Boolean or sequence (default: False). When set to True all generated model fields corresponding to the `OFTReal` type will be `DecimalField` instead of `FloatField`. A sequence of specific field names to generate as `DecimalField` may also be used. `blank` => Boolean or sequence (default: False). When set to True all - generated model fields will have `blank=True`. If the user wants to + generated model fields will have `blank=True`. If the user wants to give specific fields to have blank, then a list/tuple of OGR field names may be used. @@ -111,13 +111,13 @@ def ogrinspect(*args, **kwargs): model fields will have `null=True`. If the user wants to specify give specific fields to have null, then a list/tuple of OGR field names may be used. - + Note: This routine calls the _ogrinspect() helper to do the heavy lifting. """ return '\n'.join(s for s in _ogrinspect(*args, **kwargs)) def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None, - multi_geom=False, name_field=None, imports=True, + multi_geom=False, name_field=None, imports=True, decimal=False, blank=False, null=False): """ Helper routine for `ogrinspect` that generates GeoDjango models corresponding @@ -140,7 +140,7 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non # keyword arguments. def process_kwarg(kwarg): if isinstance(kwarg, (list, tuple)): - return [s.lower() for s in kwarg] + return [s.lower() for s in kwarg] elif kwarg: return [s.lower() for s in ogr_fields] else: @@ -164,18 +164,18 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non yield '' yield 'class %s(models.Model):' % model_name - + for field_name, width, precision, field_type in izip(ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types): # The model field name. mfield = field_name.lower() if mfield[-1:] == '_': mfield += 'field' - + # Getting the keyword args string. kwargs_str = get_kwargs_str(field_name) if field_type is OFTReal: # By default OFTReals are mapped to `FloatField`, however, they - # may also be mapped to `DecimalField` if specified in the + # may also be mapped to `DecimalField` if specified in the # `decimal` keyword. if field_name.lower() in decimal_fields: yield ' %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)' % (mfield, width, precision, kwargs_str) @@ -192,8 +192,8 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non elif field_type is OFTDate: yield ' %s = models.TimeField(%s)' % (mfield, kwargs_str[2:]) else: - raise TypeError('Unknown field type %s in %s' % (fld_type, mfield)) - + raise TypeError('Unknown field type %s in %s' % (field_type, mfield)) + # TODO: Autodetection of multigeometry types (see #7218). gtype = layer.geom_type if multi_geom and gtype.num in (1, 2, 3): diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 394e30ba97..d290d60e63 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -689,7 +689,7 @@ class BaseQuery(object): If 'with_aliases' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in - some cases to avoid ambiguitity with nested queries. + some cases to avoid ambiguity with nested queries. """ qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name @@ -1303,7 +1303,7 @@ class BaseQuery(object): opts = self.model._meta root_alias = self.tables[0] seen = {None: root_alias} - + # Skip all proxy to the root proxied model proxied_model = get_proxied_model(opts) @@ -1732,7 +1732,7 @@ class BaseQuery(object): raise MultiJoin(pos + 1) if model: # The field lives on a base class of the current model. - # Skip the chain of proxy to the concrete proxied model + # Skip the chain of proxy to the concrete proxied model proxied_model = get_proxied_model(opts) for int_model in opts.get_base_chain(model): @@ -2362,7 +2362,7 @@ class BaseQuery(object): return cursor if result_type == SINGLE: if self.ordering_aliases: - return cursor.fetchone()[:-len(results.ordering_aliases)] + return cursor.fetchone()[:-len(self.ordering_aliases)] return cursor.fetchone() # The MULTI case. From 419747d1c8363f06a143429ffe58e67f2f217b5e Mon Sep 17 00:00:00 2001 From: Gary Wilson Jr Date: Fri, 29 May 2009 05:23:50 +0000 Subject: [PATCH 05/66] Fixed a few Python 2.3 incompatibilities that were causing test failures. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10863 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/forms/models.py | 2 +- tests/regressiontests/admin_scripts/tests.py | 2 +- tests/regressiontests/file_storage/tests.py | 12 ++++++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/django/forms/models.py b/django/forms/models.py index a0b217860d..8e9c0de0e7 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -584,7 +584,7 @@ class BaseModelFormSet(BaseFormSet): else: return ugettext("Please correct the duplicate data for %(field)s, " "which must be unique.") % { - "field": get_text_list(unique_check, _("and")), + "field": get_text_list(unique_check, unicode(_("and"))), } def get_date_error_message(self, date_check): diff --git a/tests/regressiontests/admin_scripts/tests.py b/tests/regressiontests/admin_scripts/tests.py index 0e28a9749f..e67126e9a7 100644 --- a/tests/regressiontests/admin_scripts/tests.py +++ b/tests/regressiontests/admin_scripts/tests.py @@ -536,7 +536,7 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase): args = ['startapp','settings_test'] out, err = self.run_django_admin(args,'settings') self.assertNoOutput(err) - self.assertTrue(os.path.exists(os.path.join(test_dir, 'settings_test'))) + self.assert_(os.path.exists(os.path.join(test_dir, 'settings_test'))) shutil.rmtree(os.path.join(test_dir, 'settings_test')) def test_builtin_command(self): diff --git a/tests/regressiontests/file_storage/tests.py b/tests/regressiontests/file_storage/tests.py index 6e2b7be8e7..c228764e06 100644 --- a/tests/regressiontests/file_storage/tests.py +++ b/tests/regressiontests/file_storage/tests.py @@ -161,9 +161,9 @@ class FileStoragePathParsing(TestCase): self.storage.save('dotted.path/test', ContentFile("1")) self.storage.save('dotted.path/test', ContentFile("2")) - self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) - self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) - self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_'))) + self.failIf(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) + self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) + self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_'))) def test_first_character_dot(self): """ @@ -173,13 +173,13 @@ class FileStoragePathParsing(TestCase): self.storage.save('dotted.path/.test', ContentFile("1")) self.storage.save('dotted.path/.test', ContentFile("2")) - self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test'))) + self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test'))) # Before 2.6, a leading dot was treated as an extension, and so # underscore gets added to beginning instead of end. if sys.version_info < (2, 6): - self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_.test'))) + self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_.test'))) else: - self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_'))) + self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_'))) if Image is not None: class DimensionClosingBug(TestCase): From 1ed5d8fc39aa634cacb740c916d1cef682063dbb Mon Sep 17 00:00:00 2001 From: Justin Bronn Date: Sat, 30 May 2009 16:10:23 +0000 Subject: [PATCH 06/66] Fixed #11200 -- Now use a `set` data structure for `GoogleMap` icons so that they aren't repeated in rendered JavaScript. Thanks to ludifan for ticket and initial patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10865 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/maps/google/gmap.py | 6 +++--- django/contrib/gis/maps/google/overlays.py | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/django/contrib/gis/maps/google/gmap.py b/django/contrib/gis/maps/google/gmap.py index dd4f67bc52..de8f75c5a0 100644 --- a/django/contrib/gis/maps/google/gmap.py +++ b/django/contrib/gis/maps/google/gmap.py @@ -143,7 +143,7 @@ class GoogleMap(object): @property def icons(self): "Returns a sequence of GIcon objects in this map." - return [marker.icon for marker in self.markers if marker.icon] + return set([marker.icon for marker in self.markers if marker.icon]) class GoogleMapSet(GoogleMap): @@ -221,6 +221,6 @@ class GoogleMapSet(GoogleMap): @property def icons(self): "Returns a sequence of all icons in each map of the set." - icons = [] - for map in self.maps: icons.extend(map.icons) + icons = set() + for map in self.maps: icons |= map.icons return icons diff --git a/django/contrib/gis/maps/google/overlays.py b/django/contrib/gis/maps/google/overlays.py index 4f1247d0a4..c2ebb3c992 100644 --- a/django/contrib/gis/maps/google/overlays.py +++ b/django/contrib/gis/maps/google/overlays.py @@ -231,6 +231,14 @@ class GIcon(object): self.iconanchor = iconanchor self.infowindowanchor = infowindowanchor + def __cmp__(self, other): + return cmp(self.varname, other.varname) + + def __hash__(self): + # XOR with hash of GIcon type so that hash('varname') won't + # equal hash(GIcon('varname')). + return hash(self.__class__) ^ hash(self.varname) + class GMarker(GOverlayBase): """ A Python wrapper for the Google GMarker object. For more information From be907bcdcbea7d95b5adefdcc9fd6c4d8cbfafe0 Mon Sep 17 00:00:00 2001 From: Justin Bronn Date: Wed, 3 Jun 2009 04:49:16 +0000 Subject: [PATCH 07/66] Fixed #11087 -- Fixed the `Count` annotation when used with `GeoManager`. Thanks to dgouldin for ticket and initial patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10912 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/db/models/sql/where.py | 4 +-- django/contrib/gis/tests/relatedapp/models.py | 10 ++++++ django/contrib/gis/tests/relatedapp/tests.py | 34 ++++++++++++++++--- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/django/contrib/gis/db/models/sql/where.py b/django/contrib/gis/db/models/sql/where.py index 838889fbad..105cbfbec5 100644 --- a/django/contrib/gis/db/models/sql/where.py +++ b/django/contrib/gis/db/models/sql/where.py @@ -35,7 +35,7 @@ class GeoWhereNode(WhereNode): return super(WhereNode, self).add(data, connector) obj, lookup_type, value = data - alias, col, field = obj.alias, obj.col, obj.field + col, field = obj.col, obj.field if not hasattr(field, "geom_type"): # Not a geographic field, so call `WhereNode.add`. @@ -76,7 +76,7 @@ class GeoWhereNode(WhereNode): # the `get_geo_where_clause` to construct the appropriate # spatial SQL when `make_atom` is called. annotation = GeoAnnotation(field, value, where) - return super(WhereNode, self).add(((alias, col, field.db_type()), lookup_type, annotation, params), connector) + return super(WhereNode, self).add(((obj.alias, col, field.db_type()), lookup_type, annotation, params), connector) def make_atom(self, child, qn): obj, lookup_type, value_annot, params = child diff --git a/django/contrib/gis/tests/relatedapp/models.py b/django/contrib/gis/tests/relatedapp/models.py index d7dd6bbfd2..1125d7fb85 100644 --- a/django/contrib/gis/tests/relatedapp/models.py +++ b/django/contrib/gis/tests/relatedapp/models.py @@ -32,3 +32,13 @@ class Parcel(models.Model): border2 = models.PolygonField(srid=2276) objects = models.GeoManager() def __unicode__(self): return self.name + +# These use the GeoManager but do not have any geographic fields. +class Author(models.Model): + name = models.CharField(max_length=100) + objects = models.GeoManager() + +class Book(models.Model): + title = models.CharField(max_length=100) + author = models.ForeignKey(Author, related_name='books') + objects = models.GeoManager() diff --git a/django/contrib/gis/tests/relatedapp/tests.py b/django/contrib/gis/tests/relatedapp/tests.py index 77f6c73bb6..8c4f83b15a 100644 --- a/django/contrib/gis/tests/relatedapp/tests.py +++ b/django/contrib/gis/tests/relatedapp/tests.py @@ -1,10 +1,10 @@ import os, unittest from django.contrib.gis.geos import * from django.contrib.gis.db.backend import SpatialBackend -from django.contrib.gis.db.models import F, Extent, Union +from django.contrib.gis.db.models import Count, Extent, F, Union from django.contrib.gis.tests.utils import no_mysql, no_oracle, no_spatialite from django.conf import settings -from models import City, Location, DirectoryEntry, Parcel +from models import City, Location, DirectoryEntry, Parcel, Book, Author cities = (('Aurora', 'TX', -97.516111, 33.058333), ('Roswell', 'NM', -104.528056, 33.387222), @@ -196,8 +196,8 @@ class RelatedGeoModelTest(unittest.TestCase): # ID values do not match their City ID values. loc1 = Location.objects.create(point='POINT (-95.363151 29.763374)') loc2 = Location.objects.create(point='POINT (-96.801611 32.782057)') - dallas = City.objects.create(name='Dallas', location=loc2) - houston = City.objects.create(name='Houston', location=loc1) + dallas = City.objects.create(name='Dallas', state='TX', location=loc2) + houston = City.objects.create(name='Houston', state='TX', location=loc1) # The expected ID values -- notice the last two location IDs # are out of order. We want to make sure that the related @@ -231,6 +231,32 @@ class RelatedGeoModelTest(unittest.TestCase): q = pickle.loads(q_str) self.assertEqual(GeoQuery, q.__class__) + def test12_count(self): + "Testing `Count` aggregate use with the `GeoManager`. See #11087." + # Creating a new City, 'Fort Worth', that uses the same location + # as Dallas. + dallas = City.objects.get(name='Dallas') + ftworth = City.objects.create(name='Fort Worth', state='TX', location=dallas.location) + + # Count annotation should be 2 for the Dallas location now. + loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id) + self.assertEqual(2, loc.num_cities) + + # Creating some data for the Book/Author non-geo models that + # use GeoManager. See #11087. + tp = Author.objects.create(name='Trevor Paglen') + Book.objects.create(title='Torture Taxi', author=tp) + Book.objects.create(title='I Could Tell You But Then You Would Have to be Destroyed by Me', author=tp) + Book.objects.create(title='Blank Spots on the Map', author=tp) + wp = Author.objects.create(name='William Patry') + Book.objects.create(title='Patry on Copyright', author=wp) + + # Should only be one author (Trevor Paglen) returned by this query, and + # the annotation should have 3 for the number of books. + qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1) + self.assertEqual(1, len(qs)) + self.assertEqual(3, qs[0].num_books) + # TODO: Related tests for KML, GML, and distance lookups. def suite(): From 2416e5fefe0e853cbfee17ae4dcb62b7055ed2d8 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 3 Jun 2009 13:23:19 +0000 Subject: [PATCH 08/66] Fixed #9479 -- Corrected an edge case in bulk queryset deletion that could cause an infinite loop when using MySQL InnoDB. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10913 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/query.py | 3 +- django/db/models/query_utils.py | 15 ++++- .../delete_regress/__init__.py | 1 + .../regressiontests/delete_regress/models.py | 61 +++++++++++++++++++ 4 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 tests/regressiontests/delete_regress/__init__.py create mode 100644 tests/regressiontests/delete_regress/models.py diff --git a/django/db/models/query.py b/django/db/models/query.py index 6a8d7d5e64..0d35b0ba16 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -355,10 +355,11 @@ class QuerySet(object): # Delete objects in chunks to prevent the list of related objects from # becoming too long. + seen_objs = None while 1: # Collect all the objects to be deleted in this chunk, and all the # objects that are related to the objects that are to be deleted. - seen_objs = CollectedObjects() + seen_objs = CollectedObjects(seen_objs) for object in del_query[:CHUNK_SIZE]: object._collect_sub_objects(seen_objs) diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py index 7a5ad919a1..6a6b69013f 100644 --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -32,11 +32,21 @@ class CollectedObjects(object): This is used for the database object deletion routines so that we can calculate the 'leaf' objects which should be deleted first. + + previously_seen is an optional argument. It must be a CollectedObjects + instance itself; any previously_seen collected object will be blocked from + being added to this instance. """ - def __init__(self): + def __init__(self, previously_seen=None): self.data = {} self.children = {} + if previously_seen: + self.blocked = previously_seen.blocked + for cls, seen in previously_seen.data.items(): + self.blocked.setdefault(cls, SortedDict()).update(seen) + else: + self.blocked = {} def add(self, model, pk, obj, parent_model, nullable=False): """ @@ -53,6 +63,9 @@ class CollectedObjects(object): Returns True if the item already existed in the structure and False otherwise. """ + if pk in self.blocked.get(model, {}): + return True + d = self.data.setdefault(model, SortedDict()) retval = pk in d d[pk] = obj diff --git a/tests/regressiontests/delete_regress/__init__.py b/tests/regressiontests/delete_regress/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/tests/regressiontests/delete_regress/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/regressiontests/delete_regress/models.py b/tests/regressiontests/delete_regress/models.py new file mode 100644 index 0000000000..93cadc58fa --- /dev/null +++ b/tests/regressiontests/delete_regress/models.py @@ -0,0 +1,61 @@ +from django.conf import settings +from django.db import models, backend, connection, transaction +from django.db.models import sql, query +from django.test import TransactionTestCase + +class Book(models.Model): + pagecount = models.IntegerField() + +# Can't run this test under SQLite, because you can't +# get two connections to an in-memory database. +if settings.DATABASE_ENGINE != 'sqlite3': + class DeleteLockingTest(TransactionTestCase): + def setUp(self): + # Create a second connection to the database + self.conn2 = backend.DatabaseWrapper({ + 'DATABASE_HOST': settings.DATABASE_HOST, + 'DATABASE_NAME': settings.DATABASE_NAME, + 'DATABASE_OPTIONS': settings.DATABASE_OPTIONS, + 'DATABASE_PASSWORD': settings.DATABASE_PASSWORD, + 'DATABASE_PORT': settings.DATABASE_PORT, + 'DATABASE_USER': settings.DATABASE_USER, + 'TIME_ZONE': settings.TIME_ZONE, + }) + + # Put both DB connections into managed transaction mode + transaction.enter_transaction_management() + transaction.managed(True) + self.conn2._enter_transaction_management(True) + + def tearDown(self): + # Close down the second connection. + transaction.leave_transaction_management() + self.conn2.close() + + def test_concurrent_delete(self): + "Deletes on concurrent transactions don't collide and lock the database. Regression for #9479" + + # Create some dummy data + b1 = Book(id=1, pagecount=100) + b2 = Book(id=2, pagecount=200) + b3 = Book(id=3, pagecount=300) + b1.save() + b2.save() + b3.save() + + transaction.commit() + + self.assertEquals(3, Book.objects.count()) + + # Delete something using connection 2. + cursor2 = self.conn2.cursor() + cursor2.execute('DELETE from delete_regress_book WHERE id=1') + self.conn2._commit(); + + # Now perform a queryset delete that covers the object + # deleted in connection 2. This causes an infinite loop + # under MySQL InnoDB unless we keep track of already + # deleted objects. + Book.objects.filter(pagecount__lt=250).delete() + transaction.commit() + self.assertEquals(1, Book.objects.count()) From 5b40ee32e6634f686c821ffa0dd5357c8dd85302 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 3 Jun 2009 13:32:26 +0000 Subject: [PATCH 09/66] Added svn:ignore property to a recently added directory git-svn-id: http://code.djangoproject.com/svn/django/trunk@10914 bcc190cf-cafb-0310-a4f2-bffc1f526a37 From 512ee0f52889eb7f624f309cdc61fab57ab73a7b Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Sat, 6 Jun 2009 06:14:05 +0000 Subject: [PATCH 10/66] Fixed #10572 -- Corrected the operation of the defer() and only() clauses when used on inherited models. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10926 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/query.py | 20 ++++++- django/db/models/sql/query.py | 10 +++- tests/modeltests/defer/models.py | 92 +++++++++++++++++++++++++++++++- 3 files changed, 118 insertions(+), 4 deletions(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index 0d35b0ba16..0f34fb8a5a 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -190,7 +190,25 @@ class QuerySet(object): index_start = len(extra_select) aggregate_start = index_start + len(self.model._meta.fields) - load_fields = only_load.get(self.model) + load_fields = [] + # If only/defer clauses have been specified, + # build the list of fields that are to be loaded. + if only_load: + for field, model in self.model._meta.get_fields_with_model(): + if model is None: + model = self.model + if field == self.model._meta.pk: + # Record the index of the primary key when it is found + pk_idx = len(load_fields) + try: + if field.name in only_load[model]: + # Add a field that has been explicitly included + load_fields.append(field.name) + except KeyError: + # Model wasn't explicitly listed in the only_load table + # Therefore, we need to load all fields from this model + load_fields.append(field.name) + skip = None if load_fields and not fill_cache: # Some fields have been deferred, so we have to initialise diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index d290d60e63..15b9fd6366 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -635,10 +635,10 @@ class BaseQuery(object): # models. workset = {} for model, values in seen.iteritems(): - for field, f_model in model._meta.get_fields_with_model(): + for field in model._meta.local_fields: if field in values: continue - add_to_dict(workset, f_model or model, field) + add_to_dict(workset, model, field) for model, values in must_include.iteritems(): # If we haven't included a model in workset, we don't add the # corresponding must_include fields for that model, since an @@ -657,6 +657,12 @@ class BaseQuery(object): # included any fields, we have to make sure it's mentioned # so that only the "must include" fields are pulled in. seen[model] = values + # Now ensure that every model in the inheritance chain is mentioned + # in the parent list. Again, it must be mentioned to ensure that + # only "must include" fields are pulled in. + for model in orig_opts.get_parent_list(): + if model not in seen: + seen[model] = set() for model, values in seen.iteritems(): callback(target, model, values) diff --git a/tests/modeltests/defer/models.py b/tests/modeltests/defer/models.py index ce65065d40..96eb427811 100644 --- a/tests/modeltests/defer/models.py +++ b/tests/modeltests/defer/models.py @@ -17,6 +17,12 @@ class Primary(models.Model): def __unicode__(self): return self.name +class Child(Primary): + pass + +class BigChild(Primary): + other = models.CharField(max_length=50) + def count_delayed_fields(obj, debug=False): """ Returns the number of delayed attributes on the given model instance. @@ -33,7 +39,7 @@ def count_delayed_fields(obj, debug=False): __test__ = {"API_TEST": """ To all outward appearances, instances with deferred fields look the same as -normal instances when we examine attribut values. Therefore we test for the +normal instances when we examine attribute values. Therefore we test for the number of deferred fields on returned instances (by poking at the internals), as a way to observe what is going on. @@ -98,5 +104,89 @@ Using defer() and only() with get() is also valid. >>> Primary.objects.all() [] +# Regression for #10572 - A subclass with no extra fields can defer fields from the base class +>>> _ = Child.objects.create(name="c1", value="foo", related=s1) + +# You can defer a field on a baseclass when the subclass has no fields +>>> obj = Child.objects.defer("value").get(name="c1") +>>> count_delayed_fields(obj) +1 +>>> obj.name +u"c1" +>>> obj.value +u"foo" +>>> obj.name = "c2" +>>> obj.save() + +# You can retrive a single column on a base class with no fields +>>> obj = Child.objects.only("name").get(name="c2") +>>> count_delayed_fields(obj) +3 +>>> obj.name +u"c2" +>>> obj.value +u"foo" +>>> obj.name = "cc" +>>> obj.save() + +>>> _ = BigChild.objects.create(name="b1", value="foo", related=s1, other="bar") + +# You can defer a field on a baseclass +>>> obj = BigChild.objects.defer("value").get(name="b1") +>>> count_delayed_fields(obj) +1 +>>> obj.name +u"b1" +>>> obj.value +u"foo" +>>> obj.other +u"bar" +>>> obj.name = "b2" +>>> obj.save() + +# You can defer a field on a subclass +>>> obj = BigChild.objects.defer("other").get(name="b2") +>>> count_delayed_fields(obj) +1 +>>> obj.name +u"b2" +>>> obj.value +u"foo" +>>> obj.other +u"bar" +>>> obj.name = "b3" +>>> obj.save() + +# You can retrieve a single field on a baseclass +>>> obj = BigChild.objects.only("name").get(name="b3") +>>> count_delayed_fields(obj) +4 +>>> obj.name +u"b3" +>>> obj.value +u"foo" +>>> obj.other +u"bar" +>>> obj.name = "b4" +>>> obj.save() + +# You can retrieve a single field on a baseclass +>>> obj = BigChild.objects.only("other").get(name="b4") +>>> count_delayed_fields(obj) +4 +>>> obj.name +u"b4" +>>> obj.value +u"foo" +>>> obj.other +u"bar" +>>> obj.name = "bb" +>>> obj.save() + +# Finally, we need to flush the app cache for the defer module. +# Using only/defer creates some artifical entries in the app cache +# that messes up later tests. Purge all entries, just to be sure. +>>> from django.db.models.loading import cache +>>> cache.app_models['defer'] = {} """} From fa43a32bcbfd7b2e7092c664251406416ef280fd Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Sat, 6 Jun 2009 12:16:06 +0000 Subject: [PATCH 11/66] Fixed #10733 -- Added a regression test for queries with multiple references to multiple foreign keys in only() clauses. Thanks to mrts for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10928 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- tests/regressiontests/defer_regress/models.py | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/regressiontests/defer_regress/models.py b/tests/regressiontests/defer_regress/models.py index 11ce1557fe..da9822ab88 100644 --- a/tests/regressiontests/defer_regress/models.py +++ b/tests/regressiontests/defer_regress/models.py @@ -84,7 +84,8 @@ Some further checks for select_related() and inherited model behaviour (regression for #10710). >>> c1 = Child.objects.create(name="c1", value=42) ->>> obj = Leaf.objects.create(name="l1", child=c1) +>>> c2 = Child.objects.create(name="c2", value=37) +>>> obj = Leaf.objects.create(name="l1", child=c1, second_child=c2) >>> obj = Leaf.objects.only("name", "child").select_related()[0] >>> obj.child.name @@ -101,5 +102,24 @@ types as their non-deferred versions (bug #10738). >>> c1 is c2 is c3 True +# Regression for #10733 - only() can be used on a model with two foreign keys. +>>> results = Leaf.objects.all().only('name', 'child', 'second_child').select_related() +>>> results[0].child.name +u'c1' +>>> results[0].second_child.name +u'c2' + +>>> results = Leaf.objects.all().only('name', 'child', 'second_child', 'child__name', 'second_child__name').select_related() +>>> results[0].child.name +u'c1' +>>> results[0].second_child.name +u'c2' + +# Finally, we need to flush the app cache for the defer module. +# Using only/defer creates some artifical entries in the app cache +# that messes up later tests. Purge all entries, just to be sure. +>>> from django.db.models.loading import cache +>>> cache.app_models['defer_regress'] = {} + """ } From 151d88af4e972547c40f1e70a3cd982f202f5c86 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Sat, 6 Jun 2009 13:35:33 +0000 Subject: [PATCH 12/66] Fixed #11082 -- Ensured that subqueries used in an exclude(X__in=) clause aren't pre-evaluated. Thanks to Henry Andrews for the report, and clement for the fix. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10929 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/query.py | 13 ++++++++++++ django/db/models/sql/query.py | 6 +++++- tests/regressiontests/queries/models.py | 27 +++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index 0f34fb8a5a..46a86fc03c 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -7,6 +7,8 @@ try: except NameError: from sets import Set as set # Python 2.3 fallback +from copy import deepcopy + from django.db import connection, transaction, IntegrityError from django.db.models.aggregates import Aggregate from django.db.models.fields import DateField @@ -40,6 +42,17 @@ class QuerySet(object): # PYTHON MAGIC METHODS # ######################## + def __deepcopy__(self, memo): + """ + Deep copy of a QuerySet doesn't populate the cache + """ + obj_dict = deepcopy(self.__dict__, memo) + obj_dict['_iter'] = None + + obj = self.__class__() + obj.__dict__.update(obj_dict) + return obj + def __getstate__(self): """ Allows the QuerySet to be pickled. diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 15b9fd6366..23f99e41ad 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1625,10 +1625,14 @@ class BaseQuery(object): entry.negate() self.where.add(entry, AND) break - elif not (lookup_type == 'in' and not value) and field.null: + elif not (lookup_type == 'in' + and not hasattr(value, 'as_sql') + and not hasattr(value, '_as_sql') + and not value) and field.null: # Leaky abstraction artifact: We have to specifically # exclude the "foo__in=[]" case from this handling, because # it's short-circuited in the Where class. + # We also need to handle the case where a subquery is provided entry = self.where_class() entry.add((Constraint(alias, col, None), 'isnull', True), AND) entry.negate() diff --git a/tests/regressiontests/queries/models.py b/tests/regressiontests/queries/models.py index b5fa377496..3649d27171 100644 --- a/tests/regressiontests/queries/models.py +++ b/tests/regressiontests/queries/models.py @@ -1143,6 +1143,33 @@ True >>> r.save() >>> Ranking.objects.all() [, , ] + +# Regression test for #10742: +# Queries used in an __in clause don't execute subqueries + +>>> subq = Author.objects.filter(num__lt=3000) +>>> qs = Author.objects.filter(pk__in=subq) +>>> list(qs) +[, ] +# The subquery result cache should not be populated +>>> subq._result_cache is None +True + +>>> subq = Author.objects.filter(num__lt=3000) +>>> qs = Author.objects.exclude(pk__in=subq) +>>> list(qs) +[, ] +# The subquery result cache should not be populated +>>> subq._result_cache is None +True + +>>> subq = Author.objects.filter(num__lt=3000) +>>> list(Author.objects.filter(Q(pk__in=subq) & Q(name='a1'))) +[] +# The subquery result cache should not be populated +>>> subq._result_cache is None +True + """} # In Python 2.3 and the Python 2.6 beta releases, exceptions raised in __len__ From 708bc80ba63a5512fab3aea59e4e65c4eb380786 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Sat, 6 Jun 2009 13:43:44 +0000 Subject: [PATCH 13/66] Fixed #11271 -- Added a translation marker for the list_editable save button. Thanks to dc for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10931 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/admin/templates/admin/pagination.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/django/contrib/admin/templates/admin/pagination.html b/django/contrib/admin/templates/admin/pagination.html index aaba97fdb7..358813290c 100644 --- a/django/contrib/admin/templates/admin/pagination.html +++ b/django/contrib/admin/templates/admin/pagination.html @@ -8,5 +8,5 @@ {% endif %} {{ cl.result_count }} {% ifequal cl.result_count 1 %}{{ cl.opts.verbose_name }}{% else %}{{ cl.opts.verbose_name_plural }}{% endifequal %} {% if show_all_url %}  {% trans 'Show all' %}{% endif %} -{% if cl.formset and cl.result_count %}{% endif %} +{% if cl.formset and cl.result_count %}{% endif %}

    From 89df572c476c3817eaf33dd9eec3aa9ad4732dcf Mon Sep 17 00:00:00 2001 From: Brian Rosner Date: Sun, 7 Jun 2009 18:07:53 +0000 Subject: [PATCH 14/66] Fixed #11274 -- Corrected doctests to not cause test failures due to missing newlines. Thanks Honza Kral. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10941 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- tests/regressiontests/queries/models.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/regressiontests/queries/models.py b/tests/regressiontests/queries/models.py index 3649d27171..0d28926149 100644 --- a/tests/regressiontests/queries/models.py +++ b/tests/regressiontests/queries/models.py @@ -1151,6 +1151,7 @@ True >>> qs = Author.objects.filter(pk__in=subq) >>> list(qs) [, ] + # The subquery result cache should not be populated >>> subq._result_cache is None True @@ -1159,6 +1160,7 @@ True >>> qs = Author.objects.exclude(pk__in=subq) >>> list(qs) [, ] + # The subquery result cache should not be populated >>> subq._result_cache is None True @@ -1166,6 +1168,7 @@ True >>> subq = Author.objects.filter(num__lt=3000) >>> list(Author.objects.filter(Q(pk__in=subq) & Q(name='a1'))) [] + # The subquery result cache should not be populated >>> subq._result_cache is None True From 6cd37e0a1ffff06517a62c1cb0009825c551e31c Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Mon, 8 Jun 2009 04:50:24 +0000 Subject: [PATCH 15/66] Fixed #10785 -- Corrected a case for foreign key lookup where the related object is a custom primary key. Thanks to Alex Gaynor for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10952 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/related.py | 14 ++++---- tests/modeltests/custom_pk/fields.py | 54 ++++++++++++++++++++++++++++ tests/modeltests/custom_pk/models.py | 27 ++++++++++++++ 3 files changed, 88 insertions(+), 7 deletions(-) create mode 100644 tests/modeltests/custom_pk/fields.py diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 419695b74b..78019f2bd1 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -132,12 +132,13 @@ class RelatedField(object): v, field = getattr(v, v._meta.pk.name), v._meta.pk except AttributeError: pass - if field: - if lookup_type in ('range', 'in'): - v = [v] - v = field.get_db_prep_lookup(lookup_type, v) - if isinstance(v, list): - v = v[0] + if not field: + field = self.rel.get_related_field() + if lookup_type in ('range', 'in'): + v = [v] + v = field.get_db_prep_lookup(lookup_type, v) + if isinstance(v, list): + v = v[0] return v if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): @@ -958,4 +959,3 @@ class ManyToManyField(RelatedField, Field): # A ManyToManyField is not represented by a single column, # so return None. return None - diff --git a/tests/modeltests/custom_pk/fields.py b/tests/modeltests/custom_pk/fields.py new file mode 100644 index 0000000000..319e42f974 --- /dev/null +++ b/tests/modeltests/custom_pk/fields.py @@ -0,0 +1,54 @@ +import random +import string + +from django.db import models + +class MyWrapper(object): + def __init__(self, value): + self.value = value + + def __repr__(self): + return "<%s: %s>" % (self.__class__.__name__, self.value) + + def __unicode__(self): + return self.value + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self.value == other.value + return self.value == other + +class MyAutoField(models.CharField): + __metaclass__ = models.SubfieldBase + + def __init__(self, *args, **kwargs): + kwargs['max_length'] = 10 + super(MyAutoField, self).__init__(*args, **kwargs) + + def pre_save(self, instance, add): + value = getattr(instance, self.attname, None) + if not value: + value = MyWrapper(''.join(random.sample(string.lowercase, 10))) + setattr(instance, self.attname, value) + return value + + def to_python(self, value): + if not value: + return + if not isinstance(value, MyWrapper): + value = MyWrapper(value) + return value + + def get_db_prep_save(self, value): + if not value: + return + if isinstance(value, MyWrapper): + return unicode(value) + return value + + def get_db_prep_value(self, value): + if not value: + return + if isinstance(value, MyWrapper): + return unicode(value) + return value diff --git a/tests/modeltests/custom_pk/models.py b/tests/modeltests/custom_pk/models.py index 091f7f32b4..b1d0cb37d0 100644 --- a/tests/modeltests/custom_pk/models.py +++ b/tests/modeltests/custom_pk/models.py @@ -9,6 +9,8 @@ this behavior by explicitly adding ``primary_key=True`` to a field. from django.conf import settings from django.db import models, transaction, IntegrityError +from fields import MyAutoField + class Employee(models.Model): employee_code = models.IntegerField(primary_key=True, db_column = 'code') first_name = models.CharField(max_length=20) @@ -28,6 +30,16 @@ class Business(models.Model): def __unicode__(self): return self.name +class Bar(models.Model): + id = MyAutoField(primary_key=True, db_index=True) + + def __unicode__(self): + return repr(self.pk) + + +class Foo(models.Model): + bar = models.ForeignKey(Bar) + __test__ = {'API_TESTS':""" >>> dan = Employee(employee_code=123, first_name='Dan', last_name='Jones') >>> dan.save() @@ -121,6 +133,21 @@ DoesNotExist: Employee matching query does not exist. ... print "Fail with %s" % type(e) Pass +# Regression for #10785 -- Custom fields can be used for primary keys. +>>> new_bar = Bar.objects.create() +>>> new_foo = Foo.objects.create(bar=new_bar) +>>> f = Foo.objects.get(bar=new_bar.pk) +>>> f == new_foo +True +>>> f.bar == new_bar +True + +>>> f = Foo.objects.get(bar=new_bar) +>>> f == new_foo +True +>>> f.bar == new_bar +True + """} # SQLite lets objects be saved with an empty primary key, even though an From 81aedbd157209518a2a25ac528f29893900c1ae5 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Mon, 8 Jun 2009 13:04:22 +0000 Subject: [PATCH 16/66] Fixed #10672 -- Altered save_base to ensure that proxy models send a post_save signal. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10954 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/base.py | 29 +++++++++++++++---------- tests/modeltests/proxy_models/models.py | 29 ++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/django/db/models/base.py b/django/db/models/base.py index 13ff7e8f35..325e8764f1 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -411,29 +411,35 @@ class Model(object): save.alters_data = True - def save_base(self, raw=False, cls=None, force_insert=False, - force_update=False): + def save_base(self, raw=False, cls=None, origin=None, + force_insert=False, force_update=False): """ Does the heavy-lifting involved in saving. Subclasses shouldn't need to override this method. It's separate from save() in order to hide the need for overrides of save() to pass around internal-only parameters - ('raw' and 'cls'). + ('raw', 'cls', and 'origin'). """ assert not (force_insert and force_update) - if not cls: + if cls is None: cls = self.__class__ - meta = self._meta - signal = True - signals.pre_save.send(sender=self.__class__, instance=self, raw=raw) + meta = cls._meta + if not meta.proxy: + origin = cls else: meta = cls._meta - signal = False + + if origin: + signals.pre_save.send(sender=origin, instance=self, raw=raw) # If we are in a raw save, save the object exactly as presented. # That means that we don't try to be smart about saving attributes # that might have come from the parent class - we just save the # attributes we have been given to the class we have been given. if not raw: + if meta.proxy: + org = cls + else: + org = None for parent, field in meta.parents.items(): # At this point, parent's primary key field may be unknown # (for example, from administration form which doesn't fill @@ -441,7 +447,8 @@ class Model(object): if field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None: setattr(self, parent._meta.pk.attname, getattr(self, field.attname)) - self.save_base(cls=parent) + self.save_base(cls=parent, origin=org) + if field: setattr(self, field.attname, self._get_pk_val(parent._meta)) if meta.proxy: @@ -492,8 +499,8 @@ class Model(object): setattr(self, meta.pk.attname, result) transaction.commit_unless_managed() - if signal: - signals.post_save.send(sender=self.__class__, instance=self, + if origin: + signals.post_save.send(sender=origin, instance=self, created=(not record_exists), raw=raw) save_base.alters_data = True diff --git a/tests/modeltests/proxy_models/models.py b/tests/modeltests/proxy_models/models.py index 4b3f7d925d..4074a323ae 100644 --- a/tests/modeltests/proxy_models/models.py +++ b/tests/modeltests/proxy_models/models.py @@ -259,6 +259,33 @@ FieldError: Proxy model 'NoNewFields' contains model fields. >>> OtherPerson._default_manager.all() [, ] +# Test save signals for proxy models +>>> from django.db.models import signals +>>> def make_handler(model, event): +... def _handler(*args, **kwargs): +... print u"%s %s save" % (model, event) +... return _handler +>>> h1 = make_handler('MyPerson', 'pre') +>>> h2 = make_handler('MyPerson', 'post') +>>> h3 = make_handler('Person', 'pre') +>>> h4 = make_handler('Person', 'post') +>>> signals.pre_save.connect(h1, sender=MyPerson) +>>> signals.post_save.connect(h2, sender=MyPerson) +>>> signals.pre_save.connect(h3, sender=Person) +>>> signals.post_save.connect(h4, sender=Person) +>>> dino = MyPerson.objects.create(name=u"dino") +MyPerson pre save +MyPerson post save + +# Test save signals for proxy proxy models +>>> h5 = make_handler('MyPersonProxy', 'pre') +>>> h6 = make_handler('MyPersonProxy', 'post') +>>> signals.pre_save.connect(h5, sender=MyPersonProxy) +>>> signals.post_save.connect(h6, sender=MyPersonProxy) +>>> dino = MyPersonProxy.objects.create(name=u"pebbles") +MyPersonProxy pre save +MyPersonProxy post save + # A proxy has the same content type as the model it is proxying for (at the # storage level, it is meant to be essentially indistinguishable). >>> ctype = ContentType.objects.get_for_model @@ -266,7 +293,7 @@ FieldError: Proxy model 'NoNewFields' contains model fields. True >>> MyPersonProxy.objects.all() -[, ] +[, , , ] >>> u = User.objects.create(name='Bruce') >>> User.objects.all() From 031385e4cc3be747319458eab5ba80270a5285f9 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Mon, 8 Jun 2009 13:35:39 +0000 Subject: [PATCH 17/66] Fixed #11194 -- Corrected loading of Proxy models from fixtures (and, by extension, save_base(raw=True) for Proxy models). git-svn-id: http://code.djangoproject.com/svn/django/trunk@10955 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/base.py | 4 +++- .../modeltests/proxy_models/fixtures/mypeople.json | 9 +++++++++ tests/modeltests/proxy_models/models.py | 14 ++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/modeltests/proxy_models/fixtures/mypeople.json diff --git a/django/db/models/base.py b/django/db/models/base.py index 325e8764f1..a5c99865a6 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -435,7 +435,9 @@ class Model(object): # That means that we don't try to be smart about saving attributes # that might have come from the parent class - we just save the # attributes we have been given to the class we have been given. - if not raw: + # We also go through this process to defer the save of proxy objects + # to their actual underlying model. + if not raw or meta.proxy: if meta.proxy: org = cls else: diff --git a/tests/modeltests/proxy_models/fixtures/mypeople.json b/tests/modeltests/proxy_models/fixtures/mypeople.json new file mode 100644 index 0000000000..d20c8f2a6e --- /dev/null +++ b/tests/modeltests/proxy_models/fixtures/mypeople.json @@ -0,0 +1,9 @@ +[ + { + "pk": 100, + "model": "proxy_models.myperson", + "fields": { + "name": "Elvis Presley" + } + } +] \ No newline at end of file diff --git a/tests/modeltests/proxy_models/models.py b/tests/modeltests/proxy_models/models.py index 4074a323ae..e38266fb70 100644 --- a/tests/modeltests/proxy_models/models.py +++ b/tests/modeltests/proxy_models/models.py @@ -286,6 +286,13 @@ MyPerson post save MyPersonProxy pre save MyPersonProxy post save +>>> signals.pre_save.disconnect(h1, sender=MyPerson) +>>> signals.post_save.disconnect(h2, sender=MyPerson) +>>> signals.pre_save.disconnect(h3, sender=Person) +>>> signals.post_save.disconnect(h4, sender=Person) +>>> signals.pre_save.disconnect(h5, sender=MyPersonProxy) +>>> signals.post_save.disconnect(h6, sender=MyPersonProxy) + # A proxy has the same content type as the model it is proxying for (at the # storage level, it is meant to be essentially indistinguishable). >>> ctype = ContentType.objects.get_for_model @@ -354,4 +361,11 @@ True # Select related + filter on a related proxy of proxy field >>> ProxyImprovement.objects.select_related().get(associated_bug__summary__icontains='fix') + +Proxy models can be loaded from fixtures (Regression for #11194) +>>> from django.core import management +>>> management.call_command('loaddata', 'mypeople.json', verbosity=0) +>>> MyPerson.objects.get(pk=100) + + """} From 64be8f29d5a9892047ac40d9306015ac402b1a39 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Tue, 9 Jun 2009 12:59:41 +0000 Subject: [PATCH 18/66] Fixed #9253 -- Modified the method used to generate constraint names so that it is consistent regardless of machine word size. NOTE: This change is backwards incompatible for some users. If you are using a 32-bit platform, you will observe no differences as a result of this change. However, users on 64-bit platforms may experience some problems using the `reset` management command. Prior to this change, 64-bit platforms would generate a 64-bit, 16 character digest in the constraint name; for example: ALTER TABLE `myapp_sometable` ADD CONSTRAINT `object_id_refs_id_5e8f10c132091d1e` FOREIGN KEY ... Following this change, all platforms, regardless of word size, will generate a 32-bit, 8 character digest in the constraint name; for example: ALTER TABLE `myapp_sometable` ADD CONSTRAINT `object_id_refs_id_32091d1e` FOREIGN KEY ... As a result of this change, you will not be able to use the `reset` management command on any table created with 64-bit constraints. This is because the the new generated name will not match the historically generated name; as a result, the SQL constructed by the `reset` command will be invalid. If you need to reset an application that was created with 64-bit constraints, you will need to manually drop the old constraint prior to invoking `reset`. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10966 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/backends/creation.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/django/db/backends/creation.py b/django/db/backends/creation.py index f6041c73f3..53874f9f73 100644 --- a/django/db/backends/creation.py +++ b/django/db/backends/creation.py @@ -25,6 +25,10 @@ class BaseDatabaseCreation(object): def __init__(self, connection): self.connection = connection + def _digest(self, *args): + "Generate a 32 bit digest of a set of arguments that can be used to shorten identifying names" + return '%x' % (abs(hash(args)) % (1<<32)) + def sql_create_model(self, model, style, known_models=set()): """ Returns the SQL required to create a single model, as a tuple of: @@ -128,7 +132,7 @@ class BaseDatabaseCreation(object): col = opts.get_field(f.rel.field_name).column # For MySQL, r_name must be unique in the first 64 characters. # So we are careful with character usage here. - r_name = '%s_refs_%s_%x' % (r_col, col, abs(hash((r_table, table)))) + r_name = '%s_refs_%s_%s' % (r_col, col, self._digest(r_table, table)) final_output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' % \ (qn(r_table), qn(truncate_name(r_name, self.connection.ops.max_name_length())), qn(r_col), qn(table), qn(col), @@ -187,8 +191,7 @@ class BaseDatabaseCreation(object): output.append('\n'.join(table_output)) for r_table, r_col, table, col in deferred: - r_name = '%s_refs_%s_%x' % (r_col, col, - abs(hash((r_table, table)))) + r_name = '%s_refs_%s_%s' % (r_col, col, self._digest(r_table, table)) output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' % (qn(r_table), qn(truncate_name(r_name, self.connection.ops.max_name_length())), @@ -289,7 +292,7 @@ class BaseDatabaseCreation(object): col = f.column r_table = model._meta.db_table r_col = model._meta.get_field(f.rel.field_name).column - r_name = '%s_refs_%s_%x' % (col, r_col, abs(hash((table, r_table)))) + r_name = '%s_refs_%s_%s' % (col, r_col, self._digest(table, r_table)) output.append('%s %s %s %s;' % \ (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(table)), From d3bd3203f9d202ed781d204f283459df87139bc5 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Tue, 9 Jun 2009 13:14:40 +0000 Subject: [PATCH 19/66] Fixed #11286 -- Ensured that dumpdata uses the default manager, rather than always using the manager called `objects`. Thanks to Marc Remolt for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10967 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/management/commands/dumpdata.py | 2 +- tests/regressiontests/fixtures_regress/models.py | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py index 1f2a2db981..9172d938d2 100644 --- a/django/core/management/commands/dumpdata.py +++ b/django/core/management/commands/dumpdata.py @@ -73,7 +73,7 @@ class Command(BaseCommand): model_list = get_models(app) for model in model_list: - objects.extend(model.objects.all()) + objects.extend(model._default_manager.all()) try: return serializers.serialize(format, objects, indent=indent) diff --git a/tests/regressiontests/fixtures_regress/models.py b/tests/regressiontests/fixtures_regress/models.py index 621c80c15f..16a9fc4fc5 100644 --- a/tests/regressiontests/fixtures_regress/models.py +++ b/tests/regressiontests/fixtures_regress/models.py @@ -9,6 +9,9 @@ class Animal(models.Model): count = models.IntegerField() weight = models.FloatField() + # use a non-default name for the default manager + specimens = models.Manager() + def __unicode__(self): return self.common_name @@ -161,4 +164,10 @@ Weight = 1.2 () >>> models.signals.pre_save.disconnect(animal_pre_save_check) +############################################### +# Regression for #11286 -- Ensure that dumpdata honors the default manager +# Dump the current contents of the database as a JSON fixture +>>> management.call_command('dumpdata', 'fixtures_regress.animal', format='json') +[{"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}, {"pk": 2, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.29..., "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}, {"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}] + """} From 74131e82eb1a1bdad1789889c38c8d96b6ab25aa Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 10 Jun 2009 12:44:53 +0000 Subject: [PATCH 20/66] Fixed #11056 -- Corrected reference to File class in storage docs. Thanks to wam for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10970 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/files/storage.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ref/files/storage.txt b/docs/ref/files/storage.txt index 0ca577059e..c8aafa8626 100644 --- a/docs/ref/files/storage.txt +++ b/docs/ref/files/storage.txt @@ -43,8 +43,8 @@ modify the filename as necessary to get a unique name. The actual name of the stored file will be returned. The ``content`` argument must be an instance of -:class:`django.db.files.File` or of a subclass of -:class:`~django.db.files.File`. +:class:`django.core.files.File` or of a subclass of +:class:`~django.core.files.File`. ``Storage.delete(name)`` ~~~~~~~~~~~~~~~~~~~~~~~~ From 6c36d4c4f8379433cdce150a64dad6a1f16097cd Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 10 Jun 2009 12:45:29 +0000 Subject: [PATCH 21/66] Fixed #10981 -- Clarified documentation regarding lazy cross-application relationships. Thanks to Ramiro for the suggestion. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10971 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/models/fields.txt | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 2ec74e4306..177df12862 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -800,21 +800,22 @@ you can use the name of the model, rather than the model object itself:: class Manufacturer(models.Model): # ... -Note, however, that this only refers to models in the same ``models.py`` file -- -you cannot use a string to reference a model defined in another application or -imported from elsewhere. +.. versionadded:: 1.0 -.. versionchanged:: 1.0 - Refering models in other applications must include the application label. - -To refer to models defined in another -application, you must instead explicitly specify the application label. For -example, if the ``Manufacturer`` model above is defined in another application -called ``production``, you'd need to use:: +To refer to models defined in another application, you can explicitly specify +a model with the full application label. For example, if the ``Manufacturer`` +model above is defined in another application called ``production``, you'd +need to use:: class Car(models.Model): manufacturer = models.ForeignKey('production.Manufacturer') +This sort of reference can be useful when resolving circular import +dependencies between two applications. + +Database Representation +~~~~~~~~~~~~~~~~~~~~~~~ + Behind the scenes, Django appends ``"_id"`` to the field name to create its database column name. In the above example, the database table for the ``Car`` model will have a ``manufacturer_id`` column. (You can change this explicitly by @@ -824,6 +825,9 @@ deal with the field names of your model object. .. _foreign-key-arguments: +Arguments +~~~~~~~~~ + :class:`ForeignKey` accepts an extra set of arguments -- all optional -- that define the details of how the relation works. @@ -871,6 +875,9 @@ the model is related. This works exactly the same as it does for :class:`ForeignKey`, including all the options regarding :ref:`recursive ` and :ref:`lazy ` relationships. +Database Representation +~~~~~~~~~~~~~~~~~~~~~~~ + Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the names of the two tables being joined. Since some databases don't support table @@ -882,6 +889,9 @@ You can manually provide the name of the join table using the .. _manytomany-arguments: +Arguments +~~~~~~~~~ + :class:`ManyToManyField` accepts an extra set of arguments -- all optional -- that control how the relationship functions. From 6ad26e6acc34134752d8728bf6dc6e592883bbfa Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 10 Jun 2009 12:46:04 +0000 Subject: [PATCH 22/66] Fixed #10845 -- Clarified the examples for using ModelForms with fields or exclude specified. Thanks to Andrew Durdin for the suggestion. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10972 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/forms/modelforms.txt | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index 370ac887b7..690ca7f391 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -323,16 +323,19 @@ Since the Author model has only 3 fields, 'name', 'title', and to be empty, and does not provide a default value for the missing fields, any attempt to ``save()`` a ``ModelForm`` with missing fields will fail. To avoid this failure, you must instantiate your model with initial values - for the missing, but required fields, or use ``save(commit=False)`` and - manually set any extra required fields:: + for the missing, but required fields:: - instance = Instance(required_field='value') - form = InstanceForm(request.POST, instance=instance) - new_instance = form.save() + author = Author(title='Mr') + form = PartialAuthorForm(request.POST, instance=author) + form.save() - instance = form.save(commit=False) - instance.required_field = 'new value' - new_instance = instance.save() + Alternatively, you can use ``save(commit=False)`` and manually set + any extra required fields:: + + form = PartialAuthorForm(request.POST) + author = form.save(commit=False) + author.title = 'Mr' + author.save() See the `section on saving forms`_ for more details on using ``save(commit=False)``. @@ -563,8 +566,8 @@ number of objects needed:: >>> formset.initial [{'id': 1, 'name': u'Charles Baudelaire'}, {'id': 3, 'name': u'Paul Verlaine'}] -If the value of ``max_num`` is higher than the number of objects returned, up to -``extra`` additional blank forms will be added to the formset, so long as the +If the value of ``max_num`` is higher than the number of objects returned, up to +``extra`` additional blank forms will be added to the formset, so long as the total number of forms does not exceed ``max_num``:: >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2) From 8765615b9b365ed2ee822c1757cc00a9a2813b16 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 10 Jun 2009 12:46:43 +0000 Subject: [PATCH 23/66] Fixed #10801 -- Reverted a portion of [10371]. Practicality beats purity in this case. Thanks to bruce@z2a.org for the report. Refs #9771. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10973 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/intro/tutorial04.txt | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/intro/tutorial04.txt b/docs/intro/tutorial04.txt index 07aa477d67..28ace85ca8 100644 --- a/docs/intro/tutorial04.txt +++ b/docs/intro/tutorial04.txt @@ -20,7 +20,7 @@ tutorial, so that the template contains an HTML ``
    `` element: {% if error_message %}

    {{ error_message }}

    {% endif %} - + {% for choice in poll.choice_set.all %}
    @@ -36,12 +36,12 @@ A quick rundown: selects one of the radio buttons and submits the form, it'll send the POST data ``choice=3``. This is HTML Forms 101. - * We set the form's ``action`` to ``vote/``, and we set ``method="post"``. - Using ``method="post"`` (as opposed to ``method="get"``) is very - important, because the act of submitting this form will alter data - server-side. Whenever you create a form that alters data server-side, use - ``method="post"``. This tip isn't specific to Django; it's just good Web - development practice. + * We set the form's ``action`` to ``/polls/{{ poll.id }}/vote/``, and we + set ``method="post"``. Using ``method="post"`` (as opposed to + ``method="get"``) is very important, because the act of submitting this + form will alter data server-side. Whenever you create a form that alters + data server-side, use ``method="post"``. This tip isn't specific to + Django; it's just good Web development practice. * ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone through its loop @@ -173,11 +173,11 @@ bunch of our own code. We'll just have to take a few steps to make the conversion. We will: 1. Convert the URLconf. - + 2. Rename a few templates. - + 3. Delete some the old, now unneeded views. - + 4. Fix up URL handling for the new views. Read on for details. From 4cb4086b2a16d6992fbffd2e8f15ae11b17412a7 Mon Sep 17 00:00:00 2001 From: Justin Bronn Date: Thu, 11 Jun 2009 02:45:46 +0000 Subject: [PATCH 24/66] Fixed #11245, #11246 -- Fixed validity check of `GeoIP` pointers and leaking of their references; also clarified initialization, fixed a stale test, added comments about version compatibility, and did some whitespace cleanup. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10979 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/tests/test_geoip.py | 7 +-- django/contrib/gis/utils/geoip.py | 85 +++++++++++++++----------- 2 files changed, 54 insertions(+), 38 deletions(-) diff --git a/django/contrib/gis/tests/test_geoip.py b/django/contrib/gis/tests/test_geoip.py index 44b080223c..430d61b6d5 100644 --- a/django/contrib/gis/tests/test_geoip.py +++ b/django/contrib/gis/tests/test_geoip.py @@ -84,16 +84,15 @@ class GeoIPTest(unittest.TestCase): self.assertEqual('USA', d['country_code3']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) - self.assertEqual('77002', d['postal_code']) self.assertEqual(713, d['area_code']) geom = g.geos(query) self.failIf(not isinstance(geom, GEOSGeometry)) - lon, lat = (-95.366996765, 29.752300262) + lon, lat = (-95.4152, 29.7755) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): - self.assertAlmostEqual(lon, tup[0], 9) - self.assertAlmostEqual(lat, tup[1], 9) + self.assertAlmostEqual(lon, tup[0], 4) + self.assertAlmostEqual(lat, tup[1], 4) def suite(): s = unittest.TestSuite() diff --git a/django/contrib/gis/utils/geoip.py b/django/contrib/gis/utils/geoip.py index 8c21ab290a..eedaef95dd 100644 --- a/django/contrib/gis/utils/geoip.py +++ b/django/contrib/gis/utils/geoip.py @@ -6,7 +6,7 @@ GeoIP(R) is a registered trademark of MaxMind, LLC of Boston, Massachusetts. For IP-based geolocation, this module requires the GeoLite Country and City - datasets, in binary format (CSV will not work!). The datasets may be + datasets, in binary format (CSV will not work!). The datasets may be downloaded from MaxMind at http://www.maxmind.com/download/geoip/database/. Grab GeoIP.dat.gz and GeoLiteCity.dat.gz, and unzip them in the directory corresponding to settings.GEOIP_PATH. See the GeoIP docstring and examples @@ -34,7 +34,7 @@ >>> g.lat_lon('salon.com') (37.789798736572266, -122.39420318603516) >>> g.lon_lat('uh.edu') - (-95.415199279785156, 29.77549934387207) + (-95.415199279785156, 29.77549934387207) >>> g.geos('24.124.1.80').wkt 'POINT (-95.2087020874023438 39.0392990112304688)' """ @@ -45,7 +45,7 @@ from django.conf import settings if not settings.configured: settings.configure() # Creating the settings dictionary with any settings, if needed. -GEOIP_SETTINGS = dict((key, getattr(settings, key)) +GEOIP_SETTINGS = dict((key, getattr(settings, key)) for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY') if hasattr(settings, key)) lib_path = GEOIP_SETTINGS.get('GEOIP_LIBRARY_PATH', None) @@ -83,8 +83,17 @@ class GeoIPRecord(Structure): ('postal_code', c_char_p), ('latitude', c_float), ('longitude', c_float), + # TODO: In 1.4.6 this changed from `int dma_code;` to + # `union {int metro_code; int dma_code;};`. Change + # to a `ctypes.Union` in to accomodate in future when + # pre-1.4.6 versions are no longer distributed. ('dma_code', c_int), ('area_code', c_int), + # TODO: The following structure fields were added in 1.4.3 -- + # uncomment these fields when sure previous versions are no + # longer distributed by package maintainers. + #('charset', c_int), + #('continent_code', c_char_p), ] class GeoIPTag(Structure): pass @@ -99,9 +108,12 @@ def record_output(func): rec_by_addr = record_output(lgeoip.GeoIP_record_by_addr) rec_by_name = record_output(lgeoip.GeoIP_record_by_name) -# For opening up GeoIP databases. +# For opening & closing GeoIP database files. geoip_open = lgeoip.GeoIP_open geoip_open.restype = DBTYPE +geoip_close = lgeoip.GeoIP_delete +geoip_close.argtypes = [DBTYPE] +geoip_close.restype = None # String output routines. def string_output(func): @@ -136,6 +148,12 @@ class GeoIP(object): GEOIP_CHECK_CACHE = 2 GEOIP_INDEX_CACHE = 4 cache_options = dict((opt, None) for opt in (0, 1, 2, 4)) + _city_file = '' + _country_file = '' + + # Initially, pointers to GeoIP file references are NULL. + _city = None + _country = None def __init__(self, path=None, cache=0, country=None, city=None): """ @@ -174,13 +192,19 @@ class GeoIP(object): if not isinstance(path, basestring): raise TypeError('Invalid path type: %s' % type(path).__name__) - cntry_ptr, city_ptr = (None, None) if os.path.isdir(path): - # Getting the country and city files using the settings - # dictionary. If no settings are provided, default names - # are assigned. - country = os.path.join(path, country or GEOIP_SETTINGS.get('GEOIP_COUNTRY', 'GeoIP.dat')) - city = os.path.join(path, city or GEOIP_SETTINGS.get('GEOIP_CITY', 'GeoLiteCity.dat')) + # Constructing the GeoIP database filenames using the settings + # dictionary. If the database files for the GeoLite country + # and/or city datasets exist, then try and open them. + country_db = os.path.join(path, country or GEOIP_SETTINGS.get('GEOIP_COUNTRY', 'GeoIP.dat')) + if os.path.isfile(country_db): + self._country = geoip_open(country_db, cache) + self._country_file = country_db + + city_db = os.path.join(path, city or GEOIP_SETTINGS.get('GEOIP_CITY', 'GeoLiteCity.dat')) + if os.path.isfile(city_db): + self._city = geoip_open(city_db, cache) + self._city_file = city_db elif os.path.isfile(path): # Otherwise, some detective work will be needed to figure # out whether the given database path is for the GeoIP country @@ -188,29 +212,22 @@ class GeoIP(object): ptr = geoip_open(path, cache) info = geoip_dbinfo(ptr) if lite_regex.match(info): - # GeoLite City database. - city, city_ptr = path, ptr + # GeoLite City database detected. + self._city = ptr + self._city_file = path elif free_regex.match(info): - # GeoIP Country database. - country, cntry_ptr = path, ptr + # GeoIP Country database detected. + self._country = ptr + self._country_file = path else: raise GeoIPException('Unable to recognize database edition: %s' % info) else: raise GeoIPException('GeoIP path must be a valid file or directory.') - - # `_init_db` does the dirty work. - self._init_db(country, cache, '_country', cntry_ptr) - self._init_db(city, cache, '_city', city_ptr) - def _init_db(self, db_file, cache, attname, ptr=None): - "Helper routine for setting GeoIP ctypes database properties." - if ptr: - # Pointer already retrieved. - pass - elif os.path.isfile(db_file or ''): - ptr = geoip_open(db_file, cache) - setattr(self, attname, ptr) - setattr(self, '%s_file' % attname, db_file) + def __del__(self): + # Cleaning any GeoIP file handles lying around. + if self._country: geoip_close(self._country) + if self._city: geoip_close(self._city) def _check_query(self, query, country=False, city=False, city_or_country=False): "Helper routine for checking the query and database availability." @@ -219,11 +236,11 @@ class GeoIP(object): raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__) # Extra checks for the existence of country and city databases. - if city_or_country and self._country is None and self._city is None: + if city_or_country and not (self._country or self._city): raise GeoIPException('Invalid GeoIP country and city data files.') - elif country and self._country is None: + elif country and not self._country: raise GeoIPException('Invalid GeoIP country data file: %s' % self._country_file) - elif city and self._city is None: + elif city and not self._city: raise GeoIPException('Invalid GeoIP city data file: %s' % self._city_file) def city(self, query): @@ -247,7 +264,7 @@ class GeoIP(object): return dict((tup[0], getattr(record, tup[0])) for tup in record._fields_) else: return None - + def country_code(self, query): "Returns the country code for the given IP Address or FQDN." self._check_query(query, city_or_country=True) @@ -268,12 +285,12 @@ class GeoIP(object): def country(self, query): """ - Returns a dictonary with with the country code and name when given an + Returns a dictonary with with the country code and name when given an IP address or a Fully Qualified Domain Name (FQDN). For example, both '24.124.1.80' and 'djangoproject.com' are valid parameters. """ # Returning the country code and name - return {'country_code' : self.country_code(query), + return {'country_code' : self.country_code(query), 'country_name' : self.country_name(query), } @@ -318,7 +335,7 @@ class GeoIP(object): ci = geoip_dbinfo(self._city) return ci city_info = property(city_info) - + def info(self): "Returns information about all GeoIP databases in use." return 'Country:\n\t%s\nCity:\n\t%s' % (self.country_info, self.city_info) From a5e7d975940feda2c2d03201a1097d726448ec88 Mon Sep 17 00:00:00 2001 From: Brian Rosner Date: Thu, 11 Jun 2009 18:59:48 +0000 Subject: [PATCH 25/66] Fixed #11302 -- Avoid unnesscary (and possibly unintentional) queries/results from generic inline formsets. When an instance with no primary key value is passed in to a generic inline formset we ensure no queries/results occur. Thanks Alex Gaynor. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10981 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/contenttypes/generic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/django/contrib/contenttypes/generic.py b/django/contrib/contenttypes/generic.py index 5564548133..4df48ff9f5 100644 --- a/django/contrib/contenttypes/generic.py +++ b/django/contrib/contenttypes/generic.py @@ -317,7 +317,7 @@ class BaseGenericInlineFormSet(BaseModelFormSet): def get_queryset(self): # Avoid a circular import. from django.contrib.contenttypes.models import ContentType - if self.instance is None: + if self.instance is None or self.instance.pk is None: return self.model._default_manager.none() return self.model._default_manager.filter(**{ self.ct_field.name: ContentType.objects.get_for_model(self.instance), From 9294121d3c4b169406f51d99a915060b175a9bfe Mon Sep 17 00:00:00 2001 From: Luke Plant Date: Fri, 12 Jun 2009 13:56:40 +0000 Subject: [PATCH 26/66] Fixed #9367 - EmailMultiAlternatives does not properly handle attachments. Thanks to Loek Engels for the bulk of the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10983 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/mail.py | 87 +++++++++++++++++++++-------- tests/regressiontests/mail/tests.py | 46 ++++++++++++++- 2 files changed, 109 insertions(+), 24 deletions(-) diff --git a/django/core/mail.py b/django/core/mail.py index 6a45b46587..c305699158 100644 --- a/django/core/mail.py +++ b/django/core/mail.py @@ -195,7 +195,7 @@ class EmailMessage(object): A container for email information. """ content_subtype = 'plain' - multipart_subtype = 'mixed' + mixed_subtype = 'mixed' encoding = None # None => use settings default def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, @@ -234,16 +234,7 @@ class EmailMessage(object): encoding = self.encoding or settings.DEFAULT_CHARSET msg = SafeMIMEText(smart_str(self.body, settings.DEFAULT_CHARSET), self.content_subtype, encoding) - if self.attachments: - body_msg = msg - msg = SafeMIMEMultipart(_subtype=self.multipart_subtype) - if self.body: - msg.attach(body_msg) - for attachment in self.attachments: - if isinstance(attachment, MIMEBase): - msg.attach(attachment) - else: - msg.attach(self._create_attachment(*attachment)) + msg = self._create_message(msg) msg['Subject'] = self.subject msg['From'] = self.extra_headers.pop('From', self.from_email) msg['To'] = ', '.join(self.to) @@ -277,8 +268,7 @@ class EmailMessage(object): def attach(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can - be omitted (useful for multipart/alternative messages) and the mimetype - is guessed, if not provided. + be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments. @@ -296,15 +286,26 @@ class EmailMessage(object): content = open(path, 'rb').read() self.attach(filename, content, mimetype) - def _create_attachment(self, filename, content, mimetype=None): + def _create_message(self, msg): + return self._create_attachments(msg) + + def _create_attachments(self, msg): + if self.attachments: + body_msg = msg + msg = SafeMIMEMultipart(_subtype=self.mixed_subtype) + if self.body: + msg.attach(body_msg) + for attachment in self.attachments: + if isinstance(attachment, MIMEBase): + msg.attach(attachment) + else: + msg.attach(self._create_attachment(*attachment)) + return msg + + def _create_mime_attachment(self, content, mimetype): """ - Converts the filename, content, mimetype triple into a MIME attachment - object. + Converts the content, mimetype pair into a MIME attachment object. """ - if mimetype is None: - mimetype, _ = mimetypes.guess_type(filename) - if mimetype is None: - mimetype = DEFAULT_ATTACHMENT_MIME_TYPE basetype, subtype = mimetype.split('/', 1) if basetype == 'text': attachment = SafeMIMEText(smart_str(content, @@ -314,6 +315,18 @@ class EmailMessage(object): attachment = MIMEBase(basetype, subtype) attachment.set_payload(content) Encoders.encode_base64(attachment) + return attachment + + def _create_attachment(self, filename, content, mimetype=None): + """ + Converts the filename, content, mimetype triple into a MIME attachment + object. + """ + if mimetype is None: + mimetype, _ = mimetypes.guess_type(filename) + if mimetype is None: + mimetype = DEFAULT_ATTACHMENT_MIME_TYPE + attachment = self._create_mime_attachment(content, mimetype) if filename: attachment.add_header('Content-Disposition', 'attachment', filename=filename) @@ -325,11 +338,39 @@ class EmailMultiAlternatives(EmailMessage): messages. For example, including text and HTML versions of the text is made easier. """ - multipart_subtype = 'alternative' + alternative_subtype = 'alternative' - def attach_alternative(self, content, mimetype=None): + def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, + connection=None, attachments=None, headers=None, alternatives=None): + """ + Initialize a single email message (which can be sent to multiple + recipients). + + All strings used to create the message can be unicode strings (or UTF-8 + bytestrings). The SafeMIMEText class will handle any necessary encoding + conversions. + """ + super(EmailMultiAlternatives, self).__init__(subject, body, from_email, to, bcc, connection, attachments, headers) + self.alternatives=alternatives or [] + + def attach_alternative(self, content, mimetype): """Attach an alternative content representation.""" - self.attach(content=content, mimetype=mimetype) + assert content is not None + assert mimetype is not None + self.alternatives.append((content, mimetype)) + + def _create_message(self, msg): + return self._create_attachments(self._create_alternatives(msg)) + + def _create_alternatives(self, msg): + if self.alternatives: + body_msg = msg + msg = SafeMIMEMultipart(_subtype=self.alternative_subtype) + if self.body: + msg.attach(body_msg) + for alternative in self.alternatives: + msg.attach(self._create_mime_attachment(*alternative)) + return msg def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None): diff --git a/tests/regressiontests/mail/tests.py b/tests/regressiontests/mail/tests.py index 40e2f7665f..f4c416c231 100644 --- a/tests/regressiontests/mail/tests.py +++ b/tests/regressiontests/mail/tests.py @@ -4,7 +4,7 @@ r""" >>> from django.conf import settings >>> from django.core import mail ->>> from django.core.mail import EmailMessage, mail_admins, mail_managers +>>> from django.core.mail import EmailMessage, mail_admins, mail_managers, EmailMultiAlternatives >>> from django.utils.translation import ugettext_lazy # Test normal ascii character case: @@ -95,4 +95,48 @@ BadHeaderError: Header values can't contain newlines (got u'Subject\nInjection T >>> message['From'] 'from@example.com' +# Handle attachments within an multipart/alternative mail correctly (#9367) +# (test is not as precise/clear as it could be w.r.t. email tree structure, +# but it's good enough.) + +>>> headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} +>>> subject, from_email, to = 'hello', 'from@example.com', 'to@example.com' +>>> text_content = 'This is an important message.' +>>> html_content = '

    This is an important message.

    ' +>>> msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers) +>>> msg.attach_alternative(html_content, "text/html") +>>> msg.attach("an attachment.pdf", "%PDF-1.4.%...", mimetype="application/pdf") +>>> print msg.message().as_string() +Content-Type: multipart/mixed; boundary="..." +MIME-Version: 1.0 +Subject: hello +From: from@example.com +To: to@example.com +Date: Fri, 09 Nov 2001 01:08:47 -0000 +Message-ID: foo +... +Content-Type: multipart/alternative; boundary="..." +MIME-Version: 1.0 +... +Content-Type: text/plain; charset="utf-8" +MIME-Version: 1.0 +Content-Transfer-Encoding: quoted-printable +... +This is an important message. +... +Content-Type: text/html; charset="utf-8" +MIME-Version: 1.0 +Content-Transfer-Encoding: quoted-printable +... +

    This is an important message.

    +... +... +Content-Type: application/pdf +MIME-Version: 1.0 +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="an attachment.pdf" +... +JVBERi0xLjQuJS4uLg== +... + """ From 694a15ef72afbd5994ca83b20c59aa7ec3d24d3d Mon Sep 17 00:00:00 2001 From: Justin Bronn Date: Fri, 12 Jun 2009 17:16:49 +0000 Subject: [PATCH 27/66] Fixed support for GDAL 1.6 on Windows. Thanks to jtia for spotting this. git-svn-id: http://code.djangoproject.com/svn/django/trunk@10985 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/gdal/libgdal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/django/contrib/gis/gdal/libgdal.py b/django/contrib/gis/gdal/libgdal.py index c1bb45c742..92e3165680 100644 --- a/django/contrib/gis/gdal/libgdal.py +++ b/django/contrib/gis/gdal/libgdal.py @@ -14,7 +14,7 @@ if lib_path: lib_names = None elif os.name == 'nt': # Windows NT shared library - lib_names = ['gdal15'] + lib_names = ['gdal16', 'gdal15'] elif os.name == 'posix': # *NIX library names. lib_names = ['gdal', 'GDAL', 'gdal1.6.0', 'gdal1.5.0', 'gdal1.4.0'] From c98a46c2be042620f28719824fc5d9dfffbef652 Mon Sep 17 00:00:00 2001 From: Gary Wilson Jr Date: Sun, 14 Jun 2009 23:03:01 +0000 Subject: [PATCH 28/66] Fixed #11316 -- Fixed a Python 2.3 compatibilty issue with [10966] (in Python 2.3 on 32-bit machines, 1<<32 is 0). Thanks to kylef for the report and patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11004 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/backends/creation.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/django/db/backends/creation.py b/django/db/backends/creation.py index 53874f9f73..1ac75426c1 100644 --- a/django/db/backends/creation.py +++ b/django/db/backends/creation.py @@ -26,8 +26,11 @@ class BaseDatabaseCreation(object): self.connection = connection def _digest(self, *args): - "Generate a 32 bit digest of a set of arguments that can be used to shorten identifying names" - return '%x' % (abs(hash(args)) % (1<<32)) + """ + Generates a 32-bit digest of a set of arguments that can be used to + shorten identifying names. + """ + return '%x' % (abs(hash(args)) % 4294967296L) # 2**32 def sql_create_model(self, model, style, known_models=set()): """ From b38cf5db5cf843bf6d7c10c93ed707688d67f8aa Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Mon, 15 Jun 2009 11:47:01 +0000 Subject: [PATCH 29/66] Fixed #11311 -- Reverted [10952], Refs #10785. Changeset [10952] caused problems with m2m relations between models that had non-integer primary keys. Thanks to Ronny for the report and test case. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11007 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/related.py | 14 +++++++------- tests/modeltests/custom_pk/models.py | 13 ++++++++----- tests/regressiontests/m2m_regress/models.py | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 78019f2bd1..57392fd62f 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -132,13 +132,13 @@ class RelatedField(object): v, field = getattr(v, v._meta.pk.name), v._meta.pk except AttributeError: pass - if not field: - field = self.rel.get_related_field() - if lookup_type in ('range', 'in'): - v = [v] - v = field.get_db_prep_lookup(lookup_type, v) - if isinstance(v, list): - v = v[0] + + if field: + if lookup_type in ('range', 'in'): + v = [v] + v = field.get_db_prep_lookup(lookup_type, v) + if isinstance(v, list): + v = v[0] return v if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): diff --git a/tests/modeltests/custom_pk/models.py b/tests/modeltests/custom_pk/models.py index b1d0cb37d0..b88af16782 100644 --- a/tests/modeltests/custom_pk/models.py +++ b/tests/modeltests/custom_pk/models.py @@ -136,11 +136,14 @@ Pass # Regression for #10785 -- Custom fields can be used for primary keys. >>> new_bar = Bar.objects.create() >>> new_foo = Foo.objects.create(bar=new_bar) ->>> f = Foo.objects.get(bar=new_bar.pk) ->>> f == new_foo -True ->>> f.bar == new_bar -True + +# FIXME: This still doesn't work, but will require some changes in +# get_db_prep_lookup to fix it. +# >>> f = Foo.objects.get(bar=new_bar.pk) +# >>> f == new_foo +# True +# >>> f.bar == new_bar +# True >>> f = Foo.objects.get(bar=new_bar) >>> f == new_foo diff --git a/tests/regressiontests/m2m_regress/models.py b/tests/regressiontests/m2m_regress/models.py index 5484b26d17..913e719902 100644 --- a/tests/regressiontests/m2m_regress/models.py +++ b/tests/regressiontests/m2m_regress/models.py @@ -33,6 +33,14 @@ class SelfReferChild(SelfRefer): class SelfReferChildSibling(SelfRefer): pass +# Many-to-Many relation between models, where one of the PK's isn't an Autofield +class Line(models.Model): + name = models.CharField(max_length=100) + +class Worksheet(models.Model): + id = models.CharField(primary_key=True, max_length=100) + lines = models.ManyToManyField(Line, blank=True, null=True) + __test__ = {"regressions": """ # Multiple m2m references to the same model or a different model must be # distinguished when accessing the relations through an instance attribute. @@ -79,5 +87,11 @@ FieldError: Cannot resolve keyword 'porcupine' into field. Choices are: id, name >>> sr_sibling.related.all() [] +# Regression for #11311 - The primary key for models in a m2m relation +# doesn't have to be an AutoField +>>> w = Worksheet(id='abc') +>>> w.save() +>>> w.delete() + """ } From 191203b48d2cd593b9adcf99ba2c91db64c40cd1 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Mon, 15 Jun 2009 14:30:51 +0000 Subject: [PATCH 30/66] Fixed #9023 -- Corrected a problem where cached attribute values would cause a delete to cascade to a related object even when the relationship had been set to None. Thanks to TheShark for the report and test case, and to juriejan and Jacob for their work on the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11009 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/related.py | 29 +++++++++++++++++-- .../one_to_one_regress/tests.py | 22 ++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 tests/regressiontests/one_to_one_regress/tests.py diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 57392fd62f..529898ea27 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -112,9 +112,9 @@ class RelatedField(object): def do_related_class(self, other, cls): self.set_attributes_from_rel() - related = RelatedObject(other, cls, self) + self.related = RelatedObject(other, cls, self) if not cls._meta.abstract: - self.contribute_to_related_class(other, related) + self.contribute_to_related_class(other, self.related) def get_db_prep_lookup(self, lookup_type, value): # If we are doing a lookup on a Related Field, we must be @@ -184,7 +184,6 @@ class SingleRelatedObjectDescriptor(object): def __get__(self, instance, instance_type=None): if instance is None: return self - try: return getattr(instance, self.cache_name) except AttributeError: @@ -232,6 +231,7 @@ class ReverseSingleRelatedObjectDescriptor(object): def __get__(self, instance, instance_type=None): if instance is None: return self + cache_name = self.field.get_cache_name() try: return getattr(instance, cache_name) @@ -272,6 +272,29 @@ class ReverseSingleRelatedObjectDescriptor(object): (value, instance._meta.object_name, self.field.name, self.field.rel.to._meta.object_name)) + # If we're setting the value of a OneToOneField to None, we need to clear + # out the cache on any old related object. Otherwise, deleting the + # previously-related object will also cause this object to be deleted, + # which is wrong. + if value is None: + # Look up the previously-related object, which may still be available + # since we've not yet cleared out the related field. + # Use the cache directly, instead of the accessor; if we haven't + # populated the cache, then we don't care - we're only accessing + # the object to invalidate the accessor cache, so there's no + # need to populate the cache just to expire it again. + related = getattr(instance, self.field.get_cache_name(), None) + + # If we've got an old related object, we need to clear out its + # cache. This cache also might not exist if the related object + # hasn't been accessed yet. + if related: + cache_name = '_%s_cache' % self.field.related.get_accessor_name() + try: + delattr(related, cache_name) + except AttributeError: + pass + # Set the value of the related field try: val = getattr(value, self.field.rel.get_related_field().attname) diff --git a/tests/regressiontests/one_to_one_regress/tests.py b/tests/regressiontests/one_to_one_regress/tests.py new file mode 100644 index 0000000000..a0a0c0584f --- /dev/null +++ b/tests/regressiontests/one_to_one_regress/tests.py @@ -0,0 +1,22 @@ +from django.test import TestCase +from regressiontests.one_to_one_regress.models import Place, UndergroundBar + +class OneToOneDeletionTests(TestCase): + def test_reverse_relationship_cache_cascade(self): + """ + Regression test for #9023: accessing the reverse relationship shouldn't + result in a cascading delete(). + """ + place = Place.objects.create(name="Dempsey's", address="623 Vermont St") + bar = UndergroundBar.objects.create(place=place, serves_cocktails=False) + + # The bug in #9023: if you access the one-to-one relation *before* + # setting to None and deleting, the cascade happens anyway. + place.undergroundbar + bar.place.name='foo' + bar.place = None + bar.save() + place.delete() + + self.assertEqual(Place.objects.all().count(), 0) + self.assertEqual(UndergroundBar.objects.all().count(), 1) From f908eded21919cfbbbd1009c63f1cffa316ea2b2 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 17 Jun 2009 13:01:40 +0000 Subject: [PATCH 31/66] Fixed #9268 -- Ensured that the next argument is passed on when previewing comments. Thanks to leanmeandonothingmachine for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11019 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/comments/views/comments.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py index ae3a672a80..89a3dd9bba 100644 --- a/django/contrib/comments/views/comments.py +++ b/django/contrib/comments/views/comments.py @@ -37,6 +37,9 @@ def post_comment(request, next=None): if not data.get('email', ''): data["email"] = request.user.email + # Check to see if the POST data overrides the view's next argument. + next = data.get("next", next) + # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") From 1a7238c7309937a162d4f339a0821ec0f188ac19 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 17 Jun 2009 13:46:52 +0000 Subject: [PATCH 32/66] Fixed #11328 -- Added missing imports in the sample urls.py from Tutorial 3. Thanks to marcalj for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11021 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/intro/tutorial03.txt | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/intro/tutorial03.txt b/docs/intro/tutorial03.txt index 53c2bcfcfc..867b7d1224 100644 --- a/docs/intro/tutorial03.txt +++ b/docs/intro/tutorial03.txt @@ -16,28 +16,28 @@ a specific function and has a specific template. For example, in a weblog application, you might have the following views: * Blog homepage -- displays the latest few entries. - + * Entry "detail" page -- permalink page for a single entry. - + * Year-based archive page -- displays all months with entries in the given year. - + * Month-based archive page -- displays all days with entries in the given month. - + * Day-based archive page -- displays all entries in the given day. - + * Comment action -- handles posting comments to a given entry. In our poll application, we'll have the following four views: * Poll "archive" page -- displays the latest few polls. - + * Poll "detail" page -- displays a poll question, with no results but with a form to vote. - + * Poll "results" page -- displays results for a particular poll. - + * Vote action -- handles voting for a particular choice in a particular poll. @@ -82,6 +82,9 @@ Time for an example. Edit ``mysite/urls.py`` so it looks like this:: from django.conf.urls.defaults import * + from django.contrib import admin + admin.autodiscover() + urlpatterns = patterns('', (r'^polls/$', 'mysite.polls.views.index'), (r'^polls/(?P\d+)/$', 'mysite.polls.views.detail'), @@ -307,7 +310,7 @@ We'll discuss what you could put in that ``polls/detail.html`` template a bit later, but if you'd like to quickly get the above example working, just:: {{ poll }} - + will get you started for now. A shortcut: get_object_or_404() @@ -371,12 +374,12 @@ Three more things to note about 404 views: * The 404 view is also called if Django doesn't find a match after checking every regular expression in the URLconf. - + * If you don't define your own 404 view -- and simply use the default, which is recommended -- you still have one obligation: To create a ``404.html`` template in the root of your template directory. The default 404 view will use that template for all 404 errors. - + * If :setting:`DEBUG` is set to ``False`` (in your settings module) and if you didn't create a ``404.html`` file, an ``Http500`` is raised instead. So remember to create a ``404.html``. From 992ded1ad1a46b5605769735d28aad22d4cb04d5 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 17 Jun 2009 13:47:39 +0000 Subject: [PATCH 33/66] Fixed #9919 -- Added note on the need to mark transactions as dirty when using raw SQL. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11022 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/models/querysets.txt | 2 ++ docs/topics/db/sql.txt | 46 +++++++++++++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index 6c08fe079e..eb8fbfd833 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -616,6 +616,8 @@ call, since they are conflicting options. Both the ``depth`` argument and the ability to specify field names in the call to ``select_related()`` are new in Django version 1.0. +.. _extra: + ``extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt index 4352908909..9c534709ca 100644 --- a/docs/topics/db/sql.txt +++ b/docs/topics/db/sql.txt @@ -29,6 +29,45 @@ is required. For example:: return row +.. _transactions-and-raw-sql: + +Transactions and raw SQL +------------------------ +If you are using transaction decorators (such as ``commit_on_success``) to +wrap your views and provide transaction control, you don't have to make a +manual call to ``transaction.commit_unless_managed()`` -- you can manually +commit if you want to, but you aren't required to, since the decorator will +commit for you. However, if you don't manually commit your changes, you will +need to manually mark the transaction as dirty, using +``transaction.set_dirty()``:: + + @commit_on_success + def my_custom_sql_view(request, value): + from django.db import connection, transaction + cursor = connection.cursor() + + # Data modifying operation + cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value]) + + # Since we modified data, mark the transaction as dirty + transaction.set_dirty() + + # Data retrieval operation. This doesn't dirty the transaction, + # so no call to set_dirty() is required. + cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value]) + row = cursor.fetchone() + + return render_to_response('template.html', {'row': row}) + +The call to ``set_dirty()`` is made automatically when you use the Django ORM +to make data modifying database calls. However, when you use raw SQL, Django +has no way of knowing if your SQL modifies data or not. The manual call to +``set_dirty()`` ensures that Django knows that there are modifications that +must be committed. + +Connections and cursors +----------------------- + ``connection`` and ``cursor`` mostly implement the standard `Python DB-API`_ (except when it comes to :ref:`transaction handling `). If you're not familiar with the Python DB-API, note that the SQL statement in @@ -39,9 +78,12 @@ necessary. (Also note that Django expects the ``"%s"`` placeholder, *not* the ``"?"`` placeholder, which is used by the SQLite Python bindings. This is for the sake of consistency and sanity.) +An easier option? +----------------- + A final note: If all you want to do is a custom ``WHERE`` clause, you can just -use the ``where``, ``tables`` and ``params`` arguments to the standard lookup -API. +use the ``where``, ``tables`` and ``params`` arguments to the +:ref:`extra clause ` in the standard queryset API. .. _Python DB-API: http://www.python.org/peps/pep-0249.html From 6c81952b379712a5bbd4e4d73ec88a07d875b68e Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 17 Jun 2009 14:09:56 +0000 Subject: [PATCH 34/66] Fixed #10336 -- Added improved documentation of generic views. Thanks to Jacob and Adrian for the original text (from the DjangoBook), and Ramiro for doing the work of porting the docs. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11025 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/index.txt | 11 +++-- docs/internals/documentation.txt | 5 --- docs/ref/generic-views.txt | 71 +++++--------------------------- docs/topics/index.txt | 1 + 4 files changed, 19 insertions(+), 69 deletions(-) diff --git a/docs/index.txt b/docs/index.txt index 6f6151b6d6..5ea7cfed5d 100644 --- a/docs/index.txt +++ b/docs/index.txt @@ -98,10 +98,13 @@ The view layer :ref:`Storage API ` | :ref:`Managing files ` | :ref:`Custom storage ` - - * **Advanced:** - :ref:`Generic views ` | - :ref:`Generating CSV ` | + + * **Generic views:** + :ref:`Overview` | + :ref:`Built-in generic views` + + * **Advanced:** + :ref:`Generating CSV ` | :ref:`Generating PDF ` * **Middleware:** diff --git a/docs/internals/documentation.txt b/docs/internals/documentation.txt index b89b296540..f33af32597 100644 --- a/docs/internals/documentation.txt +++ b/docs/internals/documentation.txt @@ -130,11 +130,6 @@ TODO The work is mostly done, but here's what's left, in rough order of priority. - * Fix up generic view docs: adapt Chapter 9 of the Django Book (consider - this TODO item my permission and license) into - ``topics/generic-views.txt``; remove the intro material from - ``ref/generic-views.txt`` and just leave the function reference. - * Change the "Added/changed in development version" callouts to proper Sphinx ``.. versionadded::`` or ``.. versionchanged::`` directives. diff --git a/docs/ref/generic-views.txt b/docs/ref/generic-views.txt index 427ef91090..af23506505 100644 --- a/docs/ref/generic-views.txt +++ b/docs/ref/generic-views.txt @@ -9,67 +9,18 @@ again and again. In Django, the most common of these patterns have been abstracted into "generic views" that let you quickly provide common views of an object without actually needing to write any Python code. -Django's generic views contain the following: +A general introduction to generic views can be found in the :ref:`topic guide +`. - * A set of views for doing list/detail interfaces. - - * A set of views for year/month/day archive pages and associated - detail and "latest" pages (for example, the Django weblog's year_, - month_, day_, detail_, and latest_ pages). - - * A set of views for creating, editing, and deleting objects. - -.. _year: http://www.djangoproject.com/weblog/2005/ -.. _month: http://www.djangoproject.com/weblog/2005/jul/ -.. _day: http://www.djangoproject.com/weblog/2005/jul/20/ -.. _detail: http://www.djangoproject.com/weblog/2005/jul/20/autoreload/ -.. _latest: http://www.djangoproject.com/weblog/ - -All of these views are used by creating configuration dictionaries in -your URLconf files and passing those dictionaries as the third member of the -URLconf tuple for a given pattern. For example, here's the URLconf for the -simple weblog app that drives the blog on djangoproject.com:: - - from django.conf.urls.defaults import * - from django_website.apps.blog.models import Entry - - info_dict = { - 'queryset': Entry.objects.all(), - 'date_field': 'pub_date', - } - - urlpatterns = patterns('django.views.generic.date_based', - (r'^(?P\d{4})/(?P[a-z]{3})/(?P\w{1,2})/(?P[-\w]+)/$', 'object_detail', info_dict), - (r'^(?P\d{4})/(?P[a-z]{3})/(?P\w{1,2})/$', 'archive_day', info_dict), - (r'^(?P\d{4})/(?P[a-z]{3})/$', 'archive_month', info_dict), - (r'^(?P\d{4})/$', 'archive_year', info_dict), - (r'^$', 'archive_index', info_dict), - ) - -As you can see, this URLconf defines a few options in ``info_dict``. -``'queryset'`` gives the generic view a ``QuerySet`` of objects to use (in this -case, all of the ``Entry`` objects) and tells the generic view which model is -being used. - -Documentation of each generic view follows, along with a list of all keyword -arguments that a generic view expects. Remember that as in the example above, -arguments may either come from the URL pattern (as ``month``, ``day``, -``year``, etc. do above) or from the additional-information dictionary (as for -``queryset``, ``date_field``, etc.). +This reference contains details of Django's built-in generic views, along with +a list of all keyword arguments that a generic view expects. Remember that +arguments may either come from the URL pattern or from the ``extra_context`` +additional-information dictionary. Most generic views require the ``queryset`` key, which is a ``QuerySet`` instance; see :ref:`topics-db-queries` for more information about ``QuerySet`` objects. -Most views also take an optional ``extra_context`` dictionary that you can use -to pass any auxiliary information you wish to the view. The values in the -``extra_context`` dictionary can be either functions (or other callables) or -other objects. Functions are evaluated just before they are passed to the -template. However, note that QuerySets retrieve and cache their data when they -are first evaluated, so if you want to pass in a QuerySet via -``extra_context`` that is always fresh you need to wrap it in a function or -lambda that returns the QuerySet. - "Simple" generic views ====================== @@ -801,12 +752,12 @@ specify the page number in the URL in one of two ways: /objects/?page=3 - * To loop over all the available page numbers, use the ``page_range`` - variable. You can iterate over the list provided by ``page_range`` + * To loop over all the available page numbers, use the ``page_range`` + variable. You can iterate over the list provided by ``page_range`` to create a link to every page of results. These values and lists are 1-based, not 0-based, so the first page would be -represented as page ``1``. +represented as page ``1``. For more on pagination, read the :ref:`pagination documentation `. @@ -818,7 +769,7 @@ As a special case, you are also permitted to use ``last`` as a value for /objects/?page=last -This allows you to access the final page of results without first having to +This allows you to access the final page of results without first having to determine how many pages there are. Note that ``page`` *must* be either a valid page number or the value ``last``; @@ -909,7 +860,7 @@ library ` to build and display the form. **Description:** A page that displays a form for creating an object, redisplaying the form with -validation errors (if there are any) and saving the object. +validation errors (if there are any) and saving the object. **Required arguments:** diff --git a/docs/topics/index.txt b/docs/topics/index.txt index 20d7aa3061..a760d3d80c 100644 --- a/docs/topics/index.txt +++ b/docs/topics/index.txt @@ -14,6 +14,7 @@ Introductions to all the key parts of Django you'll need to know: forms/index forms/modelforms templates + generic-views files testing auth From ec1baddbb789f21ecaa9139765b52365d21a5d6b Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 17 Jun 2009 14:16:27 +0000 Subject: [PATCH 35/66] Update to [11025]. This time, actually include the new generic views documentation. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11026 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/generic-views.txt | 503 ++++++++++++++++++++++++++++++++++ 1 file changed, 503 insertions(+) create mode 100644 docs/topics/generic-views.txt diff --git a/docs/topics/generic-views.txt b/docs/topics/generic-views.txt new file mode 100644 index 0000000000..8e8f38b3ce --- /dev/null +++ b/docs/topics/generic-views.txt @@ -0,0 +1,503 @@ +.. _topics-generic-views: + +============= +Generic views +============= + +Writing Web applications can be monotonous, because we repeat certain patterns +again and again. Django tries to take away some of that monotony at the model +and template layers, but Web developers also experience this boredom at the view +level. + +Django's *generic views* were developed to ease that pain. They take certain +common idioms and patterns found in view development and abstract them so that +you can quickly write common views of data without having to write too much +code. + +We can recognize certain common tasks, like displaying a list of objects, and +write code that displays a list of *any* object. Then the model in question can +be passed as an extra argument to the URLconf. + +Django ships with generic views to do the following: + + * Perform common "simple" tasks: redirect to a different page and + render a given template. + + * Display list and detail pages for a single object. If we were creating an + application to manage conferences then a ``talk_list`` view and a + ``registered_user_list`` view would be examples of list views. A single + talk page is an example of what we call a "detail" view. + + * Present date-based objects in year/month/day archive pages, + associated detail, and "latest" pages. The Django Weblog's + (http://www.djangoproject.com/weblog/) year, month, and + day archives are built with these, as would be a typical + newspaper's archives. + + * Allow users to create, update, and delete objects -- with or + without authorization. + +Taken together, these views provide easy interfaces to perform the most common +tasks developers encounter. + +Using generic views +=================== + +All of these views are used by creating configuration dictionaries in +your URLconf files and passing those dictionaries as the third member of the +URLconf tuple for a given pattern. + +For example, here's a simple URLconf you could use to present a static "about" +page:: + + from django.conf.urls.defaults import * + from django.views.generic.simple import direct_to_template + + urlpatterns = patterns('', + ('^about/$', direct_to_template, { + 'template': 'about.html' + }) + ) + +Though this might seem a bit "magical" at first glance -- look, a view with no +code! --, actually the ``direct_to_template`` view simply grabs information from +the extra-parameters dictionary and uses that information when rendering the +view. + +Because this generic view -- and all the others -- is a regular view functions +like any other, we can reuse it inside our own views. As an example, let's +extend our "about" example to map URLs of the form ``/about//`` to +statically rendered ``about/.html``. We'll do this by first modifying +the URLconf to point to a view function: + +.. parsed-literal:: + + from django.conf.urls.defaults import * + from django.views.generic.simple import direct_to_template + **from mysite.books.views import about_pages** + + urlpatterns = patterns('', + ('^about/$', direct_to_template, { + 'template': 'about.html' + }), + **('^about/(\w+)/$', about_pages),** + ) + +Next, we'll write the ``about_pages`` view:: + + from django.http import Http404 + from django.template import TemplateDoesNotExist + from django.views.generic.simple import direct_to_template + + def about_pages(request, page): + try: + return direct_to_template(request, template="about/%s.html" % page) + except TemplateDoesNotExist: + raise Http404() + +Here we're treating ``direct_to_template`` like any other function. Since it +returns an ``HttpResponse``, we can simply return it as-is. The only slightly +tricky business here is dealing with missing templates. We don't want a +nonexistent template to cause a server error, so we catch +``TemplateDoesNotExist`` exceptions and return 404 errors instead. + +.. admonition:: Is there a security vulnerability here? + + Sharp-eyed readers may have noticed a possible security hole: we're + constructing the template name using interpolated content from the browser + (``template="about/%s.html" % page``). At first glance, this looks like a + classic *directory traversal* vulnerability. But is it really? + + Not exactly. Yes, a maliciously crafted value of ``page`` could cause + directory traversal, but although ``page`` *is* taken from the request URL, + not every value will be accepted. The key is in the URLconf: we're using + the regular expression ``\w+`` to match the ``page`` part of the URL, and + ``\w`` only accepts letters and numbers. Thus, any malicious characters + (dots and slashes, here) will be rejected by the URL resolver before they + reach the view itself. + +Generic views of objects +======================== + +The ``direct_to_template`` certainly is useful, but Django's generic views +really shine when it comes to presenting views on your database content. Because +it's such a common task, Django comes with a handful of built-in generic views +that make generating list and detail views of objects incredibly easy. + +Let's take a look at one of these generic views: the "object list" view. We'll +be using these models:: + + # models.py + from django.db import models + + class Publisher(models.Model): + name = models.CharField(max_length=30) + address = models.CharField(max_length=50) + city = models.CharField(max_length=60) + state_province = models.CharField(max_length=30) + country = models.CharField(max_length=50) + website = models.URLField() + + def __unicode__(self): + return self.name + + class Meta: + ordering = ["-name"] + + class Book(models.Model): + title = models.CharField(max_length=100) + authors = models.ManyToManyField('Author') + publisher = models.ForeignKey(Publisher) + publication_date = models.DateField() + +To build a list page of all books, we'd use a URLconf along these lines:: + + from django.conf.urls.defaults import * + from django.views.generic import list_detail + from mysite.books.models import Publisher + + publisher_info = { + "queryset" : Publisher.objects.all(), + } + + urlpatterns = patterns('', + (r'^publishers/$', list_detail.object_list, publisher_info) + ) + +That's all the Python code we need to write. We still need to write a template, +however. We could explicitly tell the ``object_list`` view which template to use +by including a ``template_name`` key in the extra arguments dictionary, but in +the absence of an explicit template Django will infer one from the object's +name. In this case, the inferred template will be +``"books/publisher_list.html"`` -- the "books" part comes from the name of the +app that defines the model, while the "publisher" bit is just the lowercased +version of the model's name. + +.. highlightlang:: html+django + +This template will be rendered against a context containing a variable called +``object_list`` that contains all the book objects. A very simple template +might look like the following:: + + {% extends "base.html" %} + + {% block content %} +

    Publishers

    +
      + {% for publisher in object_list %} +
    • {{ publisher.name }}
    • + {% endfor %} +
    + {% endblock %} + +That's really all there is to it. All the cool features of generic views come +from changing the "info" dictionary passed to the generic view. The +:ref:`generic views reference` documents all the generic +views and all their options in detail; the rest of this document will consider +some of the common ways you might customize and extend generic views. + +Extending generic views +======================= + +.. highlightlang:: python + +There's no question that using generic views can speed up development +substantially. In most projects, however, there comes a moment when the +generic views no longer suffice. Indeed, the most common question asked by new +Django developers is how to make generic views handle a wider array of +situations. + +Luckily, in nearly every one of these cases, there are ways to simply extend +generic views to handle a larger array of use cases. These situations usually +fall into a handful of patterns dealt with in the sections that follow. + +Making "friendly" template contexts +----------------------------------- + +You might have noticed that our sample publisher list template stores all the +books in a variable named ``object_list``. While this works just fine, it isn't +all that "friendly" to template authors: they have to "just know" that they're +dealing with books here. A better name for that variable would be +``publisher_list``; that variable's content is pretty obvious. + +We can change the name of that variable easily with the ``template_object_name`` +argument: + +.. parsed-literal:: + + publisher_info = { + "queryset" : Publisher.objects.all(), + **"template_object_name" : "publisher",** + } + + urlpatterns = patterns('', + (r'^publishers/$', list_detail.object_list, publisher_info) + ) + +Providing a useful ``template_object_name`` is always a good idea. Your +coworkers who design templates will thank you. + +Adding extra context +-------------------- + +Often you simply need to present some extra information beyond that provided by +the generic view. For example, think of showing a list of all the other +publishers on each publisher detail page. The ``object_detail`` generic view +provides the publisher to the context, but it seems there's no way to get a list +of *all* publishers in that template. + +But there is: all generic views take an extra optional parameter, +``extra_context``. This is a dictionary of extra objects that will be added to +the template's context. So, to provide the list of all publishers on the detail +detail view, we'd use an info dict like this: + +.. parsed-literal:: + + from mysite.books.models import Publisher, **Book** + + publisher_info = { + "queryset" : Publisher.objects.all(), + "template_object_name" : "publisher", + **"extra_context" : {"book_list" : Book.objects.all()}** + } + +This would populate a ``{{ book_list }}`` variable in the template context. +This pattern can be used to pass any information down into the template for the +generic view. It's very handy. + +However, there's actually a subtle bug here -- can you spot it? + +The problem has to do with when the queries in ``extra_context`` are evaluated. +Because this example puts ``Publisher.objects.all()`` in the URLconf, it will +be evaluated only once (when the URLconf is first loaded). Once you add or +remove publishers, you'll notice that the generic view doesn't reflect those +changes until you reload the Web server (see :ref:`caching-and-querysets` +for more information about when QuerySets are cached and evaluated). + +.. note:: + + This problem doesn't apply to the ``queryset`` generic view argument. Since + Django knows that particular QuerySet should *never* be cached, the generic + view takes care of clearing the cache when each view is rendered. + +The solution is to use a callback in ``extra_context`` instead of a value. Any +callable (i.e., a function) that's passed to ``extra_context`` will be evaluated +when the view is rendered (instead of only once). You could do this with an +explicitly defined function: + +.. parsed-literal:: + + def get_books(): + return Book.objects.all() + + publisher_info = { + "queryset" : Publisher.objects.all(), + "template_object_name" : "publisher", + "extra_context" : **{"book_list" : get_books}** + } + +or you could use a less obvious but shorter version that relies on the fact that +``Publisher.objects.all`` is itself a callable: + +.. parsed-literal:: + + publisher_info = { + "queryset" : Publisher.objects.all(), + "template_object_name" : "publisher", + "extra_context" : **{"book_list" : Book.objects.all}** + } + +Notice the lack of parentheses after ``Book.objects.all``; this references +the function without actually calling it (which the generic view will do later). + +Viewing subsets of objects +-------------------------- + +Now let's take a closer look at this ``queryset`` key we've been using all +along. Most generic views take one of these ``queryset`` arguments -- it's how +the view knows which set of objects to display (see :ref:`topics-db-queries` for +more information about ``QuerySet`` objects, and see the +:ref:`generic views reference` for the complete details). + +To pick a simple example, we might want to order a list of books by +publication date, with the most recent first: + +.. parsed-literal:: + + book_info = { + "queryset" : Book.objects.all().order_by("-publication_date"), + } + + urlpatterns = patterns('', + (r'^publishers/$', list_detail.object_list, publisher_info), + **(r'^books/$', list_detail.object_list, book_info),** + ) + + +That's a pretty simple example, but it illustrates the idea nicely. Of course, +you'll usually want to do more than just reorder objects. If you want to +present a list of books by a particular publisher, you can use the same +technique: + +.. parsed-literal:: + + **acme_books = {** + **"queryset": Book.objects.filter(publisher__name="Acme Publishing"),** + **"template_name" : "books/acme_list.html"** + **}** + + urlpatterns = patterns('', + (r'^publishers/$', list_detail.object_list, publisher_info), + **(r'^books/acme/$', list_detail.object_list, acme_books),** + ) + +Notice that along with a filtered ``queryset``, we're also using a custom +template name. If we didn't, the generic view would use the same template as the +"vanilla" object list, which might not be what we want. + +Also notice that this isn't a very elegant way of doing publisher-specific +books. If we want to add another publisher page, we'd need another handful of +lines in the URLconf, and more than a few publishers would get unreasonable. +We'll deal with this problem in the next section. + +.. note:: + + If you get a 404 when requesting ``/books/acme/``, check to ensure you + actually have a Publisher with the name 'ACME Publishing'. Generic + views have an ``allow_empty`` parameter for this case. See the + :ref:`generic views reference` for more details. + +Complex filtering with wrapper functions +---------------------------------------- + +Another common need is to filter down the objects given in a list page by some +key in the URL. Earlier we hard-coded the publisher's name in the URLconf, but +what if we wanted to write a view that displayed all the books by some arbitrary +publisher? We can "wrap" the ``object_list`` generic view to avoid writing a lot +of code by hand. As usual, we'll start by writing a URLconf: + +.. parsed-literal:: + + from mysite.books.views import books_by_publisher + + urlpatterns = patterns('', + (r'^publishers/$', list_detail.object_list, publisher_info), + **(r'^books/(\w+)/$', books_by_publisher),** + ) + +Next, we'll write the ``books_by_publisher`` view itself:: + + from django.http import Http404 + from django.views.generic import list_detail + from mysite.books.models import Book, Publisher + + def books_by_publisher(request, name): + + # Look up the publisher (and raise a 404 if it can't be found). + try: + publisher = Publisher.objects.get(name__iexact=name) + except Publisher.DoesNotExist: + raise Http404 + + # Use the object_list view for the heavy lifting. + return list_detail.object_list( + request, + queryset = Book.objects.filter(publisher=publisher), + template_name = "books/books_by_publisher.html", + template_object_name = "books", + extra_context = {"publisher" : publisher} + ) + +This works because there's really nothing special about generic views -- they're +just Python functions. Like any view function, generic views expect a certain +set of arguments and return ``HttpResponse`` objects. Thus, it's incredibly easy +to wrap a small function around a generic view that does additional work before +(or after; see the next section) handing things off to the generic view. + +.. note:: + + Notice that in the preceding example we passed the current publisher being + displayed in the ``extra_context``. This is usually a good idea in wrappers + of this nature; it lets the template know which "parent" object is currently + being browsed. + +Performing extra work +--------------------- + +The last common pattern we'll look at involves doing some extra work before +or after calling the generic view. + +Imagine we had a ``last_accessed`` field on our ``Author`` object that we were +using to keep track of the last time anybody looked at that author:: + + # models.py + + class Author(models.Model): + salutation = models.CharField(max_length=10) + first_name = models.CharField(max_length=30) + last_name = models.CharField(max_length=40) + email = models.EmailField() + headshot = models.ImageField(upload_to='/tmp') + last_accessed = models.DateTimeField() + +The generic ``object_detail`` view, of course, wouldn't know anything about this +field, but once again we could easily write a custom view to keep that field +updated. + +First, we'd need to add an author detail bit in the URLconf to point to a +custom view: + +.. parsed-literal:: + + from mysite.books.views import author_detail + + urlpatterns = patterns('', + #... + **(r'^authors/(?P\d+)/$', author_detail),** + ) + +Then we'd write our wrapper function:: + + import datetime + from mysite.books.models import Author + from django.views.generic import list_detail + from django.shortcuts import get_object_or_404 + + def author_detail(request, author_id): + # Look up the Author (and raise a 404 if she's not found) + author = get_object_or_404(Author, pk=author_id) + + # Record the last accessed date + author.last_accessed = datetime.datetime.now() + author.save() + + # Show the detail page + return list_detail.object_detail( + request, + queryset = Author.objects.all(), + object_id = author_id, + ) + +.. note:: + + This code won't actually work unless you create a + ``books/author_detail.html`` template. + +We can use a similar idiom to alter the response returned by the generic view. +If we wanted to provide a downloadable plain-text version of the list of +authors, we could use a view like this:: + + def author_list_plaintext(request): + response = list_detail.object_list( + request, + queryset = Author.objects.all(), + mimetype = "text/plain", + template_name = "books/author_list.txt" + ) + response["Content-Disposition"] = "attachment; filename=authors.txt" + return response + +This works because the generic views return simple ``HttpResponse`` objects +that can be treated like dictionaries to set HTTP headers. This +``Content-Disposition`` business, by the way, instructs the browser to +download and save the page instead of displaying it in the browser. From 80c0ee0be7755d6cdb45c0fb1541757a50851bd4 Mon Sep 17 00:00:00 2001 From: Karen Tracey Date: Wed, 17 Jun 2009 19:59:50 +0000 Subject: [PATCH 36/66] Fixed #11335 -- Corrected model reference in generic views doc. Thanks oyvind. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11028 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/generic-views.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/generic-views.txt b/docs/topics/generic-views.txt index 8e8f38b3ce..c7d751a86b 100644 --- a/docs/topics/generic-views.txt +++ b/docs/topics/generic-views.txt @@ -297,7 +297,7 @@ explicitly defined function: } or you could use a less obvious but shorter version that relies on the fact that -``Publisher.objects.all`` is itself a callable: +``Book.objects.all`` is itself a callable: .. parsed-literal:: From c9d882c4b6087f2831bb3bc62b473f57904663bf Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 17 Jun 2009 23:57:27 +0000 Subject: [PATCH 37/66] Fixed #11336 -- Dummy commit to force refresh of some index pages by Sphinx, caused by file ommitted from [11025] and included in [11026]. Thanks to Peter Landry for the report, and Ramiro for the explanation. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11031 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/index.txt | 157 +++++++++++++++++++++++---------------------- docs/ref/index.txt | 1 + 2 files changed, 80 insertions(+), 78 deletions(-) diff --git a/docs/index.txt b/docs/index.txt index 5ea7cfed5d..89ee463dfa 100644 --- a/docs/index.txt +++ b/docs/index.txt @@ -1,3 +1,4 @@ + .. _index: ==================== @@ -33,70 +34,70 @@ Having trouble? We'd like to help! First steps =========== - * **From scratch:** + * **From scratch:** :ref:`Overview ` | :ref:`Installation ` - - * **Tutorial:** - :ref:`Part 1 ` | - :ref:`Part 2 ` | - :ref:`Part 3 ` | + + * **Tutorial:** + :ref:`Part 1 ` | + :ref:`Part 2 ` | + :ref:`Part 3 ` | :ref:`Part 4 ` The model layer =============== - * **Models:** - :ref:`Model syntax ` | - :ref:`Field types ` | + * **Models:** + :ref:`Model syntax ` | + :ref:`Field types ` | :ref:`Meta options ` - - * **QuerySets:** - :ref:`Executing queries ` | + + * **QuerySets:** + :ref:`Executing queries ` | :ref:`QuerySet method reference ` - - * **Model instances:** - :ref:`Instance methods ` | + + * **Model instances:** + :ref:`Instance methods ` | :ref:`Accessing related objects ` - - * **Advanced:** - :ref:`Managers ` | - :ref:`Raw SQL ` | - :ref:`Transactions ` | - :ref:`Aggregation ` | + + * **Advanced:** + :ref:`Managers ` | + :ref:`Raw SQL ` | + :ref:`Transactions ` | + :ref:`Aggregation ` | :ref:`Custom fields ` - - * **Other:** - :ref:`Supported databases ` | - :ref:`Legacy databases ` | + + * **Other:** + :ref:`Supported databases ` | + :ref:`Legacy databases ` | :ref:`Providing initial data ` The template layer ================== - * **For designers:** - :ref:`Syntax overview ` | + * **For designers:** + :ref:`Syntax overview ` | :ref:`Built-in tags and filters ` - - * **For programmers:** - :ref:`Template API ` | + + * **For programmers:** + :ref:`Template API ` | :ref:`Custom tags and filters ` The view layer ============== - * **The basics:** - :ref:`URLconfs ` | - :ref:`View functions ` | + * **The basics:** + :ref:`URLconfs ` | + :ref:`View functions ` | :ref:`Shortcuts ` - + * **Reference:** :ref:`Request/response objects ` - - * **File uploads:** - :ref:`Overview ` | - :ref:`File objects ` | - :ref:`Storage API ` | - :ref:`Managing files ` | + + * **File uploads:** + :ref:`Overview ` | + :ref:`File objects ` | + :ref:`Storage API ` | + :ref:`Managing files ` | :ref:`Custom storage ` * **Generic views:** @@ -106,50 +107,50 @@ The view layer * **Advanced:** :ref:`Generating CSV ` | :ref:`Generating PDF ` - - * **Middleware:** - :ref:`Overview ` | + + * **Middleware:** + :ref:`Overview ` | :ref:`Built-in middleware classes ` Forms ===== - * **The basics:** - :ref:`Overview ` | - :ref:`Form API ` | - :ref:`Built-in fields ` | + * **The basics:** + :ref:`Overview ` | + :ref:`Form API ` | + :ref:`Built-in fields ` | :ref:`Built-in widgets ` - - * **Advanced:** - :ref:`Forms for models ` | - :ref:`Integrating media ` | - :ref:`Formsets ` | + + * **Advanced:** + :ref:`Forms for models ` | + :ref:`Integrating media ` | + :ref:`Formsets ` | :ref:`Customizing validation ` - - * **Extras:** - :ref:`Form preview ` | + + * **Extras:** + :ref:`Form preview ` | :ref:`Form wizard ` The development process ======================= - * **Settings:** - :ref:`Overview ` | + * **Settings:** + :ref:`Overview ` | :ref:`Full list of settings ` - * **django-admin.py and manage.py:** - :ref:`Overview ` | + * **django-admin.py and manage.py:** + :ref:`Overview ` | :ref:`Adding custom commands ` - + * **Testing:** :ref:`Overview ` - - * **Deployment:** - :ref:`Overview ` | + + * **Deployment:** + :ref:`Overview ` | :ref:`Apache/mod_wsgi ` | :ref:`Apache/mod_python ` | - :ref:`FastCGI/SCGI/AJP ` | - :ref:`Apache authentication ` | - :ref:`Serving static files ` | + :ref:`FastCGI/SCGI/AJP ` | + :ref:`Apache authentication ` | + :ref:`Serving static files ` | :ref:`Tracking code errors by e-mail ` Other batteries included @@ -183,22 +184,22 @@ Other batteries included The Django open-source project ============================== - * **Community:** - :ref:`How to get involved ` | - :ref:`The release process ` | + * **Community:** + :ref:`How to get involved ` | + :ref:`The release process ` | :ref:`Team of committers ` - - * **Design philosophies:** + + * **Design philosophies:** :ref:`Overview ` - - * **Documentation:** + + * **Documentation:** :ref:`About this documentation ` - - * **Third-party distributions:** + + * **Third-party distributions:** :ref:`Overview ` - - * **Django over time:** - :ref:`API stability ` | + + * **Django over time:** + :ref:`API stability ` | :ref:`Archive of release notes ` | `Backwards-incompatible changes`_ .. _Backwards-incompatible changes: http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges diff --git a/docs/ref/index.txt b/docs/ref/index.txt index 3ffa1fcce1..6cc796d8e4 100644 --- a/docs/ref/index.txt +++ b/docs/ref/index.txt @@ -20,3 +20,4 @@ API Reference signals templates/index unicode + From 15a908b4d1c890a480e2a50b0f23ad6fd259ce29 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 00:16:48 +0000 Subject: [PATCH 38/66] Refs #11336 -- Another dummy commit to force refresh of some index pages by Sphinx, caused by file ommitted from [11025] and included in [11026]. Thanks to Peter Landry for the report, and Ramiro for the explanation. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11032 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/generic-views.txt | 1 + docs/topics/index.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/ref/generic-views.txt b/docs/ref/generic-views.txt index af23506505..4752a705a0 100644 --- a/docs/ref/generic-views.txt +++ b/docs/ref/generic-views.txt @@ -1088,3 +1088,4 @@ In addition to ``extra_context``, the template's context will be: variable's name depends on the ``template_object_name`` parameter, which is ``'object'`` by default. If ``template_object_name`` is ``'foo'``, this variable's name will be ``foo``. + diff --git a/docs/topics/index.txt b/docs/topics/index.txt index a760d3d80c..7fa283aa1a 100644 --- a/docs/topics/index.txt +++ b/docs/topics/index.txt @@ -26,3 +26,4 @@ Introductions to all the key parts of Django you'll need to know: serialization settings signals + From 79d2cf3c121667808bdb1514adbb98317a25ebc4 Mon Sep 17 00:00:00 2001 From: Karen Tracey Date: Thu, 18 Jun 2009 12:41:16 +0000 Subject: [PATCH 39/66] Fixed #11339 -- Corrected typo in FAQ. Thanks Kellen. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11041 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/faq/install.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/faq/install.txt b/docs/faq/install.txt index 1c6ef43d7d..fb8005c7e7 100644 --- a/docs/faq/install.txt +++ b/docs/faq/install.txt @@ -26,7 +26,7 @@ For a development environment -- if you just want to experiment with Django -- you don't need to have a separate Web server installed; Django comes with its own lightweight development server. For a production environment, Django follows the WSGI_ spec, which means it can run on a variety of server -platforms. See :ref:`Deplying Django ` for some +platforms. See :ref:`Deploying Django ` for some popular alternatives. Also, the `server arrangements wiki page`_ contains details for several deployment strategies. From bc362cc6b81386d36f078a741e38f00b67fd4f8d Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:30:52 +0000 Subject: [PATCH 40/66] Fixed #10848 -- Added prairiedogg to AUTHORS. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11043 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 8367420fdf..5f36d83770 100644 --- a/AUTHORS +++ b/AUTHORS @@ -226,6 +226,7 @@ answer newbie questions, and generally made Django that much better: Ian G. Kelly Ryan Kelly Thomas Kerpe + Wiley Kestner Ossama M. Khayat Ben Khoo Garth Kidd From 457a1f9a031543e3d5d1cfb3944712fe71ebba2f Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:32:12 +0000 Subject: [PATCH 41/66] Fixed #11272 -- Made some clarifications to the overview and tutorial. Thanks to jjinux for the review notes. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11044 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/intro/overview.txt | 10 ++++----- docs/intro/tutorial01.txt | 36 +++++++++++++++---------------- docs/intro/tutorial02.txt | 8 +++---- docs/intro/tutorial03.txt | 8 +++---- docs/ref/contrib/contenttypes.txt | 4 ++-- docs/topics/http/sessions.txt | 3 +++ 6 files changed, 36 insertions(+), 33 deletions(-) diff --git a/docs/intro/overview.txt b/docs/intro/overview.txt index 297dd38f79..594c9fe582 100644 --- a/docs/intro/overview.txt +++ b/docs/intro/overview.txt @@ -144,10 +144,10 @@ as registering your model in the admin site:: headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter) - + # In admin.py in the same directory... - + import models from django.contrib import admin @@ -243,9 +243,9 @@ might look like:

    Articles for {{ year }}

    {% for article in article_list %} -

    {{ article.headline }}

    -

    By {{ article.reporter.full_name }}

    -

    Published {{ article.pub_date|date:"F j, Y" }}

    +

    {{ article.headline }}

    +

    By {{ article.reporter.full_name }}

    +

    Published {{ article.pub_date|date:"F j, Y" }}

    {% endfor %} {% endblock %} diff --git a/docs/intro/tutorial01.txt b/docs/intro/tutorial01.txt index c0ad3dd8cf..ae4af665f1 100644 --- a/docs/intro/tutorial01.txt +++ b/docs/intro/tutorial01.txt @@ -42,13 +42,13 @@ code, then run the command ``django-admin.py startproject mysite``. This will create a ``mysite`` directory in your current directory. .. admonition:: Mac OS X permissions - + If you're using Mac OS X, you may see the message "permission denied" when you try to run ``django-admin.py startproject``. This is because, on Unix-based systems like OS X, a file must be marked as "executable" before it can be run as a program. To do this, open Terminal.app and navigate (using the ``cd`` command) to the directory where :ref:`django-admin.py - ` is installed, then run the command + ` is installed, then run the command ``chmod +x django-admin.py``. .. note:: @@ -90,14 +90,14 @@ These files are: * :file:`__init__.py`: An empty file that tells Python that this directory should be considered a Python package. (Read `more about packages`_ in the official Python docs if you're a Python beginner.) - + * :file:`manage.py`: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about :file:`manage.py` in :ref:`ref-django-admin`. - + * :file:`settings.py`: Settings/configuration for this Django project. :ref:`topics-settings` will tell you all about how settings work. - + * :file:`urls.py`: The URL declarations for this Django project; a "table of contents" of your Django-powered site. You can read more about URLs in :ref:`topics-http-urls`. @@ -134,22 +134,22 @@ It worked! .. admonition:: Changing the port By default, the :djadmin:`runserver` command starts the development server - on the internal IP at port 8000. - + on the internal IP at port 8000. + If you want to change the server's port, pass it as a command-line argument. For instance, this command starts the server on port 8080: - + .. code-block:: bash python manage.py runserver 8080 - + If you want to change the server's IP, pass it along with the port. So to listen on all public IPs (useful if you want to show off your work on other computers), use: - + .. code-block:: bash - + python manage.py runserver 0.0.0.0:8000 Full docs for the development server can be found in the @@ -164,21 +164,21 @@ database's connection parameters: * :setting:`DATABASE_ENGINE` -- Either 'postgresql_psycopg2', 'mysql' or 'sqlite3'. Other backends are :setting:`also available `. - + * :setting:`DATABASE_NAME` -- The name of your database. If you're using SQLite, the database will be a file on your computer; in that case, ``DATABASE_NAME`` should be the full absolute path, including filename, of that file. If the file doesn't exist, it will automatically be created when you synchronize the database for the first time (see below). - - When specifying the path, always use forward slashes, even on Windows + + When specifying the path, always use forward slashes, even on Windows (e.g. ``C:/homes/user/mysite/sqlite3.db``). - + * :setting:`DATABASE_USER` -- Your database username (not used for SQLite). - + * :setting:`DATABASE_PASSWORD` -- Your database password (not used for SQLite). - + * :setting:`DATABASE_HOST` -- The host your database is on. Leave this as an empty string if your database server is on the same physical machine (not used for SQLite). @@ -594,7 +594,7 @@ your models, not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin. -.. admonition:: Why :meth:`~django.db.models.Model.__unicode__` and not +.. admonition:: Why :meth:`~django.db.models.Model.__unicode__` and not :meth:`~django.db.models.Model.__str__`? If you're familiar with Python, you might be in the habit of adding diff --git a/docs/intro/tutorial02.txt b/docs/intro/tutorial02.txt index fa1912213a..203c945c02 100644 --- a/docs/intro/tutorial02.txt +++ b/docs/intro/tutorial02.txt @@ -86,8 +86,8 @@ Enter the admin site ==================== Now, try logging in. (You created a superuser account in the first part of this -tutorial, remember? If you didn't create one or forgot the password you can -:ref:`create another one `.) You should see +tutorial, remember? If you didn't create one or forgot the password you can +:ref:`create another one `.) You should see the Django admin index page: .. image:: _images/admin02t.png @@ -238,8 +238,8 @@ the admin page doesn't display choices. Yet. -There are two ways to solve this problem. The first register ``Choice`` with the -admin just as we did with ``Poll``. That's easy:: +There are two ways to solve this problem. The first is to register ``Choice`` +with the admin just as we did with ``Poll``. That's easy:: from mysite.polls.models import Choice diff --git a/docs/intro/tutorial03.txt b/docs/intro/tutorial03.txt index 867b7d1224..77c54c2e43 100644 --- a/docs/intro/tutorial03.txt +++ b/docs/intro/tutorial03.txt @@ -71,7 +71,7 @@ For more on :class:`~django.http.HttpRequest` objects, see the :ref:`ref-request-response`. For more details on URLconfs, see the :ref:`topics-http-urls`. -When you ran ``python django-admin.py startproject mysite`` at the beginning of +When you ran ``django-admin.py startproject mysite`` at the beginning of Tutorial 1, it created a default URLconf in ``mysite/urls.py``. It also automatically set your :setting:`ROOT_URLCONF` setting (in ``settings.py``) to point at that file:: @@ -98,8 +98,7 @@ This is worth a review. When somebody requests a page from your Web site -- say, the :setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns`` and traverses the regular expressions in order. When it finds a regular expression that matches -- ``r'^polls/(?P\d+)/$'`` -- it loads the -associated Python package/module: ``mysite.polls.views.detail``. That -corresponds to the function ``detail()`` in ``mysite/polls/views.py``. Finally, +function ``detail()`` from ``mysite/polls/views.py``. Finally, it calls that ``detail()`` function like so:: detail(request=, poll_id='23') @@ -486,7 +485,8 @@ Here's what happens if a user goes to "/polls/34/" in this system: further processing. Now that we've decoupled that, we need to decouple the 'mysite.polls.urls' -URLconf by removing the leading "polls/" from each line:: +URLconf by removing the leading "polls/" from each line, and removing the +lines registering the admin site:: urlpatterns = patterns('mysite.polls.views', (r'^$', 'index'), diff --git a/docs/ref/contrib/contenttypes.txt b/docs/ref/contrib/contenttypes.txt index f814eccaab..94900b3892 100644 --- a/docs/ref/contrib/contenttypes.txt +++ b/docs/ref/contrib/contenttypes.txt @@ -347,8 +347,8 @@ doesn't work with a :class:`~django.contrib.contenttypes.generic.GenericRelation`. For example, you might be tempted to try something like:: - Bookmark.objects.aggregate(Count('tags')) - + Bookmark.objects.aggregate(Count('tags')) + This will not work correctly, however. The generic relation adds extra filters to the queryset to ensure the correct content type, but the ``aggregate`` method doesn't take them into account. For now, if you need aggregates on generic diff --git a/docs/topics/http/sessions.txt b/docs/topics/http/sessions.txt index fa3864a7c2..d3956504c7 100644 --- a/docs/topics/http/sessions.txt +++ b/docs/topics/http/sessions.txt @@ -4,6 +4,9 @@ How to use sessions =================== +.. module:: django.contrib.sessions + :synopsis: Provides session management for Django projects. + Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. From 3db96017bac70bd53697f5fe5e37362707f7490d Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:32:48 +0000 Subject: [PATCH 42/66] Fixed #11278 -- Clarified query documentation regarding bulk assignment of m2m values. Thanks to zgoda for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11045 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/db/queries.txt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt index 4aa54261c4..34a8b7943a 100644 --- a/docs/topics/db/queries.txt +++ b/docs/topics/db/queries.txt @@ -278,7 +278,7 @@ For example, this returns the first 5 objects (``LIMIT 5``):: This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``):: >>> Entry.objects.all()[5:10] - + Negative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported. Generally, slicing a ``QuerySet`` returns a new ``QuerySet`` -- it doesn't @@ -945,11 +945,17 @@ in the :ref:`related objects reference `. Removes all objects from the related object set. To assign the members of a related set in one fell swoop, just assign to it -from any iterable object. Example:: +from any iterable object. The iterable can contain object instances, or just +a list of primary key values. For Example:: + +Example:: b = Blog.objects.get(id=1) b.entry_set = [e1, e2] +In this example, ``e1`` and ``e2`` can be full Entry instances, or integer +values representing primary keys. + If the ``clear()`` method is available, any pre-existing objects will be removed from the ``entry_set`` before all objects in the iterable (in this case, a list) are added to the set. If the ``clear()`` method is *not* From 7c18404a2499db964343a0b4a6e57b17c2c2b619 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:33:18 +0000 Subject: [PATCH 43/66] Fixed #11312 -- Fixed the default value given for DEFAULT_FILE_STORAGE in the docs. THanks to x00nix@gmail.com for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11046 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/settings.txt | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index 0cca6fe05d..e8c673d995 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -195,7 +195,7 @@ DATABASE_NAME Default: ``''`` (Empty string) The name of the database to use. For SQLite, it's the full path to the database -file. When specifying the path, always use forward slashes, even on Windows +file. When specifying the path, always use forward slashes, even on Windows (e.g. ``C:/homes/user/mysite/sqlite3.db``). .. setting:: DATABASE_OPTIONS @@ -228,7 +228,7 @@ The port to use when connecting to the database. An empty string means the default port. Not used with SQLite. .. setting:: DATABASE_USER - + DATABASE_USER ------------- @@ -251,7 +251,7 @@ See also ``DATETIME_FORMAT``, ``TIME_FORMAT``, ``YEAR_MONTH_FORMAT`` and ``MONTH_DAY_FORMAT``. .. setting:: DATETIME_FORMAT - + DATETIME_FORMAT --------------- @@ -330,7 +330,7 @@ isn't manually specified. Used with ``DEFAULT_CHARSET`` to construct the DEFAULT_FILE_STORAGE -------------------- -Default: ``django.core.files.storage.FileSystemStorage`` +Default: ``'django.core.files.storage.FileSystemStorage'`` Default file storage class to be used for any file-related operations that don't specify a particular storage system. See :ref:`topics-files`. @@ -519,14 +519,14 @@ system's standard umask. .. warning:: **Always prefix the mode with a 0.** - + If you're not familiar with file modes, please note that the leading ``0`` is very important: it indicates an octal number, which is the way that modes must be specified. If you try to use ``644``, you'll get totally incorrect behavior. - -.. _documentation for os.chmod: http://docs.python.org/lib/os-file-dir.html + +.. _documentation for os.chmod: http://docs.python.org/lib/os-file-dir.html .. setting:: FIXTURE_DIRS @@ -1153,7 +1153,7 @@ running in the correct environment. Django cannot reliably use alternate time zones in a Windows environment. If you're running Django on Windows, this variable must be set to match the system timezone. - + .. _See available choices: http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE .. setting:: URL_VALIDATOR_USER_AGENT From 4086167ba6376a974854c698b38627c4df822904 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:33:52 +0000 Subject: [PATCH 44/66] Fixed #11318 -- Grammar correction in modelform docs. Thanks to seemant for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11047 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/forms/modelforms.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index 690ca7f391..8acb3f7646 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -611,7 +611,7 @@ Just like with ``ModelForms``, by default the ``clean()`` method of a the unique constraints on your model (either ``unique``, ``unique_together`` or ``unique_for_date|month|year``). If you want to overide the ``clean()`` method on a ``model_formset`` and maintain this validation, you must call the parent -classes ``clean`` method:: +class's ``clean`` method:: class MyModelFormSet(BaseModelFormSet): def clean(self): From d71097111ae1a5f54c8413be4b9af0c97b8904ef Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:34:27 +0000 Subject: [PATCH 45/66] Fixed #11322 -- Clarified docs regarding middleware processing. Thanks the Michael Malone for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11048 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/http/middleware.txt | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/topics/http/middleware.txt b/docs/topics/http/middleware.txt index 9040533f33..19facb8371 100644 --- a/docs/topics/http/middleware.txt +++ b/docs/topics/http/middleware.txt @@ -107,15 +107,18 @@ middleware is always called on every response. ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the :class:`~django.http. HttpResponse` object returned by a Django view. -``process_response()`` should return an :class:`~django.http. HttpResponse` +``process_response()`` must return an :class:`~django.http. HttpResponse` object. It could alter the given ``response``, or it could create and return a brand-new :class:`~django.http. HttpResponse`. -Remember that your middleware will not be called if another middleware object -returns a response before you. But unlike ``process_request()`` and -``process_view()``, during the response phase the classes are applied in reverse -order, from the bottom up. This means classes defined at the end of -:setting:`MIDDLEWARE_CLASSES` will be run first. +Unlike the ``process_request()`` and ``process_view()`` methods, the +``process_response()`` method is always called, even if the ``process_request()`` +and ``process_view()`` methods of the same middleware class were skipped because +an earlier middleware method returned an :class:`~django.http. HttpResponse` +(this means that your ``process_response()`` method cannot rely on setup done in +``process_request()``, for example). In addition, during the response phase the +classes are applied in reverse order, from the bottom up. This means classes +defined at the end of :setting:`MIDDLEWARE_CLASSES` will be run first. .. _exception-middleware: From 97fb6cf2b3c1546d1aa08a90a38d146d2b0046ef Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:35:06 +0000 Subject: [PATCH 46/66] Fixed #11141 -- Corrected a code example in the admin docs. Thanks to jodal for the report, and SmileyChris for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11049 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/contrib/admin/index.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index 6719527d2f..bad7dec390 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -347,7 +347,7 @@ A few special cases to note about ``list_display``: birthday = models.DateField() def born_in_fifties(self): - return self.birthday.strftime('%Y')[:3] == 5 + return self.birthday.strftime('%Y')[:3] == '195' born_in_fifties.boolean = True class PersonAdmin(admin.ModelAdmin): From b9d17578406553d9ac8574f90b6444f1897c7b56 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:35:36 +0000 Subject: [PATCH 47/66] Fixed #11119 -- Corrected spelling error in 1.0 porting guide. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11050 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/releases/1.0-porting-guide.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releases/1.0-porting-guide.txt b/docs/releases/1.0-porting-guide.txt index 9a5d487f38..f87da1c8d0 100644 --- a/docs/releases/1.0-porting-guide.txt +++ b/docs/releases/1.0-porting-guide.txt @@ -677,7 +677,7 @@ load_data:: management.call_command('flush', verbosity=0, interactive=False) management.call_command('loaddata', 'test_data', verbosity=0) -Subcommands must now preceed options +Subcommands must now precede options ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``django-admin.py`` and ``manage.py`` now require subcommands to precede From 3894ba853ddf84a5f075ad75de4d0da79b29bafa Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:36:11 +0000 Subject: [PATCH 48/66] Fixed #11253 -- Normalized the way the docs refer to TestCase.assert* methods. Thanks to SmileyChris for the report and patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11051 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/testing.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/topics/testing.txt b/docs/topics/testing.txt index 0410049297..1256a61187 100644 --- a/docs/topics/testing.txt +++ b/docs/topics/testing.txt @@ -139,8 +139,8 @@ In the case of model tests, note that the test runner takes care of creating its own test database. That is, any test that accesses a database -- by creating and saving model instances, for example -- will not affect your production database. However, the database is not refreshed between doctests, -so if your doctest requires a certain state you should consider flushin the -database or loading a fixture. (See the section on fixtures, below, for more +so if your doctest requires a certain state you should consider flushing the +database or loading a fixture. (See the section on fixtures, below, for more on this.) Note that to use this feature, the database user Django is connecting as must have ``CREATE DATABASE`` rights. @@ -1042,7 +1042,7 @@ applications: Asserts that a ``Response`` instance produced the given ``status_code`` and that ``text`` does not appears in the content of the response. -.. method:: assertFormError(response, form, field, errors) +.. method:: TestCase.assertFormError(response, form, field, errors) Asserts that a field on a form raises the provided list of errors when rendered on the form. @@ -1057,19 +1057,19 @@ applications: ``errors`` is an error string, or a list of error strings, that are expected as a result of form validation. -.. method:: assertTemplateUsed(response, template_name) +.. method:: TestCase.assertTemplateUsed(response, template_name) Asserts that the template with the given name was used in rendering the response. The name is a string such as ``'admin/index.html'``. -.. method:: assertTemplateNotUsed(response, template_name) +.. method:: TestCase.assertTemplateNotUsed(response, template_name) Asserts that the template with the given name was *not* used in rendering the response. -.. method:: assertRedirects(response, expected_url, status_code=302, target_status_code=200) +.. method:: TestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200) Asserts that the response return a ``status_code`` redirect status, it redirected to ``expected_url`` (including any GET data), and the final From ee8cc099c08ab4a2376758dbcf20a44e775889d8 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:36:40 +0000 Subject: [PATCH 49/66] Fixed #10978 -- Clarified that the include statement is part of the urlpattern definition. Thanks to swatermasysk for the suggestion. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11052 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/intro/tutorial03.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/intro/tutorial03.txt b/docs/intro/tutorial03.txt index 77c54c2e43..f4ef5f76fe 100644 --- a/docs/intro/tutorial03.txt +++ b/docs/intro/tutorial03.txt @@ -467,7 +467,10 @@ Copy the file ``mysite/urls.py`` to ``mysite/polls/urls.py``. Then, change ``mysite/urls.py`` to remove the poll-specific URLs and insert an :func:`~django.conf.urls.defaults.include`:: - (r'^polls/', include('mysite.polls.urls')), + ... + urlpatterns = patterns('', + (r'^polls/', include('mysite.polls.urls')), + ... :func:`~django.conf.urls.defaults.include`, simply, references another URLconf. Note that the regular expression doesn't have a ``$`` (end-of-string match From 755762e5b9990f7cba74c2af99333637ac5efa29 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:37:10 +0000 Subject: [PATCH 50/66] Fixed #11221 -- Replaced a reference to a non-existent URL with an actual explanation of sequences. Thanks to Rob Hudson for the report, and SmileyChris for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11053 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/django-admin.txt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/ref/django-admin.txt b/docs/ref/django-admin.txt index 71804cf022..f657db20f4 100644 --- a/docs/ref/django-admin.txt +++ b/docs/ref/django-admin.txt @@ -611,7 +611,11 @@ sqlsequencereset Prints the SQL statements for resetting sequences for the given app name(s). -See http://simon.incutio.com/archive/2004/04/21/postgres for more information. +Sequences are indexes used by some database engines to track the next available +number for automatically incremented fields. + +Use this command to generate SQL which will fix cases where a sequence is out +of sync with its automatically incremented field data. startapp ------------------ From b836ed46665c99228f2f4109139296f8e48551d0 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 13:44:26 +0000 Subject: [PATCH 51/66] Made correction to documentation change from [11045]. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11054 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/db/queries.txt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt index 34a8b7943a..5e353b2ec3 100644 --- a/docs/topics/db/queries.txt +++ b/docs/topics/db/queries.txt @@ -946,15 +946,13 @@ in the :ref:`related objects reference `. To assign the members of a related set in one fell swoop, just assign to it from any iterable object. The iterable can contain object instances, or just -a list of primary key values. For Example:: - -Example:: +a list of primary key values. For example:: b = Blog.objects.get(id=1) b.entry_set = [e1, e2] In this example, ``e1`` and ``e2`` can be full Entry instances, or integer -values representing primary keys. +primary key values. If the ``clear()`` method is available, any pre-existing objects will be removed from the ``entry_set`` before all objects in the iterable (in this From 8950a40ceccbdccd5ba5c3f788e5a3a3b7d0638f Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 15:03:17 +0000 Subject: [PATCH 52/66] Fixed #11270 -- Corrected naming conflict in templatetag test. Thanks to steveire for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11067 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- tests/regressiontests/templates/tests.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/regressiontests/templates/tests.py b/tests/regressiontests/templates/tests.py index 953e8faa1a..901ef39796 100644 --- a/tests/regressiontests/templates/tests.py +++ b/tests/regressiontests/templates/tests.py @@ -69,7 +69,7 @@ class SomeException(Exception): class SomeOtherException(Exception): pass - + class ContextStackException(Exception): pass @@ -629,7 +629,7 @@ class Templates(unittest.TestCase): # Logically the same as above, just written with explicit # ifchanged for the day. - 'ifchanged-param04': ('{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days':[{'day':1, 'hours':[1,2,3]},{'day':2, 'hours':[3]},] }, '112323'), + 'ifchanged-param05': ('{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days':[{'day':1, 'hours':[1,2,3]},{'day':2, 'hours':[3]},] }, '112323'), # Test the else clause of ifchanged. 'ifchanged-else01': ('{% for id in ids %}{{ id }}{% ifchanged id %}-first{% else %}-other{% endifchanged %},{% endfor %}', {'ids': [1,1,2,2,2,3]}, '1-first,1-other,2-first,2-other,2-other,3-first,'), From cbbe60c7fc39fa8ff75554bd90104eaad6924bb1 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Thu, 18 Jun 2009 15:04:00 +0000 Subject: [PATCH 53/66] Fixed #11270 -- Modified cache template tag to prevent the creation of very long cache keys. Thanks to 235 for the report and patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11068 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/templatetags/cache.py | 4 +++- tests/regressiontests/templates/tests.py | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/django/templatetags/cache.py b/django/templatetags/cache.py index 9c6ca76854..387dd8721c 100644 --- a/django/templatetags/cache.py +++ b/django/templatetags/cache.py @@ -3,6 +3,7 @@ from django.template import resolve_variable from django.core.cache import cache from django.utils.encoding import force_unicode from django.utils.http import urlquote +from django.utils.hashcompat import md5_constructor register = Library() @@ -23,7 +24,8 @@ class CacheNode(Node): except (ValueError, TypeError): raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time) # Build a unicode key for this fragment and all vary-on's. - cache_key = u':'.join([self.fragment_name] + [urlquote(resolve_variable(var, context)) for var in self.vary_on]) + args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])) + cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest()) value = cache.get(cache_key) if value is None: value = self.nodelist.render(context) diff --git a/tests/regressiontests/templates/tests.py b/tests/regressiontests/templates/tests.py index 901ef39796..9c01b492e3 100644 --- a/tests/regressiontests/templates/tests.py +++ b/tests/regressiontests/templates/tests.py @@ -1014,6 +1014,9 @@ class Templates(unittest.TestCase): # Regression test for #7460. 'cache16': ('{% load cache %}{% cache 1 foo bar %}{% endcache %}', {'foo': 'foo', 'bar': 'with spaces'}, ''), + # Regression test for #11270. + 'cache17': ('{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}', {'poem': 'Oh freddled gruntbuggly/Thy micturations are to me/As plurdled gabbleblotchits/On a lurgid bee/That mordiously hath bitled out/Its earted jurtles/Into a rancid festering/Or else I shall rend thee in the gobberwarts with my blurglecruncheon/See if I dont.'}, 'Some Content'), + ### AUTOESCAPE TAG ############################################## 'autoescape-tag01': ("{% autoescape off %}hello{% endautoescape %}", {}, "hello"), 'autoescape-tag02': ("{% autoescape off %}{{ first }}{% endautoescape %}", {"first": "hello"}, "hello"), From b69dc5206cce20926d989c21a290c8eef13bee35 Mon Sep 17 00:00:00 2001 From: Karen Tracey Date: Fri, 19 Jun 2009 01:36:56 +0000 Subject: [PATCH 54/66] Fixed #11344 -- Made a couple of minor clarifications to the mod_wsgi deployment doc. Thanks nartzpod and achew22. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11079 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/howto/deployment/modwsgi.txt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/howto/deployment/modwsgi.txt b/docs/howto/deployment/modwsgi.txt index c35fba3183..902e312551 100644 --- a/docs/howto/deployment/modwsgi.txt +++ b/docs/howto/deployment/modwsgi.txt @@ -51,8 +51,9 @@ If your project is not on your ``PYTHONPATH`` by default you can add:: sys.path.append('/usr/local/django') -just above the ``import`` line to place your project on the path. Remember to -replace 'mysite.settings' with your correct settings file. +just above the final ``import`` line to place your project on the path. Remember to +replace 'mysite.settings' with your correct settings file, and '/usr/local/django' +with your own project's location. See the :ref:`Apache/mod_python documentation` for directions on serving static media, and the `mod_wsgi documentation`_ for an @@ -65,4 +66,4 @@ For more details, see the `mod_wsgi documentation`_, which explains the above in more detail, and walks through all the various options you've got when deploying under mod_wsgi. -.. _mod_wsgi documentation: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango \ No newline at end of file +.. _mod_wsgi documentation: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango From 18b29c523bdd78531810e98c02f9f2a9c3508f7b Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 24 Jun 2009 14:00:53 +0000 Subject: [PATCH 55/66] Fixed #11356 -- Added links to the growing collection of 3rd party database backends that are available. Thank to Nathan Auch for the draft text. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11093 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/databases.txt | 35 ++++++++++++++++++++++++++++++----- docs/topics/install.txt | 35 ++++++++++++++++++++++++++++------- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/docs/ref/databases.txt b/docs/ref/databases.txt index 76a4159235..9a35b6cb8f 100644 --- a/docs/ref/databases.txt +++ b/docs/ref/databases.txt @@ -251,7 +251,7 @@ Here's a sample configuration which uses a MySQL option file:: DATABASE_OPTIONS = { 'read_default_file': '/path/to/my.cnf', } - + # my.cnf [client] database = DATABASE_NAME @@ -445,10 +445,10 @@ If you're getting this error, you can solve it by: * Switching to another database backend. At a certain point SQLite becomes too "lite" for real-world applications, and these sorts of concurrency errors indicate you've reached that point. - - * Rewriting your code to reduce concurrency and ensure that database + + * Rewriting your code to reduce concurrency and ensure that database transactions are short-lived. - + * Increase the default timeout value by setting the ``timeout`` database option option:: @@ -457,7 +457,7 @@ If you're getting this error, you can solve it by: "timeout": 20, # ... } - + This will simply make SQLite wait a bit longer before throwing "database is locked" errors; it won't really do anything to solve them. @@ -601,3 +601,28 @@ some limitations on the usage of such LOB columns in general: Oracle. A workaround to this is to keep ``TextField`` columns out of any models that you foresee performing ``distinct()`` queries on, and to include the ``TextField`` in a related model instead. + +.. _third-party-notes: + +Using a 3rd-party database backend +================================== + +In addition to the officially supported databases, there are backends provided +by 3rd parties that allow you to use other databases with Django: + +* `Sybase SQL Anywhere`_ +* `IBM DB2`_ +* `Microsoft SQL Server 2005`_ +* Firebird_ +* ODBC_ + +The Django versions and ORM features supported by these unofficial backends +vary considerably. Queries regarding the specific capabilities of these +unofficial backends, along with any support queries, should be directed to +the support channels provided by each 3rd party project. + +.. _Sybase SQL Anywhere: http://code.google.com/p/sqlany-django/ +.. _IBM DB2: http://code.google.com/p/ibm-db/ +.. _Microsoft SQL Server 2005: http://code.google.com/p/django-mssql/ +.. _Firebird: http://code.google.com/p/django-firebird/ +.. _ODBC: http://code.google.com/p/django-pyodbc/ diff --git a/docs/topics/install.txt b/docs/topics/install.txt index 4268759828..b66c8aef15 100644 --- a/docs/topics/install.txt +++ b/docs/topics/install.txt @@ -61,13 +61,27 @@ for each platform. Get your database running ========================= -If you plan to use Django's database API functionality, you'll need to -make sure a database server is running. Django works with PostgreSQL_, -MySQL_, Oracle_ and SQLite_ (although SQLite doesn't require a separate server -to be running). +If you plan to use Django's database API functionality, you'll need to make +sure a database server is running. Django supports many different database +servers and is officially supported with PostgreSQL_, MySQL_, Oracle_ and +SQLite_ (although SQLite doesn't require a separate server to be running). -Additionally, you'll need to make sure your Python database bindings are -installed. +In addition to the officially supported databases, there are backends provided +by 3rd parties that allow you to use other databases with Django: + +* `Sybase SQL Anywhere`_ +* `IBM DB2`_ +* `Microsoft SQL Server 2005`_ +* Firebird_ +* ODBC_ + +The Django versions and ORM features supported by these unofficial backends +vary considerably. Queries regarding the specific capabilities of these +unofficial backends, along with any support queries, should be directed to the +support channels provided by each 3rd party project. + +In addition to a database backend, you'll need to make sure your Python +database bindings are installed. * If you're using PostgreSQL, you'll need the psycopg_ package. Django supports both version 1 and 2. (When you configure Django's database layer, specify @@ -89,6 +103,9 @@ installed. :ref:`Oracle backend ` for important information regarding supported versions of both Oracle and ``cx_Oracle``. +* If you're using an unofficial 3rd party backend, please consult the + documentation provided for any additional requirements. + If you plan to use Django's ``manage.py syncdb`` command to automatically create database tables for your models, you'll need to ensure that Django has permission to create and alter tables in the @@ -111,7 +128,11 @@ Django will need permission to create a test database. .. _pysqlite: http://pysqlite.org/ .. _cx_Oracle: http://cx-oracle.sourceforge.net/ .. _Oracle: http://www.oracle.com/ - +.. _Sybase SQL Anywhere: http://code.google.com/p/sqlany-django/ +.. _IBM DB2: http://code.google.com/p/ibm-db/ +.. _Microsoft SQL Server 2005: http://code.google.com/p/django-mssql/ +.. _Firebird: http://code.google.com/p/django-firebird/ +.. _ODBC: http://code.google.com/p/django-pyodbc/ .. _removing-old-versions-of-django: Remove any old versions of Django From bbd7b64e7606534716be15d31a23f2b081f018ff Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 24 Jun 2009 14:01:36 +0000 Subject: [PATCH 56/66] Fixed #11354 -- Remove stray whitespace in queryset docs. Thanks to flebel for the report. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11094 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/models/querysets.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index eb8fbfd833..348486b341 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -35,7 +35,7 @@ You can evaluate a ``QuerySet`` in the following ways: * **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can be sliced, using Python's array-slicing syntax. Usually slicing a - ``QuerySet`` returns another (unevaluated ) ``QuerySet``, but Django will + ``QuerySet`` returns another (unevaluated) ``QuerySet``, but Django will execute the database query if you use the "step" parameter of slice syntax. From 4acf7f43e79d1781462b4035b871446dd8c58cf4 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 24 Jun 2009 14:02:22 +0000 Subject: [PATCH 57/66] Fixed #10415 -- Added documentation for features added in r7627 and r7630; extensibility points for the ModelAdmin and AdminSite. Thanks to Ramiro Morales for the draft text. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11095 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/contrib/admin/index.txt | 108 ++++++++++++++++++++++++++++++- 1 file changed, 105 insertions(+), 3 deletions(-) diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index bad7dec390..ec8b358974 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -667,6 +667,43 @@ Controls where on the page the actions bar appears. By default, the admin changelist displays actions at the top of the page (``actions_on_top = True; actions_on_bottom = False``). +.. attribute:: ModelAdmin.change_list_template + +Path to a custom template that will be used by the model objects "change list" +view. Templates can override or extend base admin templates as described in +`Overriding Admin Templates`_. + +If you don't specify this attribute, a default template shipped with Django +that provides the standard appearance is used. + +.. attribute:: ModelAdmin.change_form_template + +Path to a custom template that will be used by both the model object creation +and change views. Templates can override or extend base admin templates as +described in `Overriding Admin Templates`_. + +If you don't specify this attribute, a default template shipped with Django +that provides the standard appearance is used. + +.. attribute:: ModelAdmin.object_history_template + +Path to a custom template that will be used by the model object change history +display view. Templates can override or extend base admin templates as +described in `Overriding Admin Templates`_. + +If you don't specify this attribute, a default template shipped with Django +that provides the standard appearance is used. + +.. attribute:: ModelAdmin.delete_confirmation_template + +Path to a custom template that will be used by the view responsible of showing +the confirmation page when the user decides to delete one or more model +objects. Templates can override or extend base admin templates as described in +`Overriding Admin Templates`_. + +If you don't specify this attribute, a default template shipped with Django +that provides the standard appearance is used. + ``ModelAdmin`` methods ---------------------- @@ -762,6 +799,56 @@ return a subset of objects for this foreign key field based on the user:: This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key field to only the cars owned by the ``User`` instance. +Other methods +~~~~~~~~~~~~~ + +.. method:: ModelAdmin.add_view(self, request, form_url='', extra_context=None) + +Django view for the model instance addition page. See note below. + +.. method:: ModelAdmin.change_view(self, request, object_id, extra_context=None) + +Django view for the model instance edition page. See note below. + +.. method:: ModelAdmin.changelist_view(self, request, extra_context=None) + +Django view for the model instances change list/actions page. See note below. + +.. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None) + +Django view for the model instance(s) deletion confirmation page. See note below. + +.. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None) + +Django view for the page that shows the modification history for a given model +instance. + +Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section, +these five methods are in reality designed to be invoked as Django views from +the admin application URL dispatching handler to render the pages that deal +with model instances CRUD operations. As a result, completely overriding these +methods will significantly change the behavior of the admin application. + +One comon reason for overriding these methods is to augment the context data +that is provided to the template that renders the view. In the following +example, the change view is overridden so that the rendered template is +provided some extra mapping data that would not otherwise be available:: + + class MyModelAdmin(admin.ModelAdmin): + + # A template for a very customized change view: + change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html' + + def get_osm_info(self): + # ... + + def change_view(self, request, object_id, extra_context=None): + my_context = { + 'osm_data': self.get_osm_info(), + } + return super(MyModelAdmin, self).change_view(request, object_id, + extra_context=my_context)) + ``ModelAdmin`` media definitions -------------------------------- @@ -1106,7 +1193,7 @@ directory, our link would appear on every model's change form. Templates which may be overridden per app or model -------------------------------------------------- -Not every template in ``contrib\admin\templates\admin`` may be overridden per +Not every template in ``contrib/admin/templates/admin`` may be overridden per app or per model. The following can: * ``app_index.html`` @@ -1131,8 +1218,8 @@ Root and login templates ------------------------ If you wish to change the index or login templates, you are better off creating -your own ``AdminSite`` instance (see below), and changing the ``index_template`` -or ``login_template`` properties. +your own ``AdminSite`` instance (see below), and changing the :attr:`AdminSite.index_template` +or :attr:`AdminSite.login_template` properties. ``AdminSite`` objects ===================== @@ -1151,6 +1238,21 @@ or add anything you like. Then, simply create an instance of your Python class), and register your models and ``ModelAdmin`` subclasses with it instead of using the default. +``AdminSite`` attributes +------------------------ + +.. attribute:: AdminSite.index_template + +Path to a custom template that will be used by the admin site main index view. +Templates can override or extend base admin templates as described in +`Overriding Admin Templates`_. + +.. attribute:: AdminSite.login_template + +Path to a custom template that will be used by the admin site login view. +Templates can override or extend base admin templates as described in +`Overriding Admin Templates`_. + Hooking ``AdminSite`` instances into your URLconf ------------------------------------------------- From 78eb620c639b5bd2d91d8e02ecb61c8eb9d9a80a Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 24 Jun 2009 14:03:10 +0000 Subject: [PATCH 58/66] Fixed #11327 -- Added missing prefix in HTML id in admin-docs. Prefix originally added in r10343, but missed the second usage. Thanks to Nathan for the report and patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11096 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/admindocs/templates/admin_doc/model_index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/django/contrib/admindocs/templates/admin_doc/model_index.html b/django/contrib/admindocs/templates/admin_doc/model_index.html index 4dd7caa2a6..47c94c0c70 100644 --- a/django/contrib/admindocs/templates/admin_doc/model_index.html +++ b/django/contrib/admindocs/templates/admin_doc/model_index.html @@ -36,7 +36,7 @@ From 970be97530e5eef5c872462e065be630c183847d Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Wed, 24 Jun 2009 14:04:18 +0000 Subject: [PATCH 59/66] Fixed #8861 -- Added note on the availability of ModelForm.instance. Thanks to Ramiro Morales for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11097 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/ref/contrib/admin/index.txt | 6 ++++-- docs/topics/forms/modelforms.txt | 20 +++++++++++++++----- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index ec8b358974..64d9c52492 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -870,7 +870,7 @@ Adding custom validation to the admin ------------------------------------- Adding custom validation of data in the admin is quite easy. The automatic admin -interfaces reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you +interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you the ability define your own form:: class ArticleAdmin(admin.ModelAdmin): @@ -890,7 +890,9 @@ any field:: It is important you use a ``ModelForm`` here otherwise things can break. See the :ref:`forms ` documentation on :ref:`custom validation -` for more information. +` and, more specifically, the +:ref:`model form validation notes ` for more +information. .. _admin-inlines: diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index 8acb3f7646..add581268b 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -397,16 +397,26 @@ to be rendered first, we could specify the following ``ModelForm``:: ... model = Book ... fields = ['title', 'author'] +.. _overriding-modelform-clean-method: Overriding the clean() method ----------------------------- You can override the ``clean()`` method on a model form to provide additional -validation in the same way you can on a normal form. However, by default the -``clean()`` method validates the uniqueness of fields that are marked as -``unique``, ``unique_together`` or ``unique_for_date|month|year`` on the model. -Therefore, if you would like to override the ``clean()`` method and maintain the -default validation, you must call the parent class's ``clean()`` method. +validation in the same way you can on a normal form. + +In this regard, model forms have two specific characteristics when compared to +forms: + +By default the ``clean()`` method validates the uniqueness of fields that are +marked as ``unique``, ``unique_together`` or ``unique_for_date|month|year`` on +the model. Therefore, if you would like to override the ``clean()`` method and +maintain the default validation, you must call the parent class's ``clean()`` +method. + +Also, a model form instance bound to a model object will contain a +``self.instance`` attribute that gives model form methods access to that +specific model instance. Form inheritance ---------------- From fe2747d1e01cc07ed08dd3193693aa6206120afd Mon Sep 17 00:00:00 2001 From: Karen Tracey Date: Wed, 24 Jun 2009 23:33:17 +0000 Subject: [PATCH 60/66] Fixed #10741: Updated instructions on the best gettext package to get for Windows. Thanks Ramiro. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11103 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/topics/i18n.txt | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/topics/i18n.txt b/docs/topics/i18n.txt index 140adce74c..86c03221aa 100644 --- a/docs/topics/i18n.txt +++ b/docs/topics/i18n.txt @@ -978,15 +978,17 @@ message files (``.po``). Translation work itself just involves editing existing files of this type, but if you want to create your own message files, or want to test or compile a changed message file, you will need the ``gettext`` utilities: - * Download the following zip files from - http://sourceforge.net/projects/gettext + * Download the following zip files from the GNOME servers + http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/ or from one + of its mirrors_ - * ``gettext-runtime-X.bin.woe32.zip`` - * ``gettext-tools-X.bin.woe32.zip`` - * ``libiconv-X.bin.woe32.zip`` + * ``gettext-runtime-X.zip`` + * ``gettext-tools-X.zip`` - * Extract the 3 files in the same folder (i.e. ``C:\Program - Files\gettext-utils``) + ``X`` is the version number, we recomend using ``0.15`` or higher. + + * Extract the contents of the ``bin\`` directories in both files to the + same folder on your system (i.e. ``C:\Program Files\gettext-utils``) * Update the system PATH: @@ -995,6 +997,8 @@ test or compile a changed message file, you will need the ``gettext`` utilities: * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the ``Variable value`` field +.. _mirrors: http://ftp.gnome.org/pub/GNOME/MIRRORS + You may also use ``gettext`` binaries you have obtained elsewhere, so long as the ``xgettext --version`` command works properly. Some version 0.14.4 binaries have been found to not support this command. Do not attempt to use Django From e522e61a80aa9faae3fc0bcd69fd99d6b4951326 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Mon, 29 Jun 2009 12:29:48 +0000 Subject: [PATCH 61/66] Fixed #11392 -- Enforced a predictable result order for a couple of test cases. Thanks to Nathan Auch for the report and patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11119 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- tests/modeltests/transactions/models.py | 3 +++ tests/regressiontests/null_fk/models.py | 3 +++ tests/regressiontests/serializers_regress/tests.py | 4 ++-- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/modeltests/transactions/models.py b/tests/modeltests/transactions/models.py index 06d21bbdd4..6763144ca5 100644 --- a/tests/modeltests/transactions/models.py +++ b/tests/modeltests/transactions/models.py @@ -14,6 +14,9 @@ class Reporter(models.Model): last_name = models.CharField(max_length=30) email = models.EmailField() + class Meta: + ordering = ('first_name', 'last_name') + def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name) diff --git a/tests/regressiontests/null_fk/models.py b/tests/regressiontests/null_fk/models.py index 529dde5039..49887819ac 100644 --- a/tests/regressiontests/null_fk/models.py +++ b/tests/regressiontests/null_fk/models.py @@ -22,6 +22,9 @@ class Comment(models.Model): post = models.ForeignKey(Post, null=True) comment_text = models.CharField(max_length=250) + class Meta: + ordering = ('comment_text',) + def __unicode__(self): return self.comment_text diff --git a/tests/regressiontests/serializers_regress/tests.py b/tests/regressiontests/serializers_regress/tests.py index 4e52d81811..de7ddcc9f7 100644 --- a/tests/regressiontests/serializers_regress/tests.py +++ b/tests/regressiontests/serializers_regress/tests.py @@ -103,7 +103,7 @@ def data_compare(testcase, pk, klass, data): def generic_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data[0], instance.data) - testcase.assertEqual(data[1:], [t.data for t in instance.tags.all()]) + testcase.assertEqual(data[1:], [t.data for t in instance.tags.order_by('id')]) def fk_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) @@ -111,7 +111,7 @@ def fk_compare(testcase, pk, klass, data): def m2m_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) - testcase.assertEqual(data, [obj.id for obj in instance.data.all()]) + testcase.assertEqual(data, [obj.id for obj in instance.data.order_by('id')]) def im2m_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) From 735309341e24d53d5af41799a31aa964f424190c Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Mon, 29 Jun 2009 14:02:17 +0000 Subject: [PATCH 62/66] Fixed #10834 -- Added bucket condition to ensure that URL resolvers won't ever return None. Thanks to Chris Cahoon for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11120 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/urlresolvers.py | 1 + .../urlpatterns_reverse/tests.py | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py index ac83756f31..b3dcfdb8c1 100644 --- a/django/core/urlresolvers.py +++ b/django/core/urlresolvers.py @@ -195,6 +195,7 @@ class RegexURLResolver(object): return sub_match[0], sub_match[1], sub_match_dict tried.append(pattern.regex.pattern) raise Resolver404, {'tried': tried, 'path': new_path} + raise Resolver404, {'tried': [], 'path' : path} def _get_urlconf_module(self): try: diff --git a/tests/regressiontests/urlpatterns_reverse/tests.py b/tests/regressiontests/urlpatterns_reverse/tests.py index a7283d43bb..9def6b2eb2 100644 --- a/tests/regressiontests/urlpatterns_reverse/tests.py +++ b/tests/regressiontests/urlpatterns_reverse/tests.py @@ -14,8 +14,9 @@ Traceback (most recent call last): ImproperlyConfigured: The included urlconf regressiontests.urlpatterns_reverse.no_urls doesn't have any patterns in it """} +import unittest -from django.core.urlresolvers import reverse, NoReverseMatch +from django.core.urlresolvers import reverse, resolve, NoReverseMatch, Resolver404 from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.shortcuts import redirect from django.test import TestCase @@ -112,6 +113,21 @@ class URLPatternReverse(TestCase): else: self.assertEquals(got, expected) +class ResolverTests(unittest.TestCase): + def test_non_regex(self): + """ + Verifies that we raise a Resolver404 if what we are resolving doesn't + meet the basic requirements of a path to match - i.e., at the very + least, it matches the root pattern '^/'. We must never return None + from resolve, or we will get a TypeError further down the line. + + Regression for #10834. + """ + self.assertRaises(Resolver404, resolve, '') + self.assertRaises(Resolver404, resolve, 'a') + self.assertRaises(Resolver404, resolve, '\\') + self.assertRaises(Resolver404, resolve, '.') + class ReverseShortcutTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.urls' From fdcc0c774a9295f5d0fa3a1edd34e4f7e41476d5 Mon Sep 17 00:00:00 2001 From: Justin Bronn Date: Mon, 29 Jun 2009 16:31:21 +0000 Subject: [PATCH 63/66] Fixed #11381 -- `GeoManager` + `select_related` + nullable `ForeignKey` now works correctly. Thanks, bretthoerner for ticket and dgouldin for initial patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11123 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/db/models/sql/query.py | 2 +- django/contrib/gis/tests/relatedapp/models.py | 2 +- django/contrib/gis/tests/relatedapp/tests.py | 7 +++++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/django/contrib/gis/db/models/sql/query.py b/django/contrib/gis/db/models/sql/query.py index cf1ccf6483..5df15a88b1 100644 --- a/django/contrib/gis/db/models/sql/query.py +++ b/django/contrib/gis/db/models/sql/query.py @@ -225,7 +225,7 @@ class GeoQuery(sql.Query): values.append(self.convert_values(value, field)) else: values.extend(row[index_start:]) - return values + return tuple(values) def convert_values(self, value, field): """ diff --git a/django/contrib/gis/tests/relatedapp/models.py b/django/contrib/gis/tests/relatedapp/models.py index 1125d7fb85..726f9826c0 100644 --- a/django/contrib/gis/tests/relatedapp/models.py +++ b/django/contrib/gis/tests/relatedapp/models.py @@ -40,5 +40,5 @@ class Author(models.Model): class Book(models.Model): title = models.CharField(max_length=100) - author = models.ForeignKey(Author, related_name='books') + author = models.ForeignKey(Author, related_name='books', null=True) objects = models.GeoManager() diff --git a/django/contrib/gis/tests/relatedapp/tests.py b/django/contrib/gis/tests/relatedapp/tests.py index 8c4f83b15a..502a3c0be9 100644 --- a/django/contrib/gis/tests/relatedapp/tests.py +++ b/django/contrib/gis/tests/relatedapp/tests.py @@ -257,6 +257,13 @@ class RelatedGeoModelTest(unittest.TestCase): self.assertEqual(1, len(qs)) self.assertEqual(3, qs[0].num_books) + def test13_select_related_null_fk(self): + "Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381." + no_author = Book.objects.create(title='Without Author') + b = Book.objects.select_related('author').get(title='Without Author') + # Should be `None`, and not a 'dummy' model. + self.assertEqual(None, b.author) + # TODO: Related tests for KML, GML, and distance lookups. def suite(): From cb9cf01ff292cc6e6b8489258d1c59a6e8631d52 Mon Sep 17 00:00:00 2001 From: Justin Bronn Date: Mon, 29 Jun 2009 17:17:45 +0000 Subject: [PATCH 64/66] Fixed #11249, #11261 -- Blocks may now be overridden again `google-map.js` template; now use GMaps `setUIToDefault` to use default controls. Thanks to ludifan and Peter Landry for the ttickets and patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11124 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/maps/google/gmap.py | 4 ++-- .../contrib/gis/templates/gis/google/google-base.js | 7 ------- .../contrib/gis/templates/gis/google/google-map.js | 12 +++++++++--- .../contrib/gis/templates/gis/google/google-multi.js | 2 +- .../gis/templates/gis/google/google-single.js | 4 ++-- 5 files changed, 14 insertions(+), 15 deletions(-) delete mode 100644 django/contrib/gis/templates/gis/google/google-base.js diff --git a/django/contrib/gis/maps/google/gmap.py b/django/contrib/gis/maps/google/gmap.py index de8f75c5a0..cca5dc941f 100644 --- a/django/contrib/gis/maps/google/gmap.py +++ b/django/contrib/gis/maps/google/gmap.py @@ -21,7 +21,7 @@ class GoogleMap(object): def __init__(self, key=None, api_url=None, version=None, center=None, zoom=None, dom_id='map', kml_urls=[], polylines=None, polygons=None, markers=None, - template='gis/google/google-single.js', + template='gis/google/google-map.js', js_module='geodjango', extra_context={}): @@ -162,7 +162,7 @@ class GoogleMapSet(GoogleMap): # This is the template used to generate the GMap load JavaScript for # each map in the set. - self.map_template = kwargs.pop('map_template', 'gis/google/google-map.js') + self.map_template = kwargs.pop('map_template', 'gis/google/google-single.js') # Running GoogleMap.__init__(), and resetting the template # value with default obtained above. diff --git a/django/contrib/gis/templates/gis/google/google-base.js b/django/contrib/gis/templates/gis/google/google-base.js deleted file mode 100644 index f3a91edbc4..0000000000 --- a/django/contrib/gis/templates/gis/google/google-base.js +++ /dev/null @@ -1,7 +0,0 @@ -{% block vars %}var geodjango = {};{% for icon in icons %} -var {{ icon.varname }} = new GIcon(G_DEFAULT_ICON); -{% if icon.image %}{{ icon.varname }}.image = "{{ icon.image }}";{% endif %} -{% if icon.shadow %}{{ icon.varname }}.shadow = "{{ icon.shadow }}";{% endif %} {% if icon.shadowsize %}{{ icon.varname }}.shadowSize = new GSize({{ icon.shadowsize.0 }}, {{ icon.shadowsize.1 }});{% endif %} -{% if icon.iconanchor %}{{ icon.varname }}.iconAnchor = new GPoint({{ icon.iconanchor.0 }}, {{ icon.iconanchor.1 }});{% endif %} {% if icon.iconsize %}{{ icon.varname }}.iconSize = new GSize({{ icon.iconsize.0 }}, {{ icon.iconsize.1 }});{% endif %} -{% if icon.infowindowanchor %}{{ icon.varname }}.infoWindowAnchor = new GPoint({{ icon.infowindowanchor.0 }}, {{ icon.infowindowanchor.1 }});{% endif %}{% endfor %}{% endblock %} -{% block functions %}{% endblock %} \ No newline at end of file diff --git a/django/contrib/gis/templates/gis/google/google-map.js b/django/contrib/gis/templates/gis/google/google-map.js index e5f3a0e0e3..06f11e35f3 100644 --- a/django/contrib/gis/templates/gis/google/google-map.js +++ b/django/contrib/gis/templates/gis/google/google-map.js @@ -1,10 +1,16 @@ {% autoescape off %} +{% block vars %}var geodjango = {};{% for icon in icons %} +var {{ icon.varname }} = new GIcon(G_DEFAULT_ICON); +{% if icon.image %}{{ icon.varname }}.image = "{{ icon.image }}";{% endif %} +{% if icon.shadow %}{{ icon.varname }}.shadow = "{{ icon.shadow }}";{% endif %} {% if icon.shadowsize %}{{ icon.varname }}.shadowSize = new GSize({{ icon.shadowsize.0 }}, {{ icon.shadowsize.1 }});{% endif %} +{% if icon.iconanchor %}{{ icon.varname }}.iconAnchor = new GPoint({{ icon.iconanchor.0 }}, {{ icon.iconanchor.1 }});{% endif %} {% if icon.iconsize %}{{ icon.varname }}.iconSize = new GSize({{ icon.iconsize.0 }}, {{ icon.iconsize.1 }});{% endif %} +{% if icon.infowindowanchor %}{{ icon.varname }}.infoWindowAnchor = new GPoint({{ icon.infowindowanchor.0 }}, {{ icon.infowindowanchor.1 }});{% endif %}{% endfor %} +{% endblock vars %}{% block functions %} {% block load %}{{ js_module }}.{{ dom_id }}_load = function(){ if (GBrowserIsCompatible()) { {{ js_module }}.{{ dom_id }} = new GMap2(document.getElementById("{{ dom_id }}")); {{ js_module }}.{{ dom_id }}.setCenter(new GLatLng({{ center.1 }}, {{ center.0 }}), {{ zoom }}); - {% block controls %}{{ js_module }}.{{ dom_id }}.addControl(new GSmallMapControl()); - {{ js_module }}.{{ dom_id }}.addControl(new GMapTypeControl());{% endblock %} + {% block controls %}{{ js_module }}.{{ dom_id }}.setUIToDefault();{% endblock %} {% if calc_zoom %}var bounds = new GLatLngBounds(); var tmp_bounds = new GLatLngBounds();{% endif %} {% for kml_url in kml_urls %}{{ js_module }}.{{ dom_id }}_kml{{ forloop.counter }} = new GGeoXml("{{ kml_url }}"); {{ js_module }}.{{ dom_id }}.addOverlay({{ js_module }}.{{ dom_id }}_kml{{ forloop.counter }});{% endfor %} @@ -26,4 +32,4 @@ alert("Sorry, the Google Maps API is not compatible with this browser."); } } -{% endblock %}{% endautoescape %} +{% endblock load %}{% endblock functions %}{% endautoescape %} diff --git a/django/contrib/gis/templates/gis/google/google-multi.js b/django/contrib/gis/templates/gis/google/google-multi.js index 49ce584e36..e3c7e8f02b 100644 --- a/django/contrib/gis/templates/gis/google/google-multi.js +++ b/django/contrib/gis/templates/gis/google/google-multi.js @@ -1,4 +1,4 @@ -{% extends "gis/google/google-base.js" %} +{% extends "gis/google/google-map.js" %} {% block functions %} {{ load_map_js }} {{ js_module }}.load = function(){ diff --git a/django/contrib/gis/templates/gis/google/google-single.js b/django/contrib/gis/templates/gis/google/google-single.js index ab7901e42e..b930e4594f 100644 --- a/django/contrib/gis/templates/gis/google/google-single.js +++ b/django/contrib/gis/templates/gis/google/google-single.js @@ -1,2 +1,2 @@ -{% extends "gis/google/google-base.js" %} -{% block functions %}{% include "gis/google/google-map.js" %}{% endblock %} \ No newline at end of file +{% extends "gis/google/google-map.js" %} +{% block vars %}{# No vars here because used within GoogleMapSet #}{% endblock %} \ No newline at end of file From 422adffa11b57475d871ad2d1e33b04974d68f06 Mon Sep 17 00:00:00 2001 From: Justin Bronn Date: Mon, 29 Jun 2009 17:49:01 +0000 Subject: [PATCH 65/66] Fixed #11401 -- Update geographic admin to use OpenLayers 2.8 as OpenStreetMap does not support previous versions. Thanks, yourcelf for ticket and patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11125 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/gis/admin/options.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/django/contrib/gis/admin/options.py b/django/contrib/gis/admin/options.py index 6a63a9fe78..fff1cb20a6 100644 --- a/django/contrib/gis/admin/options.py +++ b/django/contrib/gis/admin/options.py @@ -32,7 +32,7 @@ class GeoModelAdmin(ModelAdmin): map_height = 400 map_srid = 4326 map_template = 'gis/admin/openlayers.html' - openlayers_url = 'http://openlayers.org/api/2.7/OpenLayers.js' + openlayers_url = 'http://openlayers.org/api/2.8/OpenLayers.js' point_zoom = num_zoom - 6 wms_url = 'http://labs.metacarta.com/wms/vmap0' wms_layer = 'basic' From 923c6755c88f19ad7fc0cd74cf818037f85dfb43 Mon Sep 17 00:00:00 2001 From: James Bennett Date: Tue, 30 Jun 2009 18:40:29 +0000 Subject: [PATCH 66/66] Fixed #11357: contrib.admindocs now correctly displays many-to-many relationships. Thanks to Ben Spaulding for the final version of the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@11127 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/admindocs/views.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py index f66ea3e9b0..4f22fe0a0a 100644 --- a/django/contrib/admindocs/views.py +++ b/django/contrib/admindocs/views.py @@ -214,6 +214,22 @@ def model_detail(request, app_label, model_name): 'help_text': field.help_text, }) + # Gather many-to-many fields. + for field in opts.many_to_many: + data_type = related_object_name = field.rel.to.__name__ + app_label = field.rel.to._meta.app_label + verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': app_label, 'object_name': data_type} + fields.append({ + 'name': "%s.all" % field.name, + "data_type": 'List', + 'verbose': utils.parse_rst(_("all %s") % verbose , 'model', _('model:') + opts.module_name), + }) + fields.append({ + 'name' : "%s.count" % field.name, + 'data_type' : 'Integer', + 'verbose' : utils.parse_rst(_("number of %s") % verbose , 'model', _('model:') + opts.module_name), + }) + # Gather model methods. for func_name, func in model.__dict__.items(): if (inspect.isfunction(func) and len(inspect.getargspec(func)[0]) == 1): @@ -233,7 +249,7 @@ def model_detail(request, app_label, model_name): }) # Gather related objects - for rel in opts.get_all_related_objects(): + for rel in opts.get_all_related_objects() + opts.get_all_related_many_to_many_objects(): verbose = _("related `%(app_label)s.%(object_name)s` objects") % {'app_label': rel.opts.app_label, 'object_name': rel.opts.object_name} accessor = rel.get_accessor_name() fields.append({