netbox-community / netbox

The premier source of truth powering network automation. Open source under Apache 2. Try NetBox Cloud free: https://netboxlabs.com/free-netbox-cloud/
http://netboxlabs.com/oss/netbox/
Apache License 2.0
15.79k stars 2.54k forks source link

When inheriting NetBoxModelSerializer without defining an override for the url attribute, an exception is thrown #17492

Closed DanSheps closed 15 hours ago

DanSheps commented 4 days ago

Deployment Type

Self-hosted

NetBox Version

4.1.1

Python Version

3.12

Steps to Reproduce

  1. Create a plugin (per the plugin docs)
  2. Add plugin to NetBox
  3. View plugin's API where url is defined as a field but not overridden

Expected Behavior

url will have a proper link

Observed Behavior

Exception: ImproperlyConfigured at

DanSheps commented 4 days ago

The root cause is by default NetBoxAPIHyperlinkedIdentityField and NetBoxURLHyperlinkedIdentityField use a static definition for the defining the path.

Proposed fix would be to make the following changes:

class NetBoxAPIHyperlinkedIdentityField(BaseNetBoxHyperlinkedIdentityField):

-    def get_view_name(self, app_name, model_name):
-        return f'{app_name}-api:{model_name}-detail'
+    def get_view_name(self, model):
+       return get_viewname(model=model, action='detail', rest_api=True)
class NetBoxURLHyperlinkedIdentityField(BaseNetBoxHyperlinkedIdentityField):

-    def get_view_name(self, app_name, model_name):
-        return f'{app_name}:{model_name}'
+    def get_view_name(self, app_name, model_name):
+       return get_viewname(model=model)
class BaseNetBoxHyperlinkedIdentityField(serializers.HyperlinkedIdentityField):

-        model_name = self.parent.Meta.model._meta.model_name
-        app_name = self.parent.Meta.model._meta.app_label
-        view_name = self.get_view_name(app_name, model_name)
+        view_name = self.get_view_name(obj)