internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: django-extensions/django-extensions

Issue:
runjobs daily error with get_cache
This is with django 1.9.x, extensions 1.6.1 and python 3.4:

Traceback (most recent call last):
  File "/home/me/python3/lib/python3.4/site-packages/django_extensions/management/commands/runjobs.py", line 29, in runjobs
    job().execute()
  File "/home/me/python3/lib/python3.4/site-packages/django_extensions/jobs/daily/cache_cleanup.py", line 37, in execute
    from django.core.cache import get_cache
ImportError: cannot import name 'get_cache'
ERROR OCCURED IN DAILY JOB: cache_cleanup (APP: django_extensions)
START TRACEBACK:
END TRACEBACK

I'm not sure what this is, googling didn't help at all.



Discussion:

Resolving patch:
diff --git a/django_extensions/jobs/daily/cache_cleanup.py b/django_extensions/jobs/daily/cache_cleanup.py
--- a/django_extensions/jobs/daily/cache_cleanup.py
+++ b/django_extensions/jobs/daily/cache_cleanup.py
@@ -35,12 +35,12 @@ def atomic(using=None):
                 transaction.commit_unless_managed(using=using)
 
         if hasattr(settings, 'CACHES') and timezone:
-            from django.core.cache import get_cache
+            from django.core.cache import caches
             from django.db import router, connections
 
             for cache_name, cache_options in six.iteritems(settings.CACHES):
                 if cache_options['BACKEND'].endswith("DatabaseCache"):
-                    cache = get_cache(cache_name)
+                    cache = caches[cache_name]
                     db = router.db_for_write(cache.cache_model_class)
                     with atomic(using=db):
                         cursor = connections[db].cursor()


Test patch:
Repository: django-extensions/django-extensions

Issue:
1.6 tests are broken on master
#837 introduced django.apps which was added in 1.7.



Discussion:

Resolving patch:
diff --git a/django_extensions/compat.py b/django_extensions/compat.py
--- a/django_extensions/compat.py
+++ b/django_extensions/compat.py
@@ -199,6 +199,15 @@ def add_to_builtins_compat(name):
         engines['django'].engine.builtins.append(name)
 
 
+def get_model(path):
+    if django.VERSION < (1.7):
+        from django.db.models.loading import get_model
+        return get_model(*path.split('.', 1))
+    else:
+        from django.apps import apps
+        return apps.get_model(*path.split('.', 1))
+
+
 class ProxyParser(object):
     """Faux parser object that will ferry our arguments into options."""
 
diff --git a/django_extensions/management/modelviz.py b/django_extensions/management/modelviz.py
--- a/django_extensions/management/modelviz.py
+++ b/django_extensions/management/modelviz.py
@@ -13,7 +13,6 @@
 
 import six
 import django
-from django.apps import apps
 from django.db.models.fields.related import (
     ForeignKey, ManyToManyField, OneToOneField, RelatedField,
 )
@@ -31,7 +30,7 @@
 except ImportError:
     from django.contrib.contenttypes.generic import GenericRelation
 
-from django_extensions.compat import get_app, get_models_compat, list_app_labels
+from django_extensions.compat import get_app, get_models_compat, list_app_labels, get_model
 
 
 __version__ = "1.0"
@@ -218,7 +217,7 @@ def add_relation(field, extras=""):
                     if field.rel.to == 'self':
                         target_model = field.model
                     else:
-                        target_model = apps.get_model(*field.rel.to.split('.'))
+                        target_model = get_model(field.rel.to)
                 else:
                     target_model = field.rel.to
 


Test patch:
Repository: django-extensions/django-extensions

Issue:
add JSON format to show_urls
Could you please add JSON format in addition to existing output formats for **show_urls** command?



Discussion:

Resolving patch:
diff --git a/django_extensions/management/commands/show_urls.py b/django_extensions/management/commands/show_urls.py
--- a/django_extensions/management/commands/show_urls.py
+++ b/django_extensions/management/commands/show_urls.py
@@ -1,5 +1,6 @@
 # coding=utf-8
 import functools
+import json
 import re
 
 from django.conf import settings
@@ -18,6 +19,8 @@
     'table': "{url},{module},{url_name},{decorator}",
     'aligned': "{url},{module},{url_name},{decorator}",
     'verbose': "{url}\n\tController: {module}\n\tURL Name: {url_name}\n\tDecorators: {decorator}\n",
+    'json': '',
+    'pretty-json': ''
 }
 
 
@@ -67,6 +70,9 @@ def handle(self, *args, **options):
         format_style = options.get('format_style')
         if format_style not in FMTR:
             raise CommandError("Format style '%s' does not exist. Options: %s" % (format_style, FMTR.keys()))
+        pretty_json = format_style == 'pretty-json'
+        if pretty_json:
+            format_style = 'json'
         fmtr = FMTR[format_style]
 
         urlconf = options.get('urlconf')
@@ -107,14 +113,22 @@ def handle(self, *args, **options):
                 else:
                     func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))
 
-                views.append(fmtr.format(
-                    module='{0}.{1}'.format(style.MODULE(func.__module__), style.MODULE_NAME(func_name)),
-                    url_name=style.URL_NAME(url_name or ''),
-                    url=style.URL(simplify_regex(regex)),
-                    decorator=', '.join(decorators),
-                ))
+                module = '{0}.{1}'.format(func.__module__, func_name)
+                url_name = url_name or ''
+                url = simplify_regex(regex)
+                decorator = ', '.join(decorators)
 
-        if not options.get('unsorted', False):
+                if format_style == 'json':
+                    views.append({"url": url, "module": module, "name": url_name, "decorators": decorator})
+                else:
+                    views.append(fmtr.format(
+                        module='{0}.{1}'.format(style.MODULE(func.__module__), style.MODULE_NAME(func_name)),
+                        url_name=style.URL_NAME(url_name),
+                        url=style.URL(url),
+                        decorator=decorator,
+                    ))
+
+        if not options.get('unsorted', False) and format_style != 'json':
             views = sorted(views)
 
         if format_style == 'aligned':
@@ -145,6 +159,11 @@ def handle(self, *args, **options):
             # Replace original views so we can return the same object
             views = table_views
 
+        elif format_style == 'json':
+            if pretty_json:
+                return json.dumps(views, indent=4)
+            return json.dumps(views)
+
         return "\n".join([v for v in views]) + "\n"
 
     def extract_views_from_urlpatterns(self, urlpatterns, base='', namespace=None):


Test patch:
Repository: django-extensions/django-extensions

Issue:
AutoSlugField doesn't populate model
Using the AutoSlugField in the normal way (making a slug from a name). It seems the slug field doesn't get populated in python but only in the sql.

Create a model and slug field is blank. Load the model from the database and the slug is populated.

Means I can't use the new model to redirect to since the slug is empty.



Discussion:
Have same behaviour when specify `allow_duplicates = False`. With `allow_duplicates = True` (default) all goes well.


Resolving patch:
diff --git a/django_extensions/db/fields/__init__.py b/django_extensions/db/fields/__init__.py
--- a/django_extensions/db/fields/__init__.py
+++ b/django_extensions/db/fields/__init__.py
@@ -168,6 +168,7 @@ def create_slug(self, model_instance, add):
         original_slug = slug
 
         if self.allow_duplicates:
+            setattr(model_instance, self.attname, slug)
             return slug
 
         return super(AutoSlugField, self).find_unique(


Test patch:
Repository: django-extensions/django-extensions

Issue:
How to use passwd doesn't seem to be documented.
When I run `manage.py passwd` it just tells me my user doesn't have a django user. `--help` doesn't really explain how to use passwd.



Discussion:

Resolving patch:
diff --git a/django_extensions/management/commands/passwd.py b/django_extensions/management/commands/passwd.py
--- a/django_extensions/management/commands/passwd.py
+++ b/django_extensions/management/commands/passwd.py
@@ -12,23 +12,20 @@ class Command(BaseCommand):
 
     requires_system_checks = False
 
+    def add_arguments(self, parser):
+        parser.add_argument('username', nargs='?', type=str)
+
     @signalcommand
     def handle(self, *args, **options):
-        if len(args) > 1:
-            raise CommandError("need exactly one or zero arguments for username")
-
-        if args:
-            username, = args
-        else:
-            username = getpass.getuser()
+        username = options['username'] or getpass.getuser()
 
         User = get_user_model()
         try:
-            u = User.objects.get(username=username)
+            u = User.objects.get_by_natural_key(username)
         except User.DoesNotExist:
             raise CommandError("user %s does not exist" % username)
 
-        print("Changing password for user: %s" % u.username)
+        print("Changing password for user: %s" % username)
         p1 = p2 = ""
         while "" in (p1, p2) or p1 != p2:
             p1 = getpass.getpass()
@@ -41,4 +38,4 @@ def handle(self, *args, **options):
         u.set_password(p1)
         u.save()
 
-        return "Password changed successfully for user %s\n" % u.username
+        return "Password changed successfully for user %s\n" % username


Test patch:
Repository: django-extensions/django-extensions

Issue:
Prefer django.urls instead of django.core.urlresolvers
`django.core.urlresolvers` is deprecated and emits warnings.


Discussion:

Resolving patch:
diff --git a/django_extensions/admin/widgets.py b/django_extensions/admin/widgets.py
--- a/django_extensions/admin/widgets.py
+++ b/django_extensions/admin/widgets.py
@@ -4,7 +4,10 @@
 from django import forms
 from django.contrib.admin.sites import site
 from django.contrib.admin.widgets import ForeignKeyRawIdWidget
-from django.core.urlresolvers import reverse
+try:
+    from django.urls import reverse
+except ImportError:
+    from django.core.urlresolvers import reverse
 from django.template.loader import render_to_string
 from django.utils.safestring import mark_safe
 from django.utils.text import Truncator
diff --git a/django_extensions/management/commands/show_urls.py b/django_extensions/management/commands/show_urls.py
--- a/django_extensions/management/commands/show_urls.py
+++ b/django_extensions/management/commands/show_urls.py
@@ -7,7 +7,10 @@
 from django.contrib.admindocs.views import simplify_regex
 from django.core.exceptions import ViewDoesNotExist
 from django.core.management.base import BaseCommand, CommandError
-from django.core.urlresolvers import RegexURLPattern, RegexURLResolver, LocaleRegexURLResolver
+try:
+    from django.urls import RegexURLPattern, RegexURLResolver, LocaleRegexURLResolver
+except ImportError:
+    from django.core.urlresolvers import RegexURLPattern, RegexURLResolver, LocaleRegexURLResolver
 from django.utils import translation
 
 from django_extensions.management.color import color_style, no_style


Test patch:
Repository: django-extensions/django-extensions

Issue:
AttributeError: 'Command' object has no attribute '_is_stable'
Pipchecker has been broken in commit 5ad36e6d9ed585b98cf3964f83fe80ad65a6913b/PR #978


Discussion:
I am terribly sorry. I must have done a bad merge when passing over the changes from the code I was using. I will submit a fix shortly.

Resolving patch:
diff --git a/django_extensions/management/commands/pipchecker.py b/django_extensions/management/commands/pipchecker.py
--- a/django_extensions/management/commands/pipchecker.py
+++ b/django_extensions/management/commands/pipchecker.py
@@ -1,6 +1,7 @@
 # -*- coding: utf-8 -*-
 import json
 import os
+import re
 from distutils.version import LooseVersion
 
 import pip
@@ -108,6 +109,9 @@ def _urlopen_as_json(self, url, headers=None):
         req = Request(url, headers=headers)
         return json.loads(urlopen(req).read())
 
+    def _is_stable(self, version):
+        return not re.search(r'[ab]\d+$', str(version))
+
     def _available_version(self, dist_version, available):
         if self._is_stable(dist_version):
             stable = [v for v in available if self._is_stable(LooseVersion(v))]


Test patch:
Repository: django-extensions/django-extensions

Issue:
runserver_plus command, pm (postmortem) mode does not work with python 3
Issue is on Line 175 in management/commands/runserver_plus.py:
`print >>> sys.stderr, "Exception occured: %s, %s" % (exc_type, exc_value)`

This syntax does not work with Python 3. To make it work, we need to do:

```
from __future__ import print_function
....
.....
print("Exception occured: %s, %s" % (exc_type, exc_value), file=sys.stderr)

```

Should I send a PR?



Discussion:
Sorry for the extremely late reply.

Yes please send a PR to fix this if it's still necessary.


Resolving patch:
diff --git a/django_extensions/management/commands/runserver_plus.py b/django_extensions/management/commands/runserver_plus.py
--- a/django_extensions/management/commands/runserver_plus.py
+++ b/django_extensions/management/commands/runserver_plus.py
@@ -1,4 +1,6 @@
 # -*- coding: utf-8 -*-
+from __future__ import print_function
+
 import logging
 import os
 import re
@@ -7,16 +9,19 @@
 import time
 
 from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
 from django.core.management.base import BaseCommand, CommandError
-from django.db import connections, DEFAULT_DB_ALIAS
+from django.core.servers.basehttp import get_internal_wsgi_application
+from django.db import DEFAULT_DB_ALIAS, connections
 from django.db.backends import utils
 from django.db.migrations.executor import MigrationExecutor
-from django.core.exceptions import ImproperlyConfigured
-from django.core.servers.basehttp import get_internal_wsgi_application
 from django.utils.autoreload import gen_filenames
 
-from django_extensions.management.technical_response import null_technical_500_response
-from django_extensions.management.utils import RedirectHandler, setup_logger, signalcommand, has_ipdb
+from django_extensions.management.technical_response import \
+    null_technical_500_response
+from django_extensions.management.utils import (
+    RedirectHandler, has_ipdb, setup_logger, signalcommand,
+)
 
 try:
     if 'whitenoise.runserver_nostatic' in settings.INSTALLED_APPS:
@@ -196,8 +201,7 @@ def postmortem(request, exc_type, exc_value, tb):
                 else:
                     import pdb
                     p = pdb
-                print >>sys.stderr, "Exception occured: %s, %s" % (exc_type,
-                                                                   exc_value)
+                print("Exception occured: %s, %s" % (exc_type, exc_value), file=sys.stderr)
                 p.post_mortem(tb)
 
         # usurp django's handler


Test patch:
Repository: django-extensions/django-extensions

Issue:
Use text/plain for foreign key autocomplete admin
My admin site uses `ForeignKeyAutocompleteAdmin`. One day, our autocomplete fields started looking like this:

<img width="816" alt="screen shot 2017-05-18 at 3 25 59 pm" src="https://cloud.githubusercontent.com/assets/3439947/26224142/5551f812-3bde-11e7-8c23-74bec868f7f5.png">

The full HTML response looked like this:

`<html><head></head><body>My Venue</body></html>`

This issue was that we are using `htmlmin.middleware.HtmlMinifyMiddleware`, and since the response's content type is `text/html`, the response was 'minified' to include HTML tags

I solved this issue by doing this in my admin class:

```
    def foreignkey_autocomplete(self, request):
        response = super(BaseModelAdmin, self).foreignkey_autocomplete(request)
        # HtmlMinifyMiddleware does not play nicely with ForeignKeyAutocompleteAdmin - force response to plain text
        response['Content-Type'] = 'text/plain'
        return response
```

Though this code solved my issue, I suggest that the content type of `foreignkey_autocomplete` response should be set to `text/plain` instead of using the default `text/html` to avoid more issues like this.



Discussion:
Could you please make a PR for this ?

Resolving patch:
diff --git a/django_extensions/admin/__init__.py b/django_extensions/admin/__init__.py
--- a/django_extensions/admin/__init__.py
+++ b/django_extensions/admin/__init__.py
@@ -120,7 +120,7 @@ def construct_search(field_name):
                     pass
                 else:
                     data = to_string_function(obj)
-            return HttpResponse(data)
+            return HttpResponse(data, content_type='text/plain')
         return HttpResponseNotFound()
 
     def get_related_filter(self, model, request):


Test patch:
Repository: django-extensions/django-extensions

Issue:
pipchecker doesn't find misconfigured pypi packages
I've encountered problems with running pipchecker when there's a package which is misconfigured on pypi with underscores instead of dashes.  For example:

```
% manage.py pipchecker
django-celery-beat 1.0.1         release is not on pypi (check capitalization and/or --extra-index-url)
django-polymorphic 1.3           release is not on pypi (check capitalization and/or --extra-index-url)
```

Each of these packages seems to have been set up incorrectly to use underscores instead of dashes, and I've filed bugs for both of these packages to change their pypi entries (hopefully)
https://github.com/django-polymorphic/django-polymorphic/issues/319#issuecomment-345702344
https://github.com/celery/django-celery-beat/issues/85

But I also think it would be great if pipchecker could be more resilient.  I've tested a fix that seems to work which when searching the parsed pypi xml data searches for both the proper name, and a transformed name where dashes are replaced by underscores.

`available = pypi.package_releases(req["pip_req"].name, True)`
->
`available = pypi.package_releases(req["pip_req"].name, True) or  pypi.package_releases(req["pip_req"].name.replace('-','_'), True)`




Discussion:

Resolving patch:
diff --git a/django_extensions/management/commands/pipchecker.py b/django_extensions/management/commands/pipchecker.py
--- a/django_extensions/management/commands/pipchecker.py
+++ b/django_extensions/management/commands/pipchecker.py
@@ -136,7 +136,7 @@ def check_pypi(self):
             elif "dist" in req:
                 dist = req["dist"]
                 dist_version = LooseVersion(dist.version)
-                available = pypi.package_releases(req["pip_req"].name, True)
+                available = pypi.package_releases(req["pip_req"].name, True) or pypi.package_releases(req["pip_req"].name.replace('-', '_'), True)
                 available_version = self._available_version(dist_version, available)
 
                 if not available_version:


Test patch:
Repository: django-extensions/django-extensions

Issue:
AutoSlugField.deconstruct does not match construction values
I'll try to submit a PR later but in case i forget:

The deconstruct() call should return the same which were used to initalize the field. However the populate_from property is changed from create_slug() which causes the django migration checker to think that a migration is required.

See workaround solution here: https://github.com/django-oscar/django-oscar/commit/27cb08936252ae320423ecccc22b5658135c5b04



Discussion:
Is this still an issue ?
If so we would appreciate the PR :)


Resolving patch:
diff --git a/django_extensions/db/fields/__init__.py b/django_extensions/db/fields/__init__.py
--- a/django_extensions/db/fields/__init__.py
+++ b/django_extensions/db/fields/__init__.py
@@ -149,14 +149,15 @@ def slug_generator(self, original_slug, start):
 
     def create_slug(self, model_instance, add):
         # get fields to populate from and slug field to set
-        if not isinstance(self._populate_from, (list, tuple)):
-            self._populate_from = (self._populate_from, )
+        populate_from = self._populate_from
+        if not isinstance(populate_from, (list, tuple)):
+            populate_from = (populate_from, )
         slug_field = model_instance._meta.get_field(self.attname)
 
         if add or self.overwrite:
             # slugify the original field content and set next step to 2
             slug_for_field = lambda lookup_value: self.slugify_func(self.get_slug_fields(model_instance, lookup_value))
-            slug = self.separator.join(map(slug_for_field, self._populate_from))
+            slug = self.separator.join(map(slug_for_field, populate_from))
             start = 2
         else:
             # get slug from the current model instance


Test patch:
diff --git a/tests/test_autoslug_fields.py b/tests/test_autoslug_fields.py
--- a/tests/test_autoslug_fields.py
+++ b/tests/test_autoslug_fields.py
@@ -172,3 +172,10 @@ def test_17_migration(self):
         # Just make sure it runs for now, and that things look alright.
         result = self.safe_exec(output)
         self.assertIn("Migration", result)
+
+    def test_stable_deconstruct(self):
+        slug_field = SluggedTestModel._meta.get_field('slug')
+        construction_values = slug_field.deconstruct()
+        m = SluggedTestModel(title='foo')
+        m.save()
+        self.assertEqual(slug_field.deconstruct(), construction_values)