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

Issue:
Employ HTMX to load job results (scripts/reports)
### Proposed Changes

Employ HTMX to automatically refresh the status of submitted jobs (e.g. the execution of a custom script).

### Justification

This would obviate the need for custom Javascript, and should simplify the job execution workflow.


Discussion:

Resolving patch:
diff --git a/netbox/extras/views.py b/netbox/extras/views.py
--- a/netbox/extras/views.py
+++ b/netbox/extras/views.py
@@ -10,6 +10,7 @@
 
 from netbox.views import generic
 from utilities.forms import ConfirmationForm
+from utilities.htmx import is_htmx
 from utilities.tables import paginate_table
 from utilities.utils import copy_safe_request, count_related, normalize_querydict, shallow_compare_dict
 from utilities.views import ContentTypePermissionRequiredMixin
@@ -693,16 +694,26 @@ def get_required_permission(self):
 
     def get(self, request, job_result_pk):
         report_content_type = ContentType.objects.get(app_label='extras', model='report')
-        jobresult = get_object_or_404(JobResult.objects.all(), pk=job_result_pk, obj_type=report_content_type)
+        result = get_object_or_404(JobResult.objects.all(), pk=job_result_pk, obj_type=report_content_type)
 
         # Retrieve the Report and attach the JobResult to it
-        module, report_name = jobresult.name.split('.')
+        module, report_name = result.name.split('.')
         report = get_report(module, report_name)
-        report.result = jobresult
+        report.result = result
+
+        # If this is an HTMX request, return only the result HTML
+        if is_htmx(request):
+            response = render(request, 'extras/htmx/report_result.html', {
+                'report': report,
+                'result': result,
+            })
+            if result.completed:
+                response.status_code = 286
+            return response
 
         return render(request, 'extras/report_result.html', {
             'report': report,
-            'result': jobresult,
+            'result': result,
         })
 
 
@@ -820,6 +831,16 @@ def get(self, request, job_result_pk):
 
         script = self._get_script(result.name)
 
