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

Issue:
filer/fields/file.py raises error when fields are empty
In the Admin change view, When I try to save an empty file field, I get an error:

    invalid literal for int() with base 10: ''
    /django/db/models/fields/__init__.py in get_prep_value, line 965

From the traceback, I get it is caused by submitting an empty string to a query in the `file.py`

```
site-packages/filer/fields/file.py in render
28.         obj = self.obj_for_value(value) 
```
Variable | Value
----- |----
__class__ | <class 'filer.fields.file.AdminFileWidget'>
attrs | {'id': 'id_image'}
name | 'image'
renderer | None
self | <filer.fields.image.AdminImageWidget object at 0x7fee4c164b70>
value | ''

I could hack a solution together by checking if `value == ''` before trying to retrieve the object in `obj_for_value`, but I'm not sure if that is the best way to fix it..

Versions:

Package | Name | Version
-- | -- | --
Django |   | 2.1
Python |   | 3.6.6
ckeditor | Ckeditor | 5.6.1
debug_toolbar | Debug Toolbar | 1.11
django_extensions | Django_Extensions | 2.1.4
easy_thumbnails | Easy_Thumbnails | <module 'easy_thumbnails.get_version' from '---/site-packages/easy_thumbnails/get_version.py'>
filer | Filer | 1.4.3




Discussion:

Resolving patch:
diff --git a/filer/fields/file.py b/filer/fields/file.py
--- a/filer/fields/file.py
+++ b/filer/fields/file.py
@@ -74,13 +74,16 @@ def label_for_value(self, value):
         return '&nbsp;<strong>%s</strong>' % truncate_words(obj, 14)
 
     def obj_for_value(self, value):
-        try:
-            key = self.rel.get_related_field().name
-            if LTE_DJANGO_1_8:
-                obj = self.rel.to._default_manager.get(**{key: value})
-            else:
-                obj = self.rel.model._default_manager.get(**{key: value})
-        except ObjectDoesNotExist:
+        if value:
+            try:
+                key = self.rel.get_related_field().name
+                if LTE_DJANGO_1_8:
+                    obj = self.rel.to._default_manager.get(**{key: value})
+                else:
+                    obj = self.rel.model._default_manager.get(**{key: value})
+            except ObjectDoesNotExist:
+                obj = None
+        else:
             obj = None
         return obj
 


Test patch:
Repository: django-cms/django-filer

Issue:
Fixes value error when folder is empty
Also makes sure the spacing is correct between button and text:

![image](https://user-images.githubusercontent.com/270307/67758686-70dda100-fa3e-11e9-8805-40fe04d90785.png)

Fixes #1165



Discussion:

Resolving patch:
diff --git a/filer/fields/folder.py b/filer/fields/folder.py
--- a/filer/fields/folder.py
+++ b/filer/fields/folder.py
@@ -31,6 +31,7 @@ def render(self, name, value, attrs=None, renderer=None):
         if attrs is None:
             attrs = {}
         related_url = None
+
         if value:
             try:
                 folder = Folder.objects.get(pk=value)
@@ -73,6 +74,8 @@ def label_for_value(self, value):
         return '&nbsp;<strong>%s</strong>' % truncate_words(obj, 14)
 
     def obj_for_value(self, value):
+        if not value:
+            return None
         try:
             key = self.rel.get_related_field().name
             obj = self.rel.model._default_manager.get(**{key: value})


Test patch:
Repository: django-cms/django-filer

Issue:
JQuery loaded by File polluting the global namespace when DEBUG = False
Encountered as a problem while using Mezzanine.

This was a regression introduced in b66a42b. Basically it causes jquery.js to be loaded after jquery.init.js when not in DEBUG.

Two-line fix, PR incoming.


Discussion:
This is required for all Django>2 installations. Which Django version are you using?

Resolving patch:
diff --git a/filer/fields/file.py b/filer/fields/file.py
--- a/filer/fields/file.py
+++ b/filer/fields/file.py
@@ -5,6 +5,7 @@
 import warnings
 
 from django import forms
+from django.conf import settings
 from django.contrib.admin.sites import site
 from django.contrib.admin.widgets import ForeignKeyRawIdWidget
 from django.core.exceptions import ObjectDoesNotExist
@@ -84,13 +85,14 @@ def obj_for_value(self, value):
         return obj
 
     class Media(object):
+        extra = '' if settings.DEBUG else '.min'
         css = {
             'all': [
                 'filer/css/admin_filer.css',
             ]
         }
         js = (
-            'admin/js/vendor/jquery/jquery.js',
+            'admin/js/vendor/jquery/jquery%s.js' % extra,
             'admin/js/jquery.init.js',
             'filer/js/libs/dropzone.min.js',
             'filer/js/addons/dropzone.init.js',


Test patch:
Repository: django-cms/django-filer

Issue:
By default, upload files into last used folder
Currently, if someone uploads a file using drag and drop on a widget, it is stored inside the special folder named "Unsorted Files". In large installations, this gives a bad user experience. One would expect such a file in the last used folder, which in django-filer is handled by the session variable `filer_last_folder_id`.

By adding one line in `filer.admin.clipboardadmin.ajax_upload()`, this could be fixed.

Please comment on this feature proposal.


Discussion:
Or a default public folder. At the moment the files are "unsorted", which means they don't have a folder.
They won't show in the search results (If FILER_ENABLE_PERMISSIONS = True), for users that aren't Admins. I wrote a migration to move all the files to the "public" folder, but I feel like it should be a default.

Another issue I didn't find an answer to yet. How to choose a default folder, that Filer would open in. At the moment the default is "Unsorted", which means no folder. Users just drag and drop by default to Unsorted. 

Resolving patch:
diff --git a/filer/admin/clipboardadmin.py b/filer/admin/clipboardadmin.py
--- a/filer/admin/clipboardadmin.py
+++ b/filer/admin/clipboardadmin.py
@@ -73,13 +73,14 @@ def ajax_upload(request, folder_id=None):
     """
     Receives an upload from the uploader. Receives only one file at a time.
     """
-    folder = None
     if folder_id:
         try:
             # Get folder
             folder = Folder.objects.get(pk=folder_id)
         except Folder.DoesNotExist:
             return JsonResponse({'error': NO_FOLDER_ERROR})
+    else:
+        folder = Folder.objects.filter(pk=request.session.get('filer_last_folder_id', 0)).first()
 
     # check permissions
     if folder and not folder.has_add_children_permission(request):


Test patch:
Repository: django-cms/django-filer

Issue:
On upload MIME-type is not set correctly
Since version 2.0, the MIME-type of files is stored inside a model field. Before that is was guessed each time needed, by using the file suffix.

At the time, when I created that pull request (#1152), I believed that the browser sends the correct MIME type using the HTTP request header `Content-Type`. Now, after working with version 2.0, I discovered that this is not the case (anymore?). For instance, when uploading JPEG-s to the server, the Content-Type is set to `application/octet-stream` instead of `image/jpeg` (what I expected). Therefore, uploaded images can not be interpreted as such anymore. 

This is a serious bug and I am sorry for having it introduced.

Anyway, it's easy to fix. We just have to look at the file immediately after upload, determining the MIME-type and storing that. We have two solutions:
1. we look at the file suffix of the uploaded file and guess the MIME-type using the well known function [`mimetypes.guess_type()`](https://docs.python.org/3.8/library/mimetypes.html#mimetypes.guess_type).
2. we use the third party library [`filetype`](https://pypi.org/project/filetype/), which opens the file and by reading parts of the content, it determines the MIME-type using some magic header information.

Actually, I would prefer solution 2 because it is safer. With solution 1, a malicious user could just add a wrong file suffix and have it processed by Pillow. Probably without any serious effect, but forgable anyway. Solution 2 however adds a third party dependency.

@FinalAngel @yakky what are your opinions about this?


Discussion:

Resolving patch:
diff --git a/filer/utils/files.py b/filer/utils/files.py
--- a/filer/utils/files.py
+++ b/filer/utils/files.py
@@ -32,7 +32,7 @@ def handle_upload(request):
             # This means we shouldn't continue...raise an error.
             raise UploadException("Invalid content length: %r" % content_length)
 
-        mime_type = request.META.get('CONTENT_TYPE', 'application/octet-stream')
+        mime_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
 
         upload_handlers = request.upload_handlers
         for handler in upload_handlers:


Test patch:
Repository: django-cms/django-filer

Issue:
filter.server.views `serve() missing 1 required positional argument: 'filer_file'`
A bug was introduced here when `filer_file` was made into a kwarg:

https://github.com/divio/django-filer/blame/29eea047f425254af9f4d68b24096fc3fd3a7197/filer/server/views.py#L31

Exception:
```
TypeError at /smedia/filer/filer_private/2d/ba/2dbaf742-4b45-456f-95b1-f560ec64e637/xxx.png
serve() missing 1 required positional argument: 'filer_file'


/usr/local/lib/python3.8/site-packages/filer/server/views.py, line 31, in serve_protected_file
    return server.serve(request, file_obj=file_obj, save_as=False) 

Variable | Value
-- | --
file_obj | <File:xxxpng>
path | 'filer_private/2d/ba/2dbaf742-4b45-456f-95b1-f560ec64e637/xxx.png'
request | <WSGIRequest: GET '/smedia/filer/filer_private/2d/ba/2dbaf742-4b45-456f-95b1-f560ec64e637/axxx.png'>
```


Discussion:

Resolving patch:
diff --git a/filer/server/views.py b/filer/server/views.py
--- a/filer/server/views.py
+++ b/filer/server/views.py
@@ -28,7 +28,7 @@ def serve_protected_file(request, path):
             raise PermissionDenied
         else:
             raise Http404('File not found')
-    return server.serve(request, file_obj=file_obj, save_as=False)
+    return server.serve(request, file_obj, save_as=False)
 
 
 @never_cache


Test patch:
Repository: django-cms/django-filer

Issue:
OSError Text file busy
Trying to set Permissions Disabled to false in the newly uploaded image, getting this:

**Linux**:
```
OSError at /admin/filer/image/5/change/
[Errno 26] Text file busy
```
**Windows**:
```
PermissionError at /admin/filer/image/5/change/
[WinError 32] The process cannot access the file because it is being used by another process
```

**Related code**:
https://github.com/divio/django-filer/blob/aa2feef63ab210d6ce1fbc19948752e1f8c6a460/filer/models/filemodels.py#L155-L164

**Suggestion fix**:
Add the line before deletion
`src_file.close()`

```python
        # This is needed because most of the remote File Storage backend do not
        # open the file.
        src_file = src_storage.open(src_file_name)
        src_file.open()
        # hint file_data_changed callback that data is actually unchanged
        self._file_data_changed_hint = False
        self.file = dst_storage.save(dst_file_name,
            ContentFile(src_file.read()))
        src_file.close()
        src_storage.delete(src_file_name)
```


Discussion:
Is there a problem or is it just me?

Resolving patch:
diff --git a/filer/models/filemodels.py b/filer/models/filemodels.py
--- a/filer/models/filemodels.py
+++ b/filer/models/filemodels.py
@@ -159,11 +159,12 @@ def _move_file(self):
         # This is needed because most of the remote File Storage backend do not
         # open the file.
         src_file = src_storage.open(src_file_name)
-        src_file.open()
+        # Context manager closes file after reading contents
+        with src_file.open() as f:
+            content_file = ContentFile(f.read())
         # hint file_data_changed callback that data is actually unchanged
         self._file_data_changed_hint = False
-        self.file = dst_storage.save(dst_file_name,
-            ContentFile(src_file.read()))
+        self.file = dst_storage.save(dst_file_name, content_file)
         src_storage.delete(src_file_name)
 
     def _copy_file(self, destination, overwrite=False):


Test patch:
Repository: django-cms/django-filer

Issue:
not owned files in unfiled folder can not be listed if perms ON
If there are files in "unfiled folder" which are not owned by current user, he can not list those in admin because current code filters on files inside folders the user can see (but "unfiled folder" is virtual). 

Proposal: replace this line (filer/admin/folderadmin.py):

```
file_qs = file_qs.filter(models.Q(folder__id__in=perms) | models.Q(owner=request.user))
```

by those ones:
```
filters = models.Q(folder__id__in=perms) | models.Q(owner=request.user)
if isinstance(folder, UnsortedImages):
    filters = filters | models.Q(folder_id__isnull=True)
file_qs = file_qs.filter(filters)
```

**EDIT**
Bug still there when searching a file inside all files. So, replacement should be :

```

            file_qs = file_qs.filter(models.Q(folder__id__in=perms) 
                                     | models.Q(folder_id__isnull=True) 
                                     | models.Q(owner=request.user))

```



Discussion:

Resolving patch:
diff --git a/filer/admin/folderadmin.py b/filer/admin/folderadmin.py
--- a/filer/admin/folderadmin.py
+++ b/filer/admin/folderadmin.py
@@ -322,7 +322,11 @@ def directory_listing(self, request, folder_id=None, viewtype=None):
         perms = FolderPermission.objects.get_read_id_list(request.user)
         root_exclude_kw = {'parent__isnull': False, 'parent__id__in': perms}
         if perms != 'All':
-            file_qs = file_qs.filter(models.Q(folder__id__in=perms) | models.Q(owner=request.user))
+            file_qs = file_qs.filter(
+                models.Q(folder__id__in=perms)
+                | models.Q(folder_id__isnull=True)
+                | models.Q(owner=request.user)
+            )
             folder_qs = folder_qs.filter(models.Q(id__in=perms) | models.Q(owner=request.user))
         else:
             root_exclude_kw.pop('parent__id__in')


Test patch:
Repository: django-cms/django-filer

Issue:
Field verbose_name should use gettext_lazy
Hi, 
model field verbose_names should use gettext_lazy, because it creates migrations based on user language settings. 

https://github.com/django-cms/django-filer/blob/master/filer/models/foldermodels.py#L9

This is migration generated after upgrade to django-filer 3.0
![image](https://github.com/django-cms/django-filer/assets/10236315/f3cdd97e-dcfe-449b-a928-a574976417da)

Thanks.
Field verbose_name should use gettext_lazy
Hi, 
model field verbose_names should use gettext_lazy, because it creates migrations based on user language settings. 

https://github.com/django-cms/django-filer/blob/master/filer/models/foldermodels.py#L9

This is migration generated after upgrade to django-filer 3.0
![image](https://github.com/django-cms/django-filer/assets/10236315/f3cdd97e-dcfe-449b-a928-a574976417da)

Thanks.


Discussion:
Or maybe I am just wrong and it doesn't help, just a guess.
@mihalikv No, you're right.

As a general rule;

`gettext_lazy()` should be used for anything loaded at runtime:
* `models.py` (fields, `verbose_name`, `help_text`, function `short_description`);
* `forms.py` (`labels`, `help_text`, `empty_label`);
* `apps.py` (`verbose_name`).

`gettext()`should be used for any modules that are executed during the request process, such as `views.py`
Or maybe I am just wrong and it doesn't help, just a guess.
@mihalikv No, you're right.

As a general rule;

`gettext_lazy()` should be used for anything loaded at runtime:
* `models.py` (fields, `verbose_name`, `help_text`, function `short_description`);
* `forms.py` (`labels`, `help_text`, `empty_label`);
* `apps.py` (`verbose_name`).

`gettext()`should be used for any modules that are executed during the request process, such as `views.py`

Resolving patch:
diff --git a/filer/models/foldermodels.py b/filer/models/foldermodels.py
--- a/filer/models/foldermodels.py
+++ b/filer/models/foldermodels.py
@@ -6,7 +6,7 @@
 from django.urls import reverse
 from django.utils.functional import cached_property
 from django.utils.html import format_html, format_html_join
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from .. import settings as filer_settings
 from . import mixins


Test patch:
Repository: django-cms/django-filer

Issue:
Field verbose_name should use gettext_lazy
Hi, 
model field verbose_names should use gettext_lazy, because it creates migrations based on user language settings. 

https://github.com/django-cms/django-filer/blob/master/filer/models/foldermodels.py#L9

This is migration generated after upgrade to django-filer 3.0
![image](https://github.com/django-cms/django-filer/assets/10236315/f3cdd97e-dcfe-449b-a928-a574976417da)

Thanks.


Discussion:
Or maybe I am just wrong and it doesn't help, just a guess.
@mihalikv No, you're right.

As a general rule;

`gettext_lazy()` should be used for anything loaded at runtime:
* `models.py` (fields, `verbose_name`, `help_text`, function `short_description`);
* `forms.py` (`labels`, `help_text`, `empty_label`);
* `apps.py` (`verbose_name`).

`gettext()`should be used for any modules that are executed during the request process, such as `views.py`

Resolving patch:
diff --git a/mptt/__init__.py b/mptt/__init__.py
deleted file mode 100644


Test patch:
diff --git a/tests/requirements/base.txt b/tests/requirements/base.txt
--- a/tests/requirements/base.txt
+++ b/tests/requirements/base.txt
@@ -1,5 +1,6 @@
 # requirements from setup.py
 Pillow
+django-app-helper>=3.3.1
 
 # other requirements
 coverage
diff --git a/tests/requirements/django-2.2.txt b/tests/requirements/django-2.2.txt
--- a/tests/requirements/django-2.2.txt
+++ b/tests/requirements/django-2.2.txt
@@ -2,4 +2,3 @@
 
 django>=2.2,<3.0
 django_polymorphic>=2.0,<2.1
-django-app-helper
diff --git a/tests/requirements/django-3.0.txt b/tests/requirements/django-3.0.txt
--- a/tests/requirements/django-3.0.txt
+++ b/tests/requirements/django-3.0.txt
@@ -2,4 +2,3 @@
 
 django>=3.0,<3.1
 django_polymorphic>=2.1,<2.2
-django-app-helper
diff --git a/tests/requirements/django-3.1.txt b/tests/requirements/django-3.1.txt
--- a/tests/requirements/django-3.1.txt
+++ b/tests/requirements/django-3.1.txt
@@ -2,4 +2,3 @@
 
 django>=3.1,<3.2
 django_polymorphic>=2,<3.1
-django-app-helper
diff --git a/tests/requirements/django-3.2.txt b/tests/requirements/django-3.2.txt
--- a/tests/requirements/django-3.2.txt
+++ b/tests/requirements/django-3.2.txt
@@ -2,4 +2,3 @@
 
 django>=3.2,<4
 django_polymorphic>=2,<3.1
-django-app-helper
diff --git a/tests/requirements/django-4.0.txt b/tests/requirements/django-4.0.txt
--- a/tests/requirements/django-4.0.txt
+++ b/tests/requirements/django-4.0.txt
@@ -2,4 +2,3 @@
 
 django>=4.0,<4.1
 django_polymorphic>=3.1
-https://github.com/jrief/django-app-helper/archive/refs/heads/develop.zip
diff --git a/tests/requirements/django-4.1.txt b/tests/requirements/django-4.1.txt
--- a/tests/requirements/django-4.1.txt
+++ b/tests/requirements/django-4.1.txt
@@ -2,4 +2,3 @@
 
 django>=4.1,<4.2
 django_polymorphic>=3.1
-https://github.com/jrief/django-app-helper/archive/refs/heads/develop.zip
diff --git a/tests/requirements/django-4.2.txt b/tests/requirements/django-4.2.txt
--- a/tests/requirements/django-4.2.txt
+++ b/tests/requirements/django-4.2.txt
@@ -2,4 +2,3 @@
 
 django>=4.2,<5
 django_polymorphic>=3.1
-https://github.com/jrief/django-app-helper/archive/refs/heads/develop.zip
Repository: django-cms/django-filer

Issue:
Field verbose_name should use gettext_lazy
Hi, 
model field verbose_names should use gettext_lazy, because it creates migrations based on user language settings. 

https://github.com/django-cms/django-filer/blob/master/filer/models/foldermodels.py#L9

This is migration generated after upgrade to django-filer 3.0
![image](https://github.com/django-cms/django-filer/assets/10236315/f3cdd97e-dcfe-449b-a928-a574976417da)

Thanks.


Discussion:
Or maybe I am just wrong and it doesn't help, just a guess.
@mihalikv No, you're right.

As a general rule;

`gettext_lazy()` should be used for anything loaded at runtime:
* `models.py` (fields, `verbose_name`, `help_text`, function `short_description`);
* `forms.py` (`labels`, `help_text`, `empty_label`);
* `apps.py` (`verbose_name`).

`gettext()`should be used for any modules that are executed during the request process, such as `views.py`

Resolving patch:
diff --git a/filer/admin/forms.py b/filer/admin/forms.py
--- a/filer/admin/forms.py
+++ b/filer/admin/forms.py
@@ -26,7 +26,7 @@ class CopyFilesAndFoldersForm(forms.Form, AsPWithHelpMixin):
     # overwrite_files = forms.BooleanField(required=False, help_text=_("Overwrite a file if there already exists a file with the same filename?"))
 
     def clean_suffix(self):
-        valid = get_valid_filename(self.cleaned_data['suffix'])
+        valid = get_valid_filename(self.cleaned_data['suffix']) if self.cleaned_data['suffix'] else ""
         if valid != self.cleaned_data['suffix']:
             raise forms.ValidationError(_('Suffix should be a valid, simple and lowercase filename part, like "%(valid)s".') % {'valid': valid})
         return self.cleaned_data['suffix']


Test patch:
Repository: django-cms/django-filer

Issue:
Field verbose_name should use gettext_lazy
Hi, 
model field verbose_names should use gettext_lazy, because it creates migrations based on user language settings. 

https://github.com/django-cms/django-filer/blob/master/filer/models/foldermodels.py#L9

This is migration generated after upgrade to django-filer 3.0
![image](https://github.com/django-cms/django-filer/assets/10236315/f3cdd97e-dcfe-449b-a928-a574976417da)

Thanks.


Discussion:
Or maybe I am just wrong and it doesn't help, just a guess.
@mihalikv No, you're right.

As a general rule;

`gettext_lazy()` should be used for anything loaded at runtime:
* `models.py` (fields, `verbose_name`, `help_text`, function `short_description`);
* `forms.py` (`labels`, `help_text`, `empty_label`);
* `apps.py` (`verbose_name`).

`gettext()`should be used for any modules that are executed during the request process, such as `views.py`

Resolving patch:
diff --git a/filer/__init__.py b/filer/__init__.py
--- a/filer/__init__.py
+++ b/filer/__init__.py
@@ -13,6 +13,4 @@
  8. Publish the release and it will automatically release to pypi
 """
 
-__version__ = '3.0.3'
-
-default_app_config = 'filer.apps.FilerConfig'
+__version__ = '3.0.4'


Test patch: