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

Issue:
Bulk edit of models with M2M fields can clear the M2M field
### NetBox version

v3.5.4 and tested on develop

### Python version

3.10

### Steps to Reproduce

1. Create an interface with one or more tagged_vlans.
2. Use bulk edit on the interface to change something unrelated like the speed.
3. Observe the changelog with the tagged_vlans being removed.

### Expected Behavior

The untagged_vlans should remain unchanged if none are selected and set null is unchecked.

### Observed Behavior

The untagged_vlans are removed from the interface.

Caused by https://github.com/netbox-community/netbox/blob/develop/netbox/netbox/views/generic/bulk_views.py#L554-L555
In https://github.com/netbox-community/netbox/commit/41c92483a0b9b820dd0ca0c43c6c6d6e560043ed the truthy check on the m2m queryset was removed. Django querysets evaluate to False if the queryset is empty.


Discussion:
Hello,

I'm facing this issue too... Also and for clarification, you mention the untagged_vlan field (excepted / observed behavior section). However, as you mentioned, this issue occurs with m2m fields, so with tagged_vlans (not untagged_vlan).

My proposal to fix this issue : 

```python
--- a/netbox/netbox/views/generic/bulk_views.py
+++ b/netbox/netbox/views/generic/bulk_views.py
@@ -551,7 +551,7 @@ class BulkEditView(GetReturnURLMixin, BaseMultiObjectView):
             for name, m2m_field in m2m_fields.items():
                 if name in form.nullable_fields and name in nullified_fields:
                     getattr(obj, name).clear()
-                else:
+                elif name in form.changed_data:
                     getattr(obj, name).set(form.cleaned_data[name])

```
@netopsab Would you like to submit a pr?
why not ... :)

Resolving patch:
diff --git a/netbox/netbox/views/generic/bulk_views.py b/netbox/netbox/views/generic/bulk_views.py
--- a/netbox/netbox/views/generic/bulk_views.py
+++ b/netbox/netbox/views/generic/bulk_views.py
@@ -551,7 +551,7 @@ def _update_objects(self, form, request):
             for name, m2m_field in m2m_fields.items():
                 if name in form.nullable_fields and name in nullified_fields:
                     getattr(obj, name).clear()
-                else:
+                elif form.cleaned_data[name]:
                     getattr(obj, name).set(form.cleaned_data[name])
 
             # Add/remove tags


Test patch:
Repository: netbox-community/netbox

Issue:
Usage of Comma in Custom Links not possible
### NetBox version

v3.5.2

### Python version

3.10

### Steps to Reproduce

1. Create Custom Link
2. Enter `https://www.tim-online.nrw.de/tim-online2/?center={{ object.latitude }},{{ object.longitude }}&icon=true` as Link URL

### Expected Behavior

I would expect the comma character in the `center=` parameter to be rendered as a comma (`,`).

### Observed Behavior

The comma gets replaced with `%2C`.
The map service we are using does not show the location because it needs a comma character between longitude and latitude in order to display.


Discussion:
I would be happy to open a PR that's fixing this by adding the comma character to the list of excluded characters for URL safe encoding if this gets accepted.

Resolving patch:
diff --git a/netbox/extras/models/models.py b/netbox/extras/models/models.py
--- a/netbox/extras/models/models.py
+++ b/netbox/extras/models/models.py
@@ -285,7 +285,7 @@ def render(self, context):
         text = clean_html(text, allowed_schemes)
 
         # Sanitize link
-        link = urllib.parse.quote(link, safe='/:?&=%+[]@#')
+        link = urllib.parse.quote(link, safe='/:?&=%+[]@#,')
 
         # Verify link scheme is allowed
         result = urllib.parse.urlparse(link)


Test patch:
Repository: netbox-community/netbox

Issue:
Interface Bulk edit fails if vlan_group is set to null
### NetBox version

v3.5.6

### Python version

3.8

### Steps to Reproduce

1. Select multiple Interfaces and click on Edit below the list.
2. Activate `Set Null` for the `802.1Q Switching`>` VLAN group` option
3. Click on save

### Expected Behavior

There is no `Set Null` option as the group is used for filtering only or at least no error is raised.

### Observed Behavior

 Server Error  is raised.
```
<class 'AttributeError'>

'NoneType' object has no attribute 'null'

Python version: 3.8.10
NetBox version: 3.5.6
```


Discussion:

Resolving patch:
diff --git a/netbox/dcim/forms/bulk_edit.py b/netbox/dcim/forms/bulk_edit.py
--- a/netbox/dcim/forms/bulk_edit.py
+++ b/netbox/dcim/forms/bulk_edit.py
@@ -1259,8 +1259,8 @@ class InterfaceBulkEditForm(
     )
     nullable_fields = (
         'module', 'label', 'parent', 'bridge', 'lag', 'speed', 'duplex', 'mac_address', 'wwn', 'vdcs', 'mtu', 'description',
-        'poe_mode', 'poe_type', 'mode', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power',
-        'vlan_group', 'untagged_vlan', 'tagged_vlans', 'vrf', 'wireless_lans'
+        'poe_mode', 'poe_type', 'mode', 'rf_channel', 'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'untagged_vlan',
+        'tagged_vlans', 'vrf', 'wireless_lans'
     )
 
     def __init__(self, *args, **kwargs):


Test patch:
Repository: netbox-community/netbox

Issue:
Content-Types only fetchable as logged in user
### NetBox version

v3.5.6

### Python version

3.11

### Steps to Reproduce

Config settings:
```
LOGIN_REQUIRED = False
EXEMPT_VIEW_PERMISSIONS = ["*"]
```

Try to access `/api/extras/content-types/`

### Expected Behavior

List of content types is returned.

### Observed Behavior

`{"detail":"Authentication credentials were not provided."}`

This view only uses `IsAuthenticated` while other views use `IsAuthenticatedOrLoginNotRequired`, which I believe is what should be used for `ContentTypeViewSet` as well.


Discussion:
> This view only uses IsAuthenticated while other views use IsAuthenticatedOrLoginNotRequired, which I believe is what should be used for ContentTypeViewSet as well.

Seems right on the money. Would you like to submit a PR?
> > This view only uses IsAuthenticated while other views use IsAuthenticatedOrLoginNotRequired, which I believe is what should be used for ContentTypeViewSet as well.
> 
> Seems right on the money. Would you like to submit a PR?

Sure! I'll put one up today or tomorrow!

Resolving patch:
diff --git a/netbox/extras/api/views.py b/netbox/extras/api/views.py
--- a/netbox/extras/api/views.py
+++ b/netbox/extras/api/views.py
@@ -6,7 +6,6 @@
 from rest_framework.decorators import action
 from rest_framework.exceptions import PermissionDenied
 from rest_framework.generics import RetrieveUpdateDestroyAPIView
-from rest_framework.permissions import IsAuthenticated
 from rest_framework.renderers import JSONRenderer
 from rest_framework.response import Response
 from rest_framework.routers import APIRootView
@@ -381,7 +380,7 @@ class ContentTypeViewSet(ReadOnlyModelViewSet):
     """
     Read-only list of ContentTypes. Limit results to ContentTypes pertinent to NetBox objects.
     """
-    permission_classes = (IsAuthenticated,)
+    permission_classes = [IsAuthenticatedOrLoginNotRequired]
     queryset = ContentType.objects.order_by('app_label', 'model')
     serializer_class = serializers.ContentTypeSerializer
     filterset_class = filtersets.ContentTypeFilterSet


Test patch:
Repository: netbox-community/netbox

Issue:
Script Rest API has no results
### NetBox version

v3.5.6

### Python version

3.11

### Steps to Reproduce

As reported in #13061 not only the UI had this issue but the Rest API too.

1. Save this script into a file called bug.py
```
from extras.scripts import *


class Bug13061(Script):

    class Meta:
        name = "Demo for Bug13061"
        description = "Demo for Bug13061"

    def run(self, data, commit):
        self.log_success(f"Demo for Bug13061")
```
2. Go to https://netbox.example.com/extras/scripts/add/
3. Upload the bug.py file.
4. Got to https://netbox.example.com/extras/scripts/bug/Bug13061/
5. Click on Run Script
6. Go to https://netbox.example.com/api/extras/scripts/bug.Bug13061/

### Expected Behavior

The `result` should be job result like in the reports endpoint.

### Observed Behavior

It is always `null`.