+        # If this is an HTMX request, return only the result HTML
+        if is_htmx(request):
+            response = render(request, 'extras/htmx/script_result.html', {
+                'script': script,
+                'result': result,
+            })
+            if result.completed:
+                response.status_code = 286
+            return response
+
         return render(request, 'extras/script_result.html', {
             'script': script,
             'result': result,


Test patch:
Repository: netbox-community/netbox

Issue:
Cluster count missing from tenant api output
### NetBox version

3.1.5

### Python version

3.9

### Steps to Reproduce

Assign a Cluster to a Tenant. 
Retrieve Tenant details via API i.e. /api/tenancy/tenants/5/

### Expected Behavior

cluster_count is returned as part of the API response

### Observed Behavior

cluster_count is missing from the API response


Discussion:

Resolving patch:
diff --git a/netbox/tenancy/api/views.py b/netbox/tenancy/api/views.py
--- a/netbox/tenancy/api/views.py
+++ b/netbox/tenancy/api/views.py
@@ -7,7 +7,7 @@
 from tenancy import filtersets
 from tenancy.models import *
 from utilities.utils import count_related
-from virtualization.models import VirtualMachine
+from virtualization.models import VirtualMachine, Cluster
 from . import serializers
 
 
@@ -47,7 +47,8 @@ class TenantViewSet(CustomFieldModelViewSet):
         site_count=count_related(Site, 'tenant'),
         virtualmachine_count=count_related(VirtualMachine, 'tenant'),
         vlan_count=count_related(VLAN, 'tenant'),
-        vrf_count=count_related(VRF, 'tenant')
+        vrf_count=count_related(VRF, 'tenant'),
+        cluster_count=count_related(Cluster, 'tenant')
     )
     serializer_class = serializers.TenantSerializer
     filterset_class = filtersets.TenantFilterSet


Test patch:
Repository: netbox-community/netbox

Issue:
Circuits list view to display formatted commit rate
### NetBox version

3.1.2

### Feature type

Change to existing functionality

### Proposed functionality

The current circuit list view (/circuits/circuits/) has a column called "Commit Rate (kbps) and shows the rate in kbps i.e. 1000000

However when looking at the circuit details, the commit rate is translated into something more human readable i.e 1 Gbps

Proposing either changing the existing Commit Rate (kbps) column to also translate the commit rate or the addition of an extra column simply called Commit Rate that has the human readable version.

### Use case

Easier for non-technical users to quickly see the commit rate of a circuit in the table view. Brings more parity to the circuit details view.

### Database changes

_No response_

### External dependencies

_No response_


Discussion:
> changing the existing Commit Rate (kbps) column to also translate the commit rate

The best way to handle this is probably to introduce a custom column class that displays the human-friendly value on `render()` and the raw number on `values()` (for export).

Resolving patch:
diff --git a/netbox/circuits/tables.py b/netbox/circuits/tables.py
--- a/netbox/circuits/tables.py
+++ b/netbox/circuits/tables.py
@@ -22,11 +22,32 @@
 {% endif %}
 """
 
+#
+# Table columns
+#
+
+
+class CommitRateColumn(tables.TemplateColumn):
+    """
+    Humanize the commit rate in the column view
+    """
+
+    template_code = """
+        {% load helpers %}
+        {{ record.commit_rate|humanize_speed }}
+        """
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(template_code=self.template_code, *args, **kwargs)
+
+    def value(self, value):
+        return str(value) if value else None
 
 #
 # Providers
 #
 
+
 class ProviderTable(BaseTable):
     pk = ToggleColumn()
     name = tables.Column(
@@ -119,6 +140,7 @@ class CircuitTable(BaseTable):
         template_code=CIRCUITTERMINATION_LINK,
         verbose_name='Side Z'
     )
+    commit_rate = CommitRateColumn()
     comments = MarkdownColumn()
     tags = TagColumn(
         url_name='circuits:circuit_list'


Test patch:
Repository: netbox-community/netbox

Issue:
No virtual chassis name in rack view
### NetBox version

v3.1.4

### Python version

3.8

### Steps to Reproduce

1. Create a rack
2. Add 2 devices with no name in rack
3. Create virtual chassis
4. Add devices as member
5. Open rack

### Expected Behavior

The name displayed should be something like [virtual-chassis name]:[virtual-chassis position], like in older versions (before 3.1)

### Observed Behavior

Device Type name is being displayed


Discussion:
This was changed in #8092

Resolving patch:
diff --git a/netbox/dcim/svg.py b/netbox/dcim/svg.py
--- a/netbox/dcim/svg.py
+++ b/netbox/dcim/svg.py
@@ -19,7 +19,12 @@
 
 
 def get_device_name(device):
-    return device.name or str(device.device_type)
+    if device.virtual_chassis:
+        return f'{device.virtual_chassis.name}:{device.vc_position}'
+    elif device.name:
+        return device.name
+    else:
+        return str(device.device_type)
 
 
 class RackElevationSVG:


Test patch:
Repository: netbox-community/netbox

Issue:
Filter view for Locations is missing tags field
### NetBox version

v3.1.5

### Python version

3.8

### Steps to Reproduce

Navigate to Organization -> Locations.
e.g https://demo.netbox.dev/dcim/locations/
and then open the filters tab.

### Expected Behavior

Under the first search field there should be a field for tags to compliment the Location model which was extended to include a tag field.

### Observed Behavior

Other then the missing GUI field for tags, the filtering is working as expected in the background.
Verified by trying https://demo.netbox.dev/dcim/locations/?tag=my-tag


Discussion:

Resolving patch:
diff --git a/netbox/dcim/forms/filtersets.py b/netbox/dcim/forms/filtersets.py
--- a/netbox/dcim/forms/filtersets.py
+++ b/netbox/dcim/forms/filtersets.py
@@ -152,7 +152,7 @@ class SiteFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
 class LocationFilterForm(TenancyFilterForm, CustomFieldModelFilterForm):
     model = Location
     field_groups = [
-        ['q'],
+        ['q', 'tag'],
         ['region_id', 'site_group_id', 'site_id', 'parent_id'],
         ['tenant_group_id', 'tenant_id'],
     ]


Test patch:
Repository: netbox-community/netbox

Issue:
Circuit Install Date set to NULL exports to csv as â€”
### NetBox version

v3.1.6

### Python version

3.9

### Steps to Reproduce

1. Create a circuit with no Install Date
2. Export circuits to CSV
3. Notice Install Date Field value displayed as `â€”`

### Expected Behavior

Install Date shows as NULL or empty

### Observed Behavior

Install Date shows as `â€”`


Discussion:
Weird, I get an emdash symbol (—), which we use as a placeholder in the table. This is still wrong though; it should be null.
HI, I can work on fixing this bug during the weekend. 

Resolving patch:
diff --git a/netbox/utilities/tables.py b/netbox/utilities/tables.py
--- a/netbox/utilities/tables.py
+++ b/netbox/utilities/tables.py
@@ -4,10 +4,13 @@
 from django.contrib.contenttypes.fields import GenericForeignKey
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import FieldDoesNotExist
+from django.db.models import DateField, DateTimeField
 from django.db.models.fields.related import RelatedField
 from django.urls import reverse
+from django.utils.formats import date_format
 from django.utils.safestring import mark_safe
 from django_tables2 import RequestConfig
+from django_tables2.columns import library
 from django_tables2.data import TableQuerysetData
 from django_tables2.utils import Accessor
 
@@ -205,6 +208,42 @@ def value(self, **kwargs):
         return ret
 
 
+@library.register
+class DateColumn(tables.DateColumn):
+    """
+    Overrides the default implementation of DateColumn to better handle null values, returning a default value for
+    tables and null when exporting data. It is registered in the tables library to use this class instead of the
+    default, making this behavior consistent in all fields of type DateField.
+    """
+
+    def value(self, value):
+        return value
+
+    @classmethod
+    def from_field(cls, field, **kwargs):
+        if isinstance(field, DateField):
+            return cls(**kwargs)
+
+
+@library.register
+class DateTimeColumn(tables.DateTimeColumn):
+    """
+    Overrides the default implementation of DateTimeColumn to better handle null values, returning a default value for
+    tables and null when exporting data. It is registered in the tables library to use this class instead of the
+    default, making this behavior consistent in all fields of type DateTimeField.
+    """
+
+    def value(self, value):
+        if value:
+            return date_format(value, format="SHORT_DATETIME_FORMAT")
+        return None
+
+    @classmethod
+    def from_field(cls, field, **kwargs):
+        if isinstance(field, DateTimeField):
+            return cls(**kwargs)
+
+
 class ButtonsColumn(tables.TemplateColumn):
     """
     Render edit, delete, and changelog buttons for an object.


Test patch:
Repository: netbox-community/netbox

Issue:
Bring the ASN Web UI up to the standard set by other objects
### NetBox version

v3.1.6

### Feature type

New functionality

### Proposed functionality

Currently the UI for ASN models is missing a lot of the polish and cross-references one is used to from other objects.

As far as I am concerned the following is missing:

- Tenants in the ASN table are simply the name of the tenant instead of a link to the tenant object
- ASNs can be tagged but the ASN table does not allow to show these tags.
- The description field is not shown by default in the ASN table
- The stats page of the tenant does not show a counter for the ASNs assigned to that tenant

Since all of the above should be pretty easy fixes I will prepare a PR for them.

There are other things that are already fixed in the development version (#8367) or are currently open for discussion (#8445)

### Use case

Making workflows consistent between different objects.

### Database changes

None.

### External dependencies

None.


Discussion:

Resolving patch:
diff --git a/netbox/ipam/tables/ip.py b/netbox/ipam/tables/ip.py
--- a/netbox/ipam/tables/ip.py
+++ b/netbox/ipam/tables/ip.py
@@ -119,15 +119,20 @@ class ASNTable(BaseTable):
         url_params={'asn_id': 'pk'},
         verbose_name='Sites'
     )
+    tenant = TenantColumn()
+    tags = TagColumn(
+        url_name='ipam:asn_list'
+    )
+
     actions = ButtonsColumn(ASN)
 
     class Meta(BaseTable.Meta):
         model = ASN
         fields = (
             'pk', 'asn', 'asn_asdot', 'rir', 'site_count', 'tenant', 'description', 'actions', 'created',
-            'last_updated',
+            'last_updated', 'tags',
         )
-        default_columns = ('pk', 'asn', 'rir', 'site_count', 'sites', 'tenant', 'actions')
+        default_columns = ('pk', 'asn', 'rir', 'site_count', 'sites', 'description', 'tenant', 'actions')
 
 
 #
diff --git a/netbox/tenancy/views.py b/netbox/tenancy/views.py
--- a/netbox/tenancy/views.py
+++ b/netbox/tenancy/views.py
@@ -4,7 +4,7 @@
 
 from circuits.models import Circuit
 from dcim.models import Site, Rack, Device, RackReservation, Cable
-from ipam.models import Aggregate, IPAddress, Prefix, VLAN, VRF
+from ipam.models import Aggregate, IPAddress, Prefix, VLAN, VRF, ASN
 from netbox.views import generic
 from utilities.tables import paginate_table
 from utilities.utils import count_related
@@ -113,6 +113,7 @@ def get_extra_context(self, request, instance):
             'virtualmachine_count': VirtualMachine.objects.restrict(request.user, 'view').filter(tenant=instance).count(),
             'cluster_count': Cluster.objects.restrict(request.user, 'view').filter(tenant=instance).count(),
             'cable_count': Cable.objects.restrict(request.user, 'view').filter(tenant=instance).count(),
+            'asn_count': ASN.objects.restrict(request.user, 'view').filter(tenant=instance).count(),
         }
 
         return {


Test patch:
Repository: netbox-community/netbox

Issue:
Unable to connect a cable from rear ports of a patch panel to a device console port
### NetBox version

3.1.7

### Python version

3.8

### Steps to Reproduce

1. Navigate to a patch panel modelled with front & rear ports. (Tested with a 48 port 8P8C panel).
2. Attempt to connect a cable from a rear port to Console on a device. 
3. No 'Console Port' option appears in the dropdown.

<img width="1289" alt="Screenshot 2022-02-04 at 20 02 01" src="https://user-images.githubusercontent.com/242483/152596229-ef49ac8e-d04a-4ecf-a117-8ee5b2bea405.png">


Note: This works successfully in reverse i.e.
1. Navigate to a Device with a Console Port modelled
2. Connect a cable from a Console Port to a Rear Port on a patch panel / device.

### Expected Behavior

Dropdown menu on the rear of a patch panel allows you to connect a cable to the console port of a device.

### Observed Behavior

No 'Console Port' option appears on the dropdown menu when looking at rear ports of a device. 

E.g. https://demo.netbox.dev/dcim/devices/74/rear-ports/ 


Discussion:

Resolving patch:
diff --git a/netbox/dcim/tables/template_code.py b/netbox/dcim/tables/template_code.py
--- a/netbox/dcim/tables/template_code.py
+++ b/netbox/dcim/tables/template_code.py
@@ -298,6 +298,8 @@
             </button>
             <ul class="dropdown-menu dropdown-menu-end">
                 <li><a class="dropdown-item" href="{% url 'dcim:rearport_connect' termination_a_id=record.pk termination_b_type='interface' %}?return_url={% url 'dcim:device_rearports' pk=object.pk %}">Interface</a></li>
+                <li><a class="dropdown-item" href="{% url 'dcim:rearport_connect' termination_a_id=record.pk termination_b_type='console-server-port' %}?return_url={% url 'dcim:device_rearports' pk=object.pk %}">Console Server Port</a></li>
+                <li><a class="dropdown-item" href="{% url 'dcim:rearport_connect' termination_a_id=record.pk termination_b_type='console-port' %}?return_url={% url 'dcim:device_rearports' pk=object.pk %}">Console Port</a></li>
                 <li><a class="dropdown-item" href="{% url 'dcim:rearport_connect' termination_a_id=record.pk termination_b_type='front-port' %}?return_url={% url 'dcim:device_rearports' pk=object.pk %}">Front Port</a></li>
                 <li><a class="dropdown-item" href="{% url 'dcim:rearport_connect' termination_a_id=record.pk termination_b_type='rear-port' %}?return_url={% url 'dcim:device_rearports' pk=object.pk %}">Rear Port</a></li>
                 <li><a class="dropdown-item" href="{% url 'dcim:rearport_connect' termination_a_id=record.pk termination_b_type='circuit-termination' %}?return_url={% url 'dcim:device_rearports' pk=object.pk %}">Circuit Termination</a></li>


Test patch:
Repository: netbox-community/netbox

Issue:
Banner edit fields should be larger
### NetBox version

v3.1.6

### Feature type

Change to existing functionality

### Proposed functionality

Currently the Login, Top and Bottom banner edit fields in Config revisions are small input fields: they only show a few words at the time. It makes editing the banners somewhat hard.

I propose that the input fields are shown larger, preferably as multi-line input fields, to make it easier to edit the HTML-containing banners.

### Use case

Communicating upcoming maintenances or specific login instructions is easier when the banner input fields are easier to edit.

### Database changes

None

### External dependencies

None


Discussion:

Resolving patch:
diff --git a/netbox/netbox/config/parameters.py b/netbox/netbox/config/parameters.py
--- a/netbox/netbox/config/parameters.py
+++ b/netbox/netbox/config/parameters.py
@@ -20,19 +20,28 @@ def __init__(self, name, label, default, description='', field=None, field_kwarg
         name='BANNER_LOGIN',
         label='Login banner',
         default='',
-        description="Additional content to display on the login page"
+        description="Additional content to display on the login page",
+        field_kwargs={
+            'widget': forms.Textarea(),
+        },
     ),
     ConfigParam(
         name='BANNER_TOP',
         label='Top banner',
         default='',
-        description="Additional content to display at the top of every page"
+        description="Additional content to display at the top of every page",
+        field_kwargs={
+            'widget': forms.Textarea(),
+        },
     ),
     ConfigParam(
         name='BANNER_BOTTOM',
         label='Bottom banner',
         default='',
-        description="Additional content to display at the bottom of every page"
+        description="Additional content to display at the bottom of every page",
+        field_kwargs={
+            'widget': forms.Textarea(),
+        },
     ),
 
     # IPAM


Test patch:
Repository: netbox-community/netbox

Issue:
Contact assignment amounts not shown during contact global search
### NetBox version

v3.1.7

### Python version

3.8

### Steps to Reproduce

1. Search for a name in global search
2. View the "assignments" column


### Expected Behavior

Number of assignments should be shown.

### Observed Behavior

Instead of the number of assignments being shown, a hyphen is displayed instead.


Discussion:

Resolving patch:
diff --git a/netbox/netbox/constants.py b/netbox/netbox/constants.py
--- a/netbox/netbox/constants.py
+++ b/netbox/netbox/constants.py
@@ -18,7 +18,7 @@
 from ipam.models import Aggregate, ASN, IPAddress, Prefix, VLAN, VRF
 from ipam.tables import AggregateTable, ASNTable, IPAddressTable, PrefixTable, VLANTable, VRFTable
 from tenancy.filtersets import ContactFilterSet, TenantFilterSet
-from tenancy.models import Contact, Tenant
+from tenancy.models import Contact, Tenant, ContactAssignment
 from tenancy.tables import ContactTable, TenantTable
 from utilities.utils import count_related
 from virtualization.filtersets import ClusterFilterSet, VirtualMachineFilterSet
@@ -186,7 +186,7 @@
         'url': 'tenancy:tenant_list',
     }),
     ('contact', {
-        'queryset': Contact.objects.prefetch_related('group', 'assignments'),
+        'queryset': Contact.objects.prefetch_related('group', 'assignments').annotate(assignment_count=count_related(ContactAssignment, 'contact')),
         'filterset': ContactFilterSet,
         'table': ContactTable,
         'url': 'tenancy:contact_list',


Test patch:
Repository: netbox-community/netbox

Issue:
Allow specifying an arbitrary path to NetBox's configuration module on init
### NetBox version

v3.1.8

### Feature type

New functionality

### Proposed functionality

Allow NetBox administrators to pass an arbitrary path to the desired configuration module when initializing NetBox. An environment variable should suffice for this.

The current module is hardcoded as `netbox.configuration`, referencing the prescribed configuration file at `${working_dir}/netbox/configuration.py`. We'll retain this as the default path, but defer to the `NETBOX_CONFIGURATION environment variable, if set.

### Use case

This grants NetBox admins additional flexibility in how NetBox is installed and configured. It also simplifies our CI setup slightly.

### Database changes

_No response_

### External dependencies

_No response_


Discussion:

Resolving patch:
diff --git a/netbox/netbox/configuration.example.py b/netbox/netbox/configuration_example.py
similarity index 100%
rename from netbox/netbox/configuration.example.py
rename to netbox/netbox/configuration_example.py
diff --git a/netbox/netbox/settings.py b/netbox/netbox/settings.py
--- a/netbox/netbox/settings.py
+++ b/netbox/netbox/settings.py
@@ -39,12 +39,14 @@
 #
 
 # Import configuration parameters
+config_path = os.getenv('NETBOX_CONFIGURATION', 'netbox.configuration')
 try:
-    from netbox import configuration
+    configuration = importlib.import_module(config_path)
 except ModuleNotFoundError as e:
-    if getattr(e, 'name') == 'configuration':
+    if getattr(e, 'name') == config_path:
         raise ImproperlyConfigured(
-            "Configuration file is not present. Please define netbox/netbox/configuration.py per the documentation."
+            f"Specified configuration module ({config_path}) not found. Please define netbox/netbox/configuration.py "
+            f"per the documentation, or specify an alternate module in the NETBOX_CONFIGURATION environment variable."
         )
     raise
 
@@ -61,9 +63,7 @@
 # Enforce required configuration parameters
 for parameter in ['ALLOWED_HOSTS', 'DATABASE', 'SECRET_KEY', 'REDIS']:
     if not hasattr(configuration, parameter):
-        raise ImproperlyConfigured(
-            "Required parameter {} is missing from configuration.py.".format(parameter)
-        )
+        raise ImproperlyConfigured(f"Required parameter {parameter} is missing from configuration.")
 
 # Set required parameters
 ALLOWED_HOSTS = getattr(configuration, 'ALLOWED_HOSTS')


Test patch:
diff --git a/netbox/netbox/configuration.testing.py b/netbox/netbox/configuration_testing.py
similarity index 100%
rename from netbox/netbox/configuration.testing.py
rename to netbox/netbox/configuration_testing.py