Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fixes #12110] Resources API always include link #12123

Merged
merged 1 commit into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions geonode/base/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ def to_representation(self, instance):
path = f"{path}/"
url = urljoin(path, str(instance.pk))
data["link"] = build_absolute_uri(url)
logger.warning(
f"Deprecated: BaseDynamicModelSerializer should be replaced with proper Field - Root: {type(self).__name__}"
)
except (TypeError, NoReverseMatch) as e:
logger.exception(e)
return data
Expand Down Expand Up @@ -268,7 +271,7 @@ def __init__(self, **kwargs):
def get_attribute(self, instance):
try:
logger.info(
"This field is deprecated, and will be removed in the future GeoNode version. Please refer to download_urls"
f"Field {self.field_name} is deprecated and will be removed in the future GeoNode version. Please refer to download_urls"
)
_instance = instance.get_real_instance()
return _instance.download_url if hasattr(_instance, "download_url") else None
Expand Down Expand Up @@ -325,6 +328,21 @@ def get_attribute(self, instance):
return False


class AutoLinkField(DynamicComputedField):

def get_attribute(self, instance):
try:
path = reverse(self.root.Meta.view_name)
if not path.endswith("/"):
path = f"{path}/"
url = urljoin(path, str(instance.pk))
return build_absolute_uri(url)

except Exception as e:
logger.exception(e)
return None


class ContactRoleField(DynamicComputedField):
default_error_messages = {
"required": ("ContactRoleField This field is required."),
Expand Down Expand Up @@ -492,7 +510,7 @@ def to_representation(self, instance):
return ret


class ResourceBaseSerializer(BaseDynamicModelSerializer):
class ResourceBaseSerializer(DynamicModelSerializer):
pk = serializers.CharField(read_only=True)
uuid = serializers.CharField(read_only=True)
resource_type = serializers.CharField(required=False)
Expand Down Expand Up @@ -574,6 +592,7 @@ class ResourceBaseSerializer(BaseDynamicModelSerializer):
linked_resources = DynamicRelationField(
LinkedResourceEmbeddedSerializer, source="id", deferred=True, required=False, read_only=True
)
link = AutoLinkField(read_only=True)

class Meta:
model = ResourceBase
Expand Down Expand Up @@ -656,6 +675,7 @@ class Meta:
"favorite",
"thumbnail_url",
"links",
"link",
# TODO
# csw_typename, csw_schema, csw_mdsource, csw_insert_date, csw_type, csw_anytext, csw_wkt_geometry,
# metadata_uploaded, metadata_uploaded_preserve, metadata_xml,
Expand Down
13 changes: 10 additions & 3 deletions geonode/base/api/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2516,15 +2516,22 @@ def test_exclude_all_but_one(self):
(map, "maps-detail"),
):
for viewname in (typed_viewname, "base-resources-detail"):
for field in ("pk", "title", "perms", "links", "linked_resources", "data"): # test some random fields
for field in (
"pk",
"title",
"perms",
"links",
"linked_resources",
"data",
"link",
): # test some random fields
url = reverse(viewname, args=[resource.id])
url = f"{url}?exclude[]=*&include[]={field}"
response = self.client.get(url, format="json").json()
json = next(iter(response.values()))

self.assertIn(field, json, "Missing content")
self.assertIn("link", json, "Missing content")
self.assertEqual(2, len(json), f"Only expected content was '{field}', found: {json}")
self.assertEqual(1, len(json), f"Only expected content was '{field}', found: {json}")

def test_api_should_return_all_resources_for_admin(self):
"""
Expand Down
16 changes: 15 additions & 1 deletion geonode/people/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,26 @@


class UserSerializer(base_serializers.BaseDynamicModelSerializer):

link = base_serializers.AutoLinkField(read_only=True)

class Meta:
ref_name = "UserProfile"
model = get_user_model()
name = "user"
view_name = "users-list"
fields = ("pk", "username", "first_name", "last_name", "avatar", "perms", "is_superuser", "is_staff", "email")
fields = (
"pk",
"username",
"first_name",
"last_name",
"avatar",
"perms",
"is_superuser",
"is_staff",
"email",
"link",
)

@staticmethod
def password_validation(password_payload):
Expand Down
Loading