internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: netbox-community/netbox

Issue:
Circuit Providers filter prefiled with Site
The Circuit Providers search filter should be blank by default.

### Environment
* Python version:  3.5.3
* NetBox version:  2.5.7

### Steps to Reproduce
1. Go to Organization > Sites and make sure that there is at least one site registered
2. Go to Circuits > Providers

### Expected Behavior
The search form should be blank by default.

### Observed Behavior
The search form input field for 'Site' show you the name of the site that comes first alphabetically. This issue seems to have some similarity to issue #2912.


Discussion:
Took a look at this, and there are a couple ways this could be fixed:

* Add null_label='' to the FilterChoiceField
* Change it to a APIMultipleSelect

When looking at this, I also found a few forms that aren't using Select2.



Resolving patch:
diff --git a/netbox/circuits/forms.py b/netbox/circuits/forms.py
--- a/netbox/circuits/forms.py
+++ b/netbox/circuits/forms.py
@@ -107,7 +107,7 @@ class ProviderFilterForm(BootstrapMixin, CustomFieldFilterForm):
     site = FilterChoiceField(
         queryset=Site.objects.all(),
         to_field_name='slug',
-        widget=APISelect(
+        widget=APISelectMultiple(
             api_url="/api/dcim/sites/",
             value_field="slug",
         )


Test patch:
Repository: netbox-community/netbox

Issue:
Natural ordering of device components broken
### Environment
* Python version: 3.5.2
* NetBox version: 2.5.11

### Steps to Reproduce
1. Create a device with 48 power outlets named `A[A-C][1-16]` (48 total)
2. View the device

### Expected Behavior
The outlets should be listed in natural order (AA1, AA2, ... AA12, AB1, ...).

### Observed Behavior
The outlets are listed in an apparently random order. This was caused by the replacement of DeviceComponentManager with NaturalOrderingManager in #2986. The root issue is that device components such as PowerOutlet do not specify `Meta.ordering` on the model and thus are not being ordered.


Discussion:

Resolving patch:
diff --git a/netbox/netbox/settings.py b/netbox/netbox/settings.py
--- a/netbox/netbox/settings.py
+++ b/netbox/netbox/settings.py
@@ -22,7 +22,7 @@
     )
 
 
-VERSION = '2.5.11'
+VERSION = '2.5.12'
 
 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
diff --git a/netbox/utilities/managers.py b/netbox/utilities/managers.py
--- a/netbox/utilities/managers.py
+++ b/netbox/utilities/managers.py
@@ -37,4 +37,8 @@ def get_queryset(self):
             else:
                 ordering.append(field)
 
+        # Default to using the _nat indexes if Meta.ordering is empty
+        if not ordering:
+            ordering = ('_nat1', '_nat2', '_nat3')
+
         return queryset.order_by(*ordering)


Test patch:
Repository: netbox-community/netbox

Issue:
Unable to find interfaces when attempting to connect a cable in 2.6-beta1
<!--
    NOTE: This form is only for reproducible bugs. If you need assistance with
    NetBox installation, or if you have a general question, DO NOT open an
    issue. Instead, post to our mailing list:

        https://groups.google.com/forum/#!forum/netbox-discuss

    Please describe the environment in which you are running NetBox. Be sure
    that you are running an unmodified instance of the latest stable release
    before submitting a bug report.
-->
### Environment
* Python version:  3.6.8
* NetBox version:  2.6-beta1

<!--
    Describe in detail the exact steps that someone else can take to reproduce
    this bug using the current stable release of NetBox (or the current beta
    release where applicable). Begin with the creation of any necessary
    database objects and call out every operation being performed explicitly.
    If reporting a bug in the REST API, be sure to reconstruct the raw HTTP
    request(s) being made: Don't rely on a wrapper like pynetbox.
-->
### Steps to Reproduce
1. Create two interfaces
2. Start creating a connection from one of them
3. Try to select the second one from the Name dropdown

<!-- What did you expect to happen? -->
### Expected Behavior

The available interfaces are listed for selection

<!-- What happened instead? -->
### Observed Behavior

A 400 error is received with the message;
```json
{
  "type": [
    "Select a valid choice. physical is not one of the available choices."
  ]
}
```


Discussion:

Resolving patch:
diff --git a/netbox/dcim/forms.py b/netbox/dcim/forms.py
--- a/netbox/dcim/forms.py
+++ b/netbox/dcim/forms.py
@@ -2680,7 +2680,7 @@ class ConnectCableToInterfaceForm(ConnectCableToDeviceForm):
             api_url='/api/dcim/interfaces/',
             disabled_indicator='cable',
             additional_query_params={
-                'type': 'physical',
+                'kind': 'physical',
             }
         )
     )