The [job.name](https://github.com/netbox-community/netbox/blob/develop/netbox/extras/api/views.py#L293C13-L293C21) is just the name of the script class. When search for the result the [script.name](https://github.com/netbox-community/netbox/blob/develop/netbox/extras/api/views.py#L306C41-L306C52)
is used and not the `class_name` therefore no results are found, unless the `name` ist set to the same value as the `class_name`.


Discussion:

Resolving patch:
diff --git a/netbox/extras/api/views.py b/netbox/extras/api/views.py
--- a/netbox/extras/api/views.py
+++ b/netbox/extras/api/views.py
@@ -303,7 +303,7 @@ def list(self, request):
 
         # Attach Job objects to each script (if any)
         for script in script_list:
-            script.result = results.get(script.name, None)
+            script.result = results.get(script.class_name, None)
 
         serializer = serializers.ScriptSerializer(script_list, many=True, context={'request': request})
 
@@ -314,7 +314,7 @@ def retrieve(self, request, pk):
         object_type = ContentType.objects.get(app_label='extras', model='scriptmodule')
         script.result = Job.objects.filter(
             object_type=object_type,
-            name=script.name,
+            name=script.class_name,
             status__in=JobStatusChoices.TERMINAL_STATE_CHOICES
         ).first()
         serializer = serializers.ScriptDetailSerializer(script, context={'request': request})


Test patch:
Repository: netbox-community/netbox

Issue:
add formatted speed column to interface lists
### NetBox version

v3.5.4

### Feature type

New functionality

### Proposed functionality

I propose adding a new column `Speed` to `InterfaceTable` that would show interface speed but formatted the same way it is shown on interface details view. This column would be added in addition of existing column `Speed (kbps)`. 

It would not be shown by default. Users could choose the column to be shown to show speed ether in kbps as now or shown formatted as 10 Gbps... 


### Use case

Currently it is difficult to determine if a speed is set to 1G, 10G or 100G without carefully counting if there are 6, 7 or 8 zeroes after 1. 

![image](https://github.com/netbox-community/netbox/assets/1256843/66b5d6c2-7a4d-4232-917f-7d99a100031d)

With this change:

![image](https://github.com/netbox-community/netbox/assets/1256843/8d2013f8-a694-42aa-9a8d-1d6d0074462c)


### Database changes

None

### External dependencies

None


Discussion:
Just to reiterate, this would introduce a _new_ column, leaving the current column in place. The existing column works better for programmatic consumption; the new column better serves human readability.
That is correct. 

I can take this if it's OK, as I already have the modifications made locally.


Resolving patch:
diff --git a/netbox/dcim/tables/devices.py b/netbox/dcim/tables/devices.py
--- a/netbox/dcim/tables/devices.py
+++ b/netbox/dcim/tables/devices.py
@@ -545,6 +545,11 @@ class InterfaceTable(ModularDeviceComponentTable, BaseInterfaceTable, PathEndpoi
         }
     )
     mgmt_only = columns.BooleanColumn()
+    speed_formatted = columns.TemplateColumn(
+        template_code='{% load helpers %}{{ value|humanize_speed }}',
+        accessor=Accessor('speed'),
+        verbose_name='Speed'
+    )
     wireless_link = tables.Column(
         linkify=True
     )
@@ -568,7 +573,7 @@ class Meta(DeviceComponentTable.Meta):
         model = models.Interface
         fields = (
             'pk', 'id', 'name', 'device', 'module_bay', 'module', 'label', 'enabled', 'type', 'mgmt_only', 'mtu',
-            'speed', 'duplex', 'mode', 'mac_address', 'wwn', 'poe_mode', 'poe_type', 'rf_role', 'rf_channel',
+            'speed', 'speed_formatted', 'duplex', 'mode', 'mac_address', 'wwn', 'poe_mode', 'poe_type', 'rf_role', 'rf_channel',
             'rf_channel_frequency', 'rf_channel_width', 'tx_power', 'description', 'mark_connected', 'cable',
             'cable_color', 'wireless_link', 'wireless_lans', 'link_peer', 'connection', 'tags', 'vdcs', 'vrf', 'l2vpn',
             'ip_addresses', 'fhrp_groups', 'untagged_vlan', 'tagged_vlans', 'created', 'last_updated',


Test patch:
Repository: netbox-community/netbox

Issue:
Reports: Status is "Completed" even if the Report contains failure messages
### NetBox version

v3.5.7

### Python version

3.9

### Steps to Reproduce

1. Create a Report which logs a failure, 
Example report file 'report_status_test.py':
```
from extras.reports import Report

class TestReportStatus(Report):
    description = "test report status"

    def test_report_status(self):
        self.log_info(None, "info")
        self.log_success(None, "check passed")
        self.log_failure(None, "check failed")
```

2. Add the report module to netbox
3. Go the "Reports" and run the Report
4. Check the Report Status/Results

### Expected Behavior

If a Report contains failure messages, I would expect the Report status to be "Failed". (as it was the case with older Netbox versions)

### Observed Behavior

The Report status is "Completed" instead of "Failed"
At first sight it looks to the user as if the report is successful.
![grafik](https://github.com/netbox-community/netbox/assets/123580173/faba50dc-1106-4dc1-96ee-956cd5f420cc)



Discussion:

Resolving patch:
diff --git a/netbox/extras/reports.py b/netbox/extras/reports.py
--- a/netbox/extras/reports.py
+++ b/netbox/extras/reports.py
@@ -214,20 +214,18 @@ def run(self, job):
                 self.active_test = method_name
                 test_method = getattr(self, method_name)
                 test_method()
+            job.data = self._results
             if self.failed:
                 self.logger.warning("Report failed")
-                job.status = JobStatusChoices.STATUS_FAILED
+                job.terminate(status=JobStatusChoices.STATUS_FAILED)
             else:
                 self.logger.info("Report completed successfully")
-                job.status = JobStatusChoices.STATUS_COMPLETED
+                job.terminate()
         except Exception as e:
             stacktrace = traceback.format_exc()
             self.log_failure(None, f"An exception occurred: {type(e).__name__}: {e} <pre>{stacktrace}</pre>")
             logger.error(f"Exception raised during report execution: {e}")
             job.terminate(status=JobStatusChoices.STATUS_ERRORED)
-        finally:
-            job.data = self._results
-            job.terminate()
 
         # Perform any post-run tasks
         self.post_run()


Test patch:
Repository: netbox-community/netbox

Issue:
The Add Tags field in the bulk edit form is not limited by the object types setting on the tag
### NetBox version

v3.6.0-beta1

### Python version

3.10

### Steps to Reproduce

1. Create a tag `tag1` with the object types set to DCIM > Device
2. Create a site `site1`
3. Edit site1 and observe that the tags list does not contain `tag1`
4. Go to the site list, select the checkbox to the left of `site1` and press `Edit Selected`
5. Open the `Add tags` or `Remove tags` select field

### Expected Behavior

The select field should not contain `tag1`

### Observed Behavior

The select field contains `tag1`

The implementation just looks at the name of the field, which doesn't work as the names of the fields are `add_tags` and `remove_tags`:

https://github.com/netbox-community/netbox/pull/12982/files#diff-e5b671e6922772660da9b89ea1d237483d2ebbd9bec451079b32fa22b09b8840R38-R39

Also, I don't believe that the bulk edit form inherits from `NetBoxModelForm` so the code is not touched anyway.


Discussion:

Resolving patch:
diff --git a/netbox/netbox/forms/base.py b/netbox/netbox/forms/base.py
--- a/netbox/netbox/forms/base.py
+++ b/netbox/netbox/forms/base.py
@@ -127,6 +127,11 @@ def __init__(self, *args, **kwargs):
 
         self.fields['pk'].queryset = self.model.objects.all()
 
+        # Restrict tag fields by model
+        ct = ContentType.objects.get_for_model(self.model)
+        self.fields['add_tags'].widget.add_query_param('for_object_type_id', ct.pk)
+        self.fields['remove_tags'].widget.add_query_param('for_object_type_id', ct.pk)
+
         self._extend_nullable_fields()
 
     def _get_form_field(self, customfield):


Test patch:
Repository: netbox-community/netbox

Issue:
add route-target to csv import from vrfs
### NetBox version

v3.4.2

### Feature type

New functionality

### Proposed functionality

add route-target to csv import from vrfs

### Use case

possibilty to import vrfs with import / export route targets from csv

### Database changes

i think not necessary, objects are there

### External dependencies

no debendencies


Discussion:
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. NetBox is governed by a small group of core maintainers which means not all opened issues may receive direct feedback. **Do not** attempt to circumvent this process by "bumping" the issue; doing so will result in its immediate closure and you may be barred from participating in any future discussions. Please see our [contributing guide](https://github.com/netbox-community/netbox/blob/develop/CONTRIBUTING.md).

Resolving patch:
diff --git a/netbox/ipam/forms/bulk_import.py b/netbox/ipam/forms/bulk_import.py
--- a/netbox/ipam/forms/bulk_import.py
+++ b/netbox/ipam/forms/bulk_import.py
@@ -1,7 +1,6 @@
 from django import forms
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ValidationError
-from django.db.models import Q
 from django.utils.translation import gettext as _
 
 from dcim.models import Device, Interface, Site
@@ -10,7 +9,9 @@
 from ipam.models import *
 from netbox.forms import NetBoxModelImportForm
 from tenancy.models import Tenant
-from utilities.forms.fields import CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, SlugField
+from utilities.forms.fields import (
+    CSVChoiceField, CSVContentTypeField, CSVModelChoiceField, CSVModelMultipleChoiceField, SlugField
+)
 from virtualization.models import VirtualMachine, VMInterface
 
 __all__ = (
@@ -41,10 +42,25 @@ class VRFImportForm(NetBoxModelImportForm):
         to_field_name='name',
         help_text=_('Assigned tenant')
     )
+    import_targets = CSVModelMultipleChoiceField(
+        queryset=RouteTarget.objects.all(),
+        required=False,
+        to_field_name='name',
+        help_text=_('Import route targets')
+    )
+    export_targets = CSVModelMultipleChoiceField(
+        queryset=RouteTarget.objects.all(),
+        required=False,
+        to_field_name='name',
+        help_text=_('Export route targets')
+    )
 
     class Meta:
         model = VRF
-        fields = ('name', 'rd', 'tenant', 'enforce_unique', 'description', 'comments', 'tags')
+        fields = (
+            'name', 'rd', 'tenant', 'enforce_unique', 'description', 'import_targets', 'export_targets', 'comments',
+            'tags',
+        )
 
 
 class RouteTargetImportForm(NetBoxModelImportForm):


Test patch:
Repository: netbox-community/netbox

Issue:
"Add child interface" button should inherit VDC from parent
### NetBox version

v3.4.5

### Feature type

Change to existing functionality

### Proposed functionality

When using the "add child interface" button, either from an interface or a table of interfaces from a device or VDC, the form should be prefilled with the VDC(s) of the parent interface, if any.

### Use case

It seems rather unlikely that if a parent interface is already in a VDC the child interface would not also be in the same VDC, so this should save clicks in the vast majority of cases.

### Database changes

None

### External dependencies

_No response_


Discussion:
@jeremystretch - What's the best way to do this? Are we doing it anywhere else for other many to many fields? If we want to built it into the template, we need to generate the following in the url:

`vdcs=1&vdcs=2&vcds=3` from the many to many field. 

I guess we could do a loop in the template to built it or a templatetag.
I don't have a great answer for the "how." Seems like it would be messy to implement in the template alone.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. NetBox is governed by a small group of core maintainers which means not all opened issues may receive direct feedback. **Do not** attempt to circumvent this process by "bumping" the issue; doing so will result in its immediate closure and you may be barred from participating in any future discussions. Please see our [contributing guide](https://github.com/netbox-community/netbox/blob/develop/CONTRIBUTING.md).

Resolving patch:
diff --git a/netbox/dcim/forms/model_forms.py b/netbox/dcim/forms/model_forms.py
--- a/netbox/dcim/forms/model_forms.py
+++ b/netbox/dcim/forms/model_forms.py
@@ -1042,6 +1042,9 @@ class InterfaceForm(InterfaceCommonForm, ModularDeviceComponentForm):
         queryset=VirtualDeviceContext.objects.all(),
         required=False,
         label='Virtual Device Contexts',
+        initial_params={
+            'interfaces': '$parent',
+        },
         query_params={
             'device_id': '$device',
         }


Test patch:
Repository: netbox-community/netbox

Issue:
Custom Fields omitted from Import "Field Options" Table if UI Visibility set to 'Hidden (if unset)'
### NetBox version

v3.5.7

### Python version

3.9

### Steps to Reproduce

1. Take any Custom Field object and change the UI Visibility to 'Hidden (if unset)
2. Go to a mass import page, eg https://{netbox-host}/circuits/circuits/import/
3. Observe the lack of presence for said Custom Field object in the Field Options table

### Expected Behavior

Expect the Custom Fields to be present in the Field Options table to aid in crafting CSV's with required formatting.

### Observed Behavior

CF options are omitted from the Field Objects table, and so you generally need to gather requisite information in a roundabout manner.
Export creates fields as Label Value, so you generally still need to parse CF's for the right Import formatting; can be a nuisance.

We like the newer capability of hiding unused fields from UI, but we have less skilled users using Netbox and so hope an exception can be made here for restoration of CF visibility in Import scenarios.


Discussion:

Resolving patch:
diff --git a/netbox/netbox/forms/base.py b/netbox/netbox/forms/base.py
--- a/netbox/netbox/forms/base.py
+++ b/netbox/netbox/forms/base.py
@@ -78,7 +78,10 @@ class NetBoxModelImportForm(CSVModelForm, NetBoxModelForm):
 
     def _get_custom_fields(self, content_type):
         return CustomField.objects.filter(content_types=content_type).filter(
-            ui_visibility=CustomFieldVisibilityChoices.VISIBILITY_READ_WRITE
+            ui_visibility__in=[
+                CustomFieldVisibilityChoices.VISIBILITY_READ_WRITE,
+                CustomFieldVisibilityChoices.VISIBILITY_HIDDEN_IFUNSET,
+            ]
         )
 
     def _get_form_field(self, customfield):


Test patch: