We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Order sponsors in their groups
From @andreasneumann: 

```For the sponsors listing - is there a clear order within the same level at http://changelog.qgis.org/en/qgis/version/2.16.0/ ?

In my opinion, it should either be ordered alphabetically or by date. Neither seems to be the case. I would prefer alphabetic ordering with in each sponsorship level.```

I think it is actually better to order them with most recently added sponsors first to oldest sponsors last. That we they get the most visibility when they are new, degrading over time to the bottom of the list. What do you think @andreasneumann ?


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `django_project/changes/models/version.py`
Content:
```
1 # coding=utf-8
2 from django.core.urlresolvers import reverse
3 # from django.utils.text import slugify
4 from common.utilities import version_slugify
5 import os
6 import logging
7 from core.settings.contrib import STOP_WORDS
8 from django.conf.global_settings import MEDIA_ROOT
9 from django.db import models
10 from .entry import Entry
11 from .sponsorship_period import SponsorshipPeriod
12 from django.contrib.auth.models import User
13 from django.utils.translation import ugettext_lazy as _
14 
15 logger = logging.getLogger(__name__)
16 
17 
18 class ApprovedVersionManager(models.Manager):
19     """Custom version manager that shows only approved records."""
20 
21     def get_queryset(self):
22         """Query set generator"""
23         return super(
24             ApprovedVersionManager, self).get_queryset().filter(
25                 approved=True)
26 
27 
28 class UnapprovedVersionManager(models.Manager):
29     """Custom version manager that shows only unapproved records."""
30 
31     def get_queryset(self):
32         """Query set generator"""
33         return super(
34             UnapprovedVersionManager, self).get_queryset().filter(
35                 approved=False)
36 
37 
38 # noinspection PyUnresolvedReferences
39 class Version(models.Model):
40     """A version model that the changelog is associated with.."""
41 
42     name = models.CharField(
43         help_text='Name of this release e.g. 1.0.1.',
44         max_length=255,
45         null=False,
46         blank=False,
47         unique=False)
48 
49     padded_version = models.CharField(
50         help_text=(
51             'Numeric version for this release e.g. 001000001 for 1.0.1 '
52             'calculated by zero padding each component of maj/minor/bugfix '
53             'elements from name.'),
54         max_length=9,
55         null=False,
56         blank=True,
57         unique=False)
58 
59     approved = models.BooleanField(
60         help_text=(
61             'Whether this version has been approved for use by the '
62             'project owner.'),
63         default=False)
64 
65     image_file = models.ImageField(
66         help_text=(
67             'An optional image for this version e.g. a splashscreen. '
68             'Most browsers support dragging the image directly on to the '
69             '"Choose File" button above.'),
70         upload_to=os.path.join(MEDIA_ROOT, 'images/projects'),
71         blank=True)
72 
73     description = models.TextField(
74         null=True,
75         blank=True,
76         help_text='Describe the new version. Markdown is supported.')
77 
78     release_date = models.DateField(
79         _('Release date (yyyy-mm-dd)'),
80         help_text='Date of official release',
81         null=True,
82         blank=True)
83 
84     author = models.ForeignKey(User)
85     slug = models.SlugField()
86     project = models.ForeignKey('base.Project')
87     objects = models.Manager()
88     approved_objects = ApprovedVersionManager()
89     unapproved_objects = UnapprovedVersionManager()
90 
91     # noinspection PyClassicStyleClass
92     class Meta:
93         """Meta options for the version class."""
94         unique_together = (
95             ('name', 'project'),
96             ('slug', 'project'),
97         )
98         app_label = 'changes'
99         # ordering = ['-datetime_created']
100 
101     def save(self, *args, **kwargs):
102         if not self.pk:
103             words = self.name.split()
104             filtered_words = [t for t in words if t.lower() not in STOP_WORDS]
105             new_list = ' '.join(filtered_words)
106             self.slug = version_slugify(new_list)[:50]
107         self.padded_version = self.pad_name(self.name)
108         super(Version, self).save(*args, **kwargs)
109 
110     def pad_name(self, version):
111         """Create a 0 padded version of the version name.
112 
113         e.g. input: 2.10.1
114         e.g. output: 002010100
115 
116         This will ensure we have sortable version names.
117 
118         :param version: A text version in the form 0.0.0 - if the version is
119             not in this form, we return the version unaltered.
120         :type version: str
121 
122         :returns: Zero padded representation of the version e.g. 001010100
123         :rtype: str
124 
125         """
126         tokens = version.split('.')
127         if len(tokens) != 3:
128             return version
129         result = ''
130         for token in tokens:
131             result += token.zfill(3)
132         return result
133 
134     def __unicode__(self):
135         return u'%s : %s' % (self.project.name, self.name)
136 
137     def get_absolute_url(self):
138         return reverse('version-detail', kwargs={
139             'slug': self.slug,
140             'project_slug': self.project.slug
141         })
142 
143     def entries(self):
144         """Get the entries for this version."""
145         qs = Entry.objects.filter(version=self).order_by('category__sort_number')
146         return qs
147 
148     def _entries_for_category(self, category):
149         """All entries for this version and filtered by the given category.
150 
151         :param category: Category to filter by.
152         :type category: Category
153 
154         .. note:: only approved entries returned.
155         """
156         qs = Entry.objects.filter(
157                 version=self,
158                 category=category,
159                 approved=True)
160         return qs
161 
162     def categories(self):
163         """Get a list of categories where there are one or more entries.
164 
165         Example use in template::
166             {% for row in version.categories %}
167               <h2 class="text-muted">{{ row.category.name }}</h2>
168               <ul>
169               {%  for entry in row.entries %}
170                  <li>{{ entry.name }}</li>
171               {% endfor %}
172               </ul>
173             {% endfor %}
174         """
175         qs = self.entries()
176         used = []
177         categories = []
178         for entry in qs:
179             category = entry.category
180             if category not in used:
181                 row = {
182                     'category': category,
183                     'entries': self._entries_for_category(category)
184                 }
185                 categories.append(row)
186                 used.append(category)
187         return categories
188 
189     def sponsors(self):
190         """Return a list of sponsors current at time of this version release.
191 
192         :returns: A list of SponsorPeriod objects for current project
193             whose release date coincides with the version release date.
194             Only approved sponsors are returned.
195             Returns None if the release date (which is optional) is not set.
196         :rtype: Queryset, None
197         """
198         if self.release_date is None:
199             return None
200         sponsors = SponsorshipPeriod.approved_objects.filter(
201                 end_date__gte=self.release_date).filter(
202                 start_date__lte=self.release_date).filter(
203                 project=self.project).order_by(
204             'start_date').order_by(
205             '-sponsorship_level__value')
206         return sponsors
207 
208     def formatted_release_date(self):
209         """"Return a long formatted released date e.g. 24 June 2016.
210 
211         :returns: A string containing the long formatted date, or an empty
212             string if the date is not set.
213         :rtype: str
214         """
215         long_date = None
216         if self.release_date:
217             # %-d Day of the month as a decimal number. (Platform specific)
218             # %B  Month as locale’s full name.
219             # %Y  Year e.g. 2016
220             long_date = self.release_date.strftime('%-d %B, %Y')
221         return long_date
222
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/django_project/changes/models/version.py b/django_project/changes/models/version.py
--- a/django_project/changes/models/version.py
+++ b/django_project/changes/models/version.py
@@ -202,7 +202,7 @@
                 start_date__lte=self.release_date).filter(
                 project=self.project).order_by(
             'start_date').order_by(
-            '-sponsorship_level__value')
+            '-sponsorship_level__value', 'sponsor__name')
         return sponsors
 
     def formatted_release_date(self):

{"golden_diff": "diff --git a/django_project/changes/models/version.py b/django_project/changes/models/version.py\n--- a/django_project/changes/models/version.py\n+++ b/django_project/changes/models/version.py\n@@ -202,7 +202,7 @@\n                 start_date__lte=self.release_date).filter(\n                 project=self.project).order_by(\n             'start_date').order_by(\n-            '-sponsorship_level__value')\n+            '-sponsorship_level__value', 'sponsor__name')\n         return sponsors\n \n     def formatted_release_date(self):\n", "issue": "Order sponsors in their groups\nFrom @andreasneumann: \n\n```For the sponsors listing - is there a clear order within the same level at http://changelog.qgis.org/en/qgis/version/2.16.0/ ?\n\nIn my opinion, it should either be ordered alphabetically or by date. Neither seems to be the case. I would prefer alphabetic ordering with in each sponsorship level.```\n\nI think it is actually better to order them with most recently added sponsors first to oldest sponsors last. That we they get the most visibility when they are new, degrading over time to the bottom of the list. What do you think @andreasneumann ?\n\n", "before_files": [{"content": "# coding=utf-8\nfrom django.core.urlresolvers import reverse\n# from django.utils.text import slugify\nfrom common.utilities import version_slugify\nimport os\nimport logging\nfrom core.settings.contrib import STOP_WORDS\nfrom django.conf.global_settings import MEDIA_ROOT\nfrom django.db import models\nfrom .entry import Entry\nfrom .sponsorship_period import SponsorshipPeriod\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\nlogger = logging.getLogger(__name__)\n\n\nclass ApprovedVersionManager(models.Manager):\n    \"\"\"Custom version manager that shows only approved records.\"\"\"\n\n    def get_queryset(self):\n        \"\"\"Query set generator\"\"\"\n        return super(\n            ApprovedVersionManager, self).get_queryset().filter(\n                approved=True)\n\n\nclass UnapprovedVersionManager(models.Manager):\n    \"\"\"Custom version manager that shows only unapproved records.\"\"\"\n\n    def get_queryset(self):\n        \"\"\"Query set generator\"\"\"\n        return super(\n            UnapprovedVersionManager, self).get_queryset().filter(\n                approved=False)\n\n\n# noinspection PyUnresolvedReferences\nclass Version(models.Model):\n    \"\"\"A version model that the changelog is associated with..\"\"\"\n\n    name = models.CharField(\n        help_text='Name of this release e.g. 1.0.1.',\n        max_length=255,\n        null=False,\n        blank=False,\n        unique=False)\n\n    padded_version = models.CharField(\n        help_text=(\n            'Numeric version for this release e.g. 001000001 for 1.0.1 '\n            'calculated by zero padding each component of maj/minor/bugfix '\n            'elements from name.'),\n        max_length=9,\n        null=False,\n        blank=True,\n        unique=False)\n\n    approved = models.BooleanField(\n        help_text=(\n            'Whether this version has been approved for use by the '\n            'project owner.'),\n        default=False)\n\n    image_file = models.ImageField(\n        help_text=(\n            'An optional image for this version e.g. a splashscreen. '\n            'Most browsers support dragging the image directly on to the '\n            '\"Choose File\" button above.'),\n        upload_to=os.path.join(MEDIA_ROOT, 'images/projects'),\n        blank=True)\n\n    description = models.TextField(\n        null=True,\n        blank=True,\n        help_text='Describe the new version. Markdown is supported.')\n\n    release_date = models.DateField(\n        _('Release date (yyyy-mm-dd)'),\n        help_text='Date of official release',\n        null=True,\n        blank=True)\n\n    author = models.ForeignKey(User)\n    slug = models.SlugField()\n    project = models.ForeignKey('base.Project')\n    objects = models.Manager()\n    approved_objects = ApprovedVersionManager()\n    unapproved_objects = UnapprovedVersionManager()\n\n    # noinspection PyClassicStyleClass\n    class Meta:\n        \"\"\"Meta options for the version class.\"\"\"\n        unique_together = (\n            ('name', 'project'),\n            ('slug', 'project'),\n        )\n        app_label = 'changes'\n        # ordering = ['-datetime_created']\n\n    def save(self, *args, **kwargs):\n        if not self.pk:\n            words = self.name.split()\n            filtered_words = [t for t in words if t.lower() not in STOP_WORDS]\n            new_list = ' '.join(filtered_words)\n            self.slug = version_slugify(new_list)[:50]\n        self.padded_version = self.pad_name(self.name)\n        super(Version, self).save(*args, **kwargs)\n\n    def pad_name(self, version):\n        \"\"\"Create a 0 padded version of the version name.\n\n        e.g. input: 2.10.1\n        e.g. output: 002010100\n\n        This will ensure we have sortable version names.\n\n        :param version: A text version in the form 0.0.0 - if the version is\n            not in this form, we return the version unaltered.\n        :type version: str\n\n        :returns: Zero padded representation of the version e.g. 001010100\n        :rtype: str\n\n        \"\"\"\n        tokens = version.split('.')\n        if len(tokens) != 3:\n            return version\n        result = ''\n        for token in tokens:\n            result += token.zfill(3)\n        return result\n\n    def __unicode__(self):\n        return u'%s : %s' % (self.project.name, self.name)\n\n    def get_absolute_url(self):\n        return reverse('version-detail', kwargs={\n            'slug': self.slug,\n            'project_slug': self.project.slug\n        })\n\n    def entries(self):\n        \"\"\"Get the entries for this version.\"\"\"\n        qs = Entry.objects.filter(version=self).order_by('category__sort_number')\n        return qs\n\n    def _entries_for_category(self, category):\n        \"\"\"All entries for this version and filtered by the given category.\n\n        :param category: Category to filter by.\n        :type category: Category\n\n        .. note:: only approved entries returned.\n        \"\"\"\n        qs = Entry.objects.filter(\n                version=self,\n                category=category,\n                approved=True)\n        return qs\n\n    def categories(self):\n        \"\"\"Get a list of categories where there are one or more entries.\n\n        Example use in template::\n            {% for row in version.categories %}\n              <h2 class=\"text-muted\">{{ row.category.name }}</h2>\n              <ul>\n              {%  for entry in row.entries %}\n                 <li>{{ entry.name }}</li>\n              {% endfor %}\n              </ul>\n            {% endfor %}\n        \"\"\"\n        qs = self.entries()\n        used = []\n        categories = []\n        for entry in qs:\n            category = entry.category\n            if category not in used:\n                row = {\n                    'category': category,\n                    'entries': self._entries_for_category(category)\n                }\n                categories.append(row)\n                used.append(category)\n        return categories\n\n    def sponsors(self):\n        \"\"\"Return a list of sponsors current at time of this version release.\n\n        :returns: A list of SponsorPeriod objects for current project\n            whose release date coincides with the version release date.\n            Only approved sponsors are returned.\n            Returns None if the release date (which is optional) is not set.\n        :rtype: Queryset, None\n        \"\"\"\n        if self.release_date is None:\n            return None\n        sponsors = SponsorshipPeriod.approved_objects.filter(\n                end_date__gte=self.release_date).filter(\n                start_date__lte=self.release_date).filter(\n                project=self.project).order_by(\n            'start_date').order_by(\n            '-sponsorship_level__value')\n        return sponsors\n\n    def formatted_release_date(self):\n        \"\"\"\"Return a long formatted released date e.g. 24 June 2016.\n\n        :returns: A string containing the long formatted date, or an empty\n            string if the date is not set.\n        :rtype: str\n        \"\"\"\n        long_date = None\n        if self.release_date:\n            # %-d Day of the month as a decimal number. (Platform specific)\n            # %B  Month as locale\u2019s full name.\n            # %Y  Year e.g. 2016\n            long_date = self.release_date.strftime('%-d %B, %Y')\n        return long_date\n", "path": "django_project/changes/models/version.py"}], "after_files": [{"content": "# coding=utf-8\nfrom django.core.urlresolvers import reverse\n# from django.utils.text import slugify\nfrom common.utilities import version_slugify\nimport os\nimport logging\nfrom core.settings.contrib import STOP_WORDS\nfrom django.conf.global_settings import MEDIA_ROOT\nfrom django.db import models\nfrom .entry import Entry\nfrom .sponsorship_period import SponsorshipPeriod\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\nlogger = logging.getLogger(__name__)\n\n\nclass ApprovedVersionManager(models.Manager):\n    \"\"\"Custom version manager that shows only approved records.\"\"\"\n\n    def get_queryset(self):\n        \"\"\"Query set generator\"\"\"\n        return super(\n            ApprovedVersionManager, self).get_queryset().filter(\n                approved=True)\n\n\nclass UnapprovedVersionManager(models.Manager):\n    \"\"\"Custom version manager that shows only unapproved records.\"\"\"\n\n    def get_queryset(self):\n        \"\"\"Query set generator\"\"\"\n        return super(\n            UnapprovedVersionManager, self).get_queryset().filter(\n                approved=False)\n\n\n# noinspection PyUnresolvedReferences\nclass Version(models.Model):\n    \"\"\"A version model that the changelog is associated with..\"\"\"\n\n    name = models.CharField(\n        help_text='Name of this release e.g. 1.0.1.',\n        max_length=255,\n        null=False,\n        blank=False,\n        unique=False)\n\n    padded_version = models.CharField(\n        help_text=(\n            'Numeric version for this release e.g. 001000001 for 1.0.1 '\n            'calculated by zero padding each component of maj/minor/bugfix '\n            'elements from name.'),\n        max_length=9,\n        null=False,\n        blank=True,\n        unique=False)\n\n    approved = models.BooleanField(\n        help_text=(\n            'Whether this version has been approved for use by the '\n            'project owner.'),\n        default=False)\n\n    image_file = models.ImageField(\n        help_text=(\n            'An optional image for this version e.g. a splashscreen. '\n            'Most browsers support dragging the image directly on to the '\n            '\"Choose File\" button above.'),\n        upload_to=os.path.join(MEDIA_ROOT, 'images/projects'),\n        blank=True)\n\n    description = models.TextField(\n        null=True,\n        blank=True,\n        help_text='Describe the new version. Markdown is supported.')\n\n    release_date = models.DateField(\n        _('Release date (yyyy-mm-dd)'),\n        help_text='Date of official release',\n        null=True,\n        blank=True)\n\n    author = models.ForeignKey(User)\n    slug = models.SlugField()\n    project = models.ForeignKey('base.Project')\n    objects = models.Manager()\n    approved_objects = ApprovedVersionManager()\n    unapproved_objects = UnapprovedVersionManager()\n\n    # noinspection PyClassicStyleClass\n    class Meta:\n        \"\"\"Meta options for the version class.\"\"\"\n        unique_together = (\n            ('name', 'project'),\n            ('slug', 'project'),\n        )\n        app_label = 'changes'\n        # ordering = ['-datetime_created']\n\n    def save(self, *args, **kwargs):\n        if not self.pk:\n            words = self.name.split()\n            filtered_words = [t for t in words if t.lower() not in STOP_WORDS]\n            new_list = ' '.join(filtered_words)\n            self.slug = version_slugify(new_list)[:50]\n        self.padded_version = self.pad_name(self.name)\n        super(Version, self).save(*args, **kwargs)\n\n    def pad_name(self, version):\n        \"\"\"Create a 0 padded version of the version name.\n\n        e.g. input: 2.10.1\n        e.g. output: 002010100\n\n        This will ensure we have sortable version names.\n\n        :param version: A text version in the form 0.0.0 - if the version is\n            not in this form, we return the version unaltered.\n        :type version: str\n\n        :returns: Zero padded representation of the version e.g. 001010100\n        :rtype: str\n\n        \"\"\"\n        tokens = version.split('.')\n        if len(tokens) != 3:\n            return version\n        result = ''\n        for token in tokens:\n            result += token.zfill(3)\n        return result\n\n    def __unicode__(self):\n        return u'%s : %s' % (self.project.name, self.name)\n\n    def get_absolute_url(self):\n        return reverse('version-detail', kwargs={\n            'slug': self.slug,\n            'project_slug': self.project.slug\n        })\n\n    def entries(self):\n        \"\"\"Get the entries for this version.\"\"\"\n        qs = Entry.objects.filter(version=self).order_by('category__sort_number')\n        return qs\n\n    def _entries_for_category(self, category):\n        \"\"\"All entries for this version and filtered by the given category.\n\n        :param category: Category to filter by.\n        :type category: Category\n\n        .. note:: only approved entries returned.\n        \"\"\"\n        qs = Entry.objects.filter(\n                version=self,\n                category=category,\n                approved=True)\n        return qs\n\n    def categories(self):\n        \"\"\"Get a list of categories where there are one or more entries.\n\n        Example use in template::\n            {% for row in version.categories %}\n              <h2 class=\"text-muted\">{{ row.category.name }}</h2>\n              <ul>\n              {%  for entry in row.entries %}\n                 <li>{{ entry.name }}</li>\n              {% endfor %}\n              </ul>\n            {% endfor %}\n        \"\"\"\n        qs = self.entries()\n        used = []\n        categories = []\n        for entry in qs:\n            category = entry.category\n            if category not in used:\n                row = {\n                    'category': category,\n                    'entries': self._entries_for_category(category)\n                }\n                categories.append(row)\n                used.append(category)\n        return categories\n\n    def sponsors(self):\n        \"\"\"Return a list of sponsors current at time of this version release.\n\n        :returns: A list of SponsorPeriod objects for current project\n            whose release date coincides with the version release date.\n            Only approved sponsors are returned.\n            Returns None if the release date (which is optional) is not set.\n        :rtype: Queryset, None\n        \"\"\"\n        if self.release_date is None:\n            return None\n        sponsors = SponsorshipPeriod.approved_objects.filter(\n                end_date__gte=self.release_date).filter(\n                start_date__lte=self.release_date).filter(\n                project=self.project).order_by(\n            'start_date').order_by(\n            '-sponsorship_level__value', 'sponsor__name')\n        return sponsors\n\n    def formatted_release_date(self):\n        \"\"\"\"Return a long formatted released date e.g. 24 June 2016.\n\n        :returns: A string containing the long formatted date, or an empty\n            string if the date is not set.\n        :rtype: str\n        \"\"\"\n        long_date = None\n        if self.release_date:\n            # %-d Day of the month as a decimal number. (Platform specific)\n            # %B  Month as locale\u2019s full name.\n            # %Y  Year e.g. 2016\n            long_date = self.release_date.strftime('%-d %B, %Y')\n        return long_date\n", "path": "django_project/changes/models/version.py"}]}