Test patch:
Repository: netbox-community/netbox

Issue:
Unable to connect cable to rear port in 2.6-beta1
<!--
    NOTE: This form is only for reproducible bugs. If you need assistance with
    NetBox installation, or if you have a general question, DO NOT open an
    issue. Instead, post to our mailing list:

        https://groups.google.com/forum/#!forum/netbox-discuss

    Please describe the environment in which you are running NetBox. Be sure
    that you are running an unmodified instance of the latest stable release
    before submitting a bug report.
-->
### Environment
* Python version: 3.6.8
* NetBox version: 2.6-beta1

<!--
    Describe in detail the exact steps that someone else can take to reproduce
    this bug using the current stable release of NetBox (or the current beta
    release where applicable). Begin with the creation of any necessary
    database objects and call out every operation being performed explicitly.
    If reporting a bug in the REST API, be sure to reconstruct the raw HTTP
    request(s) being made: Don't rely on a wrapper like pynetbox.
-->
### Steps to Reproduce
1. Create a device with rear (and front) ports
2. Create an interface
3. Try to start a connection from the interface to a rear port

<!-- What did you expect to happen? -->
### Expected Behavior

The cable connection dialog displays and allows setting up the connection

<!-- What happened instead? -->
### Observed Behavior

The system throws a KeyError in `/netbox/netbox/dcim/views.py in dispatch`, line 1741


Discussion:

Resolving patch:
diff --git a/netbox/dcim/views.py b/netbox/dcim/views.py
--- a/netbox/dcim/views.py
+++ b/netbox/dcim/views.py
@@ -1736,6 +1736,7 @@ def dispatch(self, request, *args, **kwargs):
             'power-outlet': forms.ConnectCableToPowerOutletForm,
             'interface': forms.ConnectCableToInterfaceForm,
             'front-port': forms.ConnectCableToFrontPortForm,
+            'rear-port': forms.ConnectCableToRearPortForm,
             'power-feed': forms.ConnectCableToPowerFeedForm,
             'circuit-termination': forms.ConnectCableToCircuitTerminationForm,
         }[termination_b_type_name]


Test patch:
Repository: netbox-community/netbox

Issue:
Search enhancement
* NetBox version: 2.5.11

Hello

In the rack section, when filtering by site, is it possible to present in the rack group drop down menu, only possible selection and not all the possible rack groups of all sites?

In the attached example, Filter is on Equinix PA6 site and drop down menu for rack group let me see Equinix PA6, Equinix PA7 and other sites.

![search-example](https://user-images.githubusercontent.com/25366020/58699900-f4676900-839e-11e9-907b-f5024fc50ee4.png)


Best regards,Alex


Discussion:
This is a fairly simple change, just need the filter_for.

Resolving patch:
diff --git a/netbox/dcim/forms.py b/netbox/dcim/forms.py
--- a/netbox/dcim/forms.py
+++ b/netbox/dcim/forms.py
@@ -601,12 +601,18 @@ class RackFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm):
         widget=APISelectMultiple(
             api_url="/api/dcim/sites/",
             value_field="slug",
+            filter_for={
+                'group_id': 'site'
+            }
         )
     )
-    group_id = FilterChoiceField(
-        queryset=RackGroup.objects.select_related('site'),
+
+    group_id = ChainedModelChoiceField(
         label='Rack group',
-        null_label='-- None --',
+        queryset=RackGroup.objects.select_related('site'),
+        chains=(
+            ('site', 'site'),
+        ),
         widget=APISelectMultiple(
             api_url="/api/dcim/rack-groups/",
             null_option=True,


Test patch:
Repository: netbox-community/netbox

Issue:
Interface Connections view inaccessible with "dcim.view_interface" permission
### Environment
* Python version: 3.6.8
* NetBox version: 2.6.1

### Steps to Reproduce
1. Create user with `dcim.view_interface` permission and login.
2. Navigate to Devices → Interface Connections.

### Expected Behavior
Interface Connections view is shown.

### Observed Behavior
"403 Forbidden" is shown. The required permission is `dcim.interface`, it should be `dcim.view_interface`. Let me know if I should submit PR.


Discussion:

Resolving patch:
diff --git a/netbox/dcim/views.py b/netbox/dcim/views.py
--- a/netbox/dcim/views.py
+++ b/netbox/dcim/views.py
@@ -1903,7 +1903,7 @@ def queryset_to_csv(self):
 
 
 class InterfaceConnectionsListView(PermissionRequiredMixin, ObjectListView):
-    permission_required = 'dcim.interface'
+    permission_required = 'dcim.view_interface'
     queryset = Interface.objects.select_related(
         'device', 'cable', '_connected_interface__device'
     ).filter(


Test patch:
Repository: netbox-community/netbox

Issue:
API Exception with invalid choice value
### Environment
* Python version:  3.5.2
* NetBox version:  2.6.2

### Steps to Reproduce

Pass a list instead of an integer for interface type when creating an interface, e.g. `[32767]` instead of `32767`

See [forum thread](https://groups.google.com/forum/#!topic/netbox-discuss/H7xIrwVnOSM)

### Expected Behavior

Value to be rejected by API as invalid

### Observed Behavior

Exception with backtrace - makes it very hard to know where the data error was.

This is because a list is not hashable, and so the test `if data not in self._choices:` raises an exception. [Code link](https://github.com/netbox-community/netbox/blob/develop/netbox/utilities/api.py#L104)




Discussion:

Resolving patch:
diff --git a/netbox/utilities/api.py b/netbox/utilities/api.py
--- a/netbox/utilities/api.py
+++ b/netbox/utilities/api.py
@@ -85,9 +85,9 @@ def to_representation(self, obj):
 
     def to_internal_value(self, data):
 
-        # Provide an explicit error message if the request is trying to write a dict
-        if type(data) is dict:
-            raise ValidationError('Value must be passed directly (e.g. "foo": 123); do not use a dictionary.')
+        # Provide an explicit error message if the request is trying to write a dict or list
+        if isinstance(data, (dict, list)):
+            raise ValidationError('Value must be passed directly (e.g. "foo": 123); do not use a dictionary or list.')
 
         # Check for string representations of boolean/integer values
         if hasattr(data, 'lower'):
@@ -101,10 +101,13 @@ def to_internal_value(self, data):
                 except ValueError:
                     pass
 
-        if data not in self._choices:
-            raise ValidationError("{} is not a valid choice.".format(data))
+        try:
+            if data in self._choices:
+                return data
+        except TypeError:  # Input is an unhashable type
+            pass
 
-        return data
+        raise ValidationError("{} is not a valid choice.".format(data))
 
     @property
     def choices(self):


Test patch:
Repository: netbox-community/netbox

Issue:
SCRIPTS_ROOT is missing in  configuration.example.py
### Change Type
[x] Addition
[ ] Correction
[ ] Deprecation
[ ] Cleanup (formatting, typos, etc.)

### Proposed Changes
Add new SCRIPTS_ROOT variable to configuration.example.py


Discussion:

Resolving patch:
diff --git a/netbox/netbox/configuration.example.py b/netbox/netbox/configuration.example.py
--- a/netbox/netbox/configuration.example.py
+++ b/netbox/netbox/configuration.example.py
@@ -154,6 +154,10 @@
 # this setting is derived from the installed location.
 # REPORTS_ROOT = '/opt/netbox/netbox/reports'
 
+# The file path where custom scripts will be stored. A trailing slash is not needed. Note that the default value of
+# this setting is derived from the installed location.
+# SCRIPTS_ROOT = '/opt/netbox/netbox/scripts'
+
 # By default, NetBox will store session data in the database. Alternatively, a file path can be specified here to use
 # local file storage instead. (This can be useful for enabling authentication on a standby instance with read-only
 # database access.) Note that the user as which NetBox runs must have read and write permissions to this path.


Test patch:
Repository: netbox-community/netbox

Issue:
circuits.* excluded from Cacheops
<!--
    NOTE: This form is only for reproducible bugs. If you need assistance with
    NetBox installation, or if you have a general question, DO NOT open an
    issue. Instead, post to our mailing list:

        https://groups.google.com/forum/#!forum/netbox-discuss

    Please describe the environment in which you are running NetBox. Be sure
    that you are running an unmodified instance of the latest stable release
    before submitting a bug report.
-->
### Environment
* Python version:  3.6
* NetBox version:  2.6.6

<!--
    Describe in detail the exact steps that someone else can take to reproduce
    this bug using the current stable release of NetBox (or the current beta
    release where applicable). Begin with the creation of any necessary
    database objects and call out every operation being performed explicitly.
    If reporting a bug in the REST API, be sure to reconstruct the raw HTTP
    request(s) being made: Don't rely on a wrapper like pynetbox.
-->
### Steps to Reproduce
1. Fresh install of Netbox 2.6.6
2. Stresstest a single resource under the /circuits/ app (e.g /api/circuits/circuit/123/
3. Notice DB-related respones and no queries to redis

<!-- What did you expect to happen? -->
### Expected Behavior
Circuits should fetch from cache as the other apps are configured to do


<!-- What happened instead? -->
### Observed Behavior
Circuits are limited in DB throughput and don't benefit from lower latency that the cache provides

### Cause
Circuits app is not in the cacheops config
https://github.com/netbox-community/netbox/blob/ae4f17264fcc2a3d3ef7f9bf81a9e1d8ce88878d/netbox/netbox/settings.py#L363


Discussion:
Should we change cacheops config to include `*.*` and only specify the exceptions ? Same way as `auth` is setup currently?

EDIT: not recommended by cacheops per their own documentation:

> Using '*.*' with non-empty ops is not recommended since it will easily cache something you don't intent to or even now about like migrations tables. The better approach will be restricting by app with 'app_name.*'. (https://github.com/Suor/django-cacheops)

Resolving patch:
diff --git a/netbox/netbox/settings.py b/netbox/netbox/settings.py
--- a/netbox/netbox/settings.py
+++ b/netbox/netbox/settings.py
@@ -364,6 +364,7 @@
     'auth.user': {'ops': 'get', 'timeout': 60 * 15},
     'auth.*': {'ops': ('fetch', 'get')},
     'auth.permission': {'ops': 'all'},
+    'circuits.*': {'ops': 'all'},
     'dcim.*': {'ops': 'all'},
     'ipam.*': {'ops': 'all'},
     'extras.*': {'ops': 'all'},


Test patch:
Repository: netbox-community/netbox

Issue:
Only preload selected options for APISelect widgets
### Proposed Changes
Change `APISelect` and `APISelectMultiple` to only preload the selected fields.

### Justification
The current implementation for `APISelect` and `APISelectMultiple` preloads all of the objects of the model. Even though paging of size 50 is performed on the API calls, the page will load with all of the objects, even ignoring what `APISelect` might be filtering out.

For example, all of the roles (11 through 99) are loaded in the device creation page. The APISelect itself paginates correctly, but I presume the default behavior of Django's `forms.Select` is making it so all of the options are loaded (not 100% sure about the last part).

```html
<select name="device_role" class="netbox-select2-api form-control select2-hidden-accessible" data-url="/api/dcim/device-roles/" required="" placeholder="Device role" id="id_device_role" tabindex="-1" aria-hidden="true">
  <option value="" selected="">---------</option>
  <option value="11">role-11</option>
  <option value="12">role-12</option>
  <option value="13">role-13</option>  
...
  <option value="97">role-97</option>
  <option value="98">role-98</option>
  <option value="99">role-99</option>
</select>
```

By preventing those options from being loaded, the pages that use the `APISelect` and/or `APISelectMultiple` would load faster due to smaller pages.

It should be noted that **selected** options must be loaded in order for them to be rendered on the form. It's only the options that aren't selected which can be omitted as they are created dynamically when selected. 


Discussion:

Resolving patch:
diff --git a/netbox/utilities/forms.py b/netbox/utilities/forms.py
--- a/netbox/utilities/forms.py
+++ b/netbox/utilities/forms.py
@@ -285,6 +285,8 @@ class APISelect(SelectWithDisabled):
         name of the query param and the value if the query param's value.
     :param null_option: If true, include the static null option in the selection list.
     """
+    # Only preload the selected option(s); new options are dynamically displayed and added via the API
+    template_name = 'widgets/select_api.html'
 
     def __init__(
         self,


Test patch:
Repository: netbox-community/netbox

Issue:
Enhance SwaggerUI to support NAPALM methods
### Issue type
[X] Feature request

### Environment
* Python version:  3.6
* NetBox version:  2.3.1

### Description
I know how to use the NetBox API directly from the CLI to get info from devices using `NAPALM` (and the works great!).  However, I can't do the same thing in the SwaggerUI and I'm hoping a small change could enable me to do that.

What I'm trying to accomplish is to programatically query the devices I have in NetBox (via `NAPALM`) to see if their `model` matches the `device_type` (or specifically `part_number`) that I have defined in NetBox.  

From what I can tell, `pynetbox` doesn't have this functionalty so I'm trying to use `netbox-pyswagger` (from @jeremyschulman) to accomplish this.  However, that "client" is solely based on the output gathered from `/api/docs/?format=openapi`.

To clarify, under the `dcim` section of Swagger, there is this option:
```
GET /api/dcim/devices/{id}/napalm/
```
And when you expand it, you can only pass the `id` field.

After entering an `id` there and clicking the "Try It Out!" button, I can confirm (with command logging on the device in question) that `NAPALM` **does** connect just fine, but doesn't run anything else (due to not be told otherwise) and then disconnects.

The, the response seen in Swagger is the following:
```
Response Body
{}

Response Code
200
```

I suppose what I'm looking for is the option to pass other `method`s (via Swagger) to get the same information as I can using the CLI.  I hope that makes sense.  If not, let me know and I can try to explain further.


Discussion:

Resolving patch:
diff --git a/netbox/dcim/api/serializers.py b/netbox/dcim/api/serializers.py
--- a/netbox/dcim/api/serializers.py
+++ b/netbox/dcim/api/serializers.py
@@ -370,6 +370,10 @@ def get_config_context(self, obj):
         return obj.get_config_context()
 
 
+class DeviceNAPALMSerializer(serializers.Serializer):
+    method = serializers.DictField()
+
+
 class ConsoleServerPortSerializer(TaggitSerializer, ConnectedEndpointSerializer):
     device = NestedDeviceSerializer()
     cable = NestedCableSerializer(read_only=True)
diff --git a/netbox/dcim/api/views.py b/netbox/dcim/api/views.py
--- a/netbox/dcim/api/views.py
+++ b/netbox/dcim/api/views.py
@@ -358,6 +358,17 @@ def graphs(self, request, pk):
 
         return Response(serializer.data)
 
+    @swagger_auto_schema(
+        manual_parameters=[
+            Parameter(
+                name='method',
+                in_='query',
+                required=True,
+                type=openapi.TYPE_STRING
+            )
+        ],
+        responses={'200': serializers.DeviceNAPALMSerializer}
+    )
     @action(detail=True, url_path='napalm')
     def napalm(self, request, pk):
         """


Test patch:
Repository: netbox-community/netbox

Issue:
No limit on related IP addresses

### Environment
* Python version:  3.6.8
* NetBox version:  2.6.11

### Steps to Reproduce
1. Create IP address in `10/8` space, like `10.1.1.1/8`
2. Repeat step 1 numerous times with a different address each time, but the same mask
3. The list of related IPs for any of those addresses grows with every new related address

### Expected Behavior

The table of related IPs is limited (i.e. a maximum to number of related IPs are displayed). 

### Observed Behavior

The related IPs table is has no bound on its size, which slows down page loading further with every new related IP. 


Discussion:

Resolving patch:
diff --git a/netbox/ipam/views.py b/netbox/ipam/views.py
--- a/netbox/ipam/views.py
+++ b/netbox/ipam/views.py
@@ -686,7 +686,14 @@ def get(self, request, pk):
         ).filter(
             vrf=ipaddress.vrf, address__net_contained_or_equal=str(ipaddress.address)
         )
-        related_ips_table = tables.IPAddressTable(list(related_ips), orderable=False)
+
+        related_ips_table = tables.IPAddressTable(related_ips, orderable=False)
+
+        paginate = {
+            'paginator_class': EnhancedPaginator,
+            'per_page': request.GET.get('per_page', settings.PAGINATE_COUNT)
+        }
+        RequestConfig(request, paginate).configure(related_ips_table)
 
         return render(request, 'ipam/ipaddress.html', {
             'ipaddress': ipaddress,


Test patch: