To dynamically display the field names and their values for each material type in your Vue frontend, you'll need to ensure that your Django REST Framework (DRF) backend properly handles OPTIONS requests and provides the necessary metadata. Additionally, your Vue component should correctly fetch and utilize this metadata to render the fields dynamically.
Here's a comprehensive guide to achieve this:
1. Ensure DRF Handles OPTIONS Requests Correctly
DRF automatically handles OPTIONS requests, providing metadata about the available endpoints and their fields. However, to customize this metadata, especially to include more detailed information like field labels, help texts, and types, you can leverage the CustomMetadata class you've already started.
a. Customizing Metadata
Your CustomMetadata class is set up to extract detailed information about serializers. Ensure it's correctly integrated with your DRF settings.
# backend/apps/archive/metadata.py
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.encoding import force_str
from rest_framework import exceptions, serializers
from rest_framework.metadata import SimpleMetadata
from rest_framework.request import clone_request
from rest_framework.utils.field_mapping import ClassLookupDict
class CustomMetadata(SimpleMetadata):
label_lookup = ClassLookupDict(
{
serializers.Field: "field",
serializers.BooleanField: "boolean",
serializers.CharField: "string",
serializers.UUIDField: "string",
serializers.URLField: "url",
serializers.EmailField: "email",
serializers.RegexField: "regex",
serializers.SlugField: "slug",
serializers.IntegerField: "integer",
serializers.FloatField: "float",
serializers.DecimalField: "decimal",
serializers.DateField: "date",
serializers.DateTimeField: "datetime",
serializers.TimeField: "time",
serializers.DurationField: "duration",
serializers.ChoiceField: "choice",
serializers.MultipleChoiceField: "multiple choice",
serializers.FileField: "file upload",
serializers.ImageField: "image upload",
serializers.ListField: "list",
serializers.DictField: "nested object",
serializers.Serializer: "nested object",
}
)
def determine_metadata(self, request, view):
metadata = {
"name": view.get_view_name(),
"description": view.get_view_description(),
"renders": [renderer.media_type for renderer in view.renderer_classes],
"parses": [parser.media_type for parser in view.parser_classes],
}
if hasattr(view, "get_serializer"):
actions = self.determine_actions(request, view)
if actions:
metadata["actions"] = actions
return metadata
def determine_actions(self, request, view):
actions = {}
for method in {"PUT", "POST", "GET"} & set(view.allowed_methods):
view.request = clone_request(request, method)
try:
if hasattr(view, "check_permissions"):
view.check_permissions(view.request)
if method == "PUT" and hasattr(view, "get_object"):
view.get_object()
except (exceptions.APIException, PermissionDenied, Http404):
pass
else:
serializer = view.get_serializer()
actions[method] = self.get_serializer_info(serializer)
finally:
view.request = request
return actions
def get_serializer_info(self, serializer):
if hasattr(serializer, "child"):
serializer = serializer.child
return {
field_name: self.get_field_info(field)
for field_name, field in serializer.fields.items()
if not isinstance(field, serializers.HiddenField)
}
def get_field_info(self, field):
field_info = {
"type": self.label_lookup.get(type(field), "field"),
"required": getattr(field, "required", False),
}
attrs = [
"read_only",
"label",
"help_text",
"min_length",
"max_length",
"min_value",
"max_value",
"max_digits",
"decimal_places",
]
for attr in attrs:
value = getattr(field, attr, None)
if value is not None and value != "":
field_info[attr] = force_str(value, strings_only=True)
if hasattr(field, "child"):
field_info["child"] = self.get_field_info(field.child)
elif hasattr(field, "fields"):
field_info["children"] = self.get_serializer_info(field)
if (
not field_info.get("read_only")
and not isinstance(field, (serializers.RelatedField, serializers.ManyRelatedField))
and hasattr(field, "choices")
):
field_info["choices"] = [
{"value": choice_value, "display_name": force_str(choice_name, strings_only=True)}
for choice_value, choice_name in field.choices.items()
]
return field_info
b. Integrate CustomMetadata with DRF Settings
Ensure that DRF uses your CustomMetadata class. Update your DRF settings accordingly.
# backend/settings.py
REST_FRAMEWORK = {
# ... other settings ...
'DEFAULT_METADATA_CLASS': 'backend.apps.archive.metadata.CustomMetadata',
# ... other settings ...
}
2. Ensure ViewSets are Configured Correctly
Your ViewSets seem properly set up for read-only operations. Ensure they inherit from the appropriate base classes and that their serializers are correctly defined.
# backend/apps/archive/views.py
from django.db.models import Q
from rest_framework import viewsets
from rest_framework.response import Response
from backend.apps.archive.models import AudioMaterial, ImageMaterial, VideoMaterial
from . import serializers
class BaseMaterialViewSet(viewsets.ReadOnlyModelViewSet):
def get_common_search_lookup(self, common_search_value):
lookup = Q()
for field in self.common_search_fields:
lookup |= Q(**{f"{field}__icontains": common_search_value})
return lookup
def get_queryset(self):
queryset = super().get_queryset()
common_search_query = self.request.GET.get("common_search_query")
if common_search_query:
query_lookup = self.get_common_search_lookup(common_search_query)
queryset = queryset.filter(query_lookup)
return queryset
def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(self.queryset, many=True)
return self.get_paginated_response(serializer.data) if page is not None else Response(serializer.data)
class AudioMaterialViewSet(BaseMaterialViewSet):
queryset = AudioMaterial.objects.all()
serializer_class = serializers.AudioMaterialListSerializer
common_search_fields = ["keywords", "annotation", "persons", "title"]
class ImageMaterialViewSet(BaseMaterialViewSet):
queryset = ImageMaterial.objects.all()
serializer_class = serializers.ImageMaterialListSerializer
common_search_fields = ["keywords", "annotation", "persons", "author"]
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
class VideoMaterialViewSet(BaseMaterialViewSet):
queryset = VideoMaterial.objects.all()
serializer_class = serializers.VideoMaterialListSerializer
common_search_fields = ["keywords", "annotation", "persons", "title", "description"]
3. Update Serializers to Include Necessary Field Information
Ensure your serializers provide all the required fields and any additional metadata if necessary.
# backend/apps/archive/serializers.py
import re
from rest_framework import serializers
from . import models
class BaseMaterialListSerializer(serializers.ModelSerializer):
archive_number = serializers.CharField(label="Архивный номер")
@staticmethod
def get_annotation(instance):
max_tokens = 11
if instance.annotation:
tokens = re.findall(r"\S+", instance.annotation)
annotation = " ".join(tokens[:max_tokens])
annotation += " ..." if len(tokens) > max_tokens else ""
return annotation
return ""
@staticmethod
def get_creation_date(instance):
match instance.creation_date_key:
case models.CreationDateVariant.ONLY_YEAR:
return instance.creation_date.year
case models.CreationDateVariant.MONTH_AND_YEAR:
return instance.creation_date.strftime("%m.%Y")
case models.CreationDateVariant.FULL_DATE:
return instance.creation_date.strftime("%d.%m.%Y")
class ImageMaterialListSerializer(BaseMaterialListSerializer):
class Meta:
model = models.ImageMaterial
fields = ("archive_number", "annotation", "creation_date", "author", "photo_type", "color")
class AudioMaterialListSerializer(BaseMaterialListSerializer):
class Meta:
model = models.AudioMaterial
fields = ("archive_number", "title", "annotation", "performer", "creation_date", "language")
class VideoMaterialListSerializer(BaseMaterialListSerializer):
class Meta:
model = models.VideoMaterial
fields = ("archive_number", "title", "creation_date", "annotation", "roles", "language")
4. Configure URLs and Router
Ensure that your viewsets are registered with the router to handle the API endpoints correctly.
# backend/apps/archive/urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import AudioMaterialViewSet, ImageMaterialViewSet, VideoMaterialViewSet
router = DefaultRouter()
router.register(r'audio-materials', AudioMaterialViewSet, basename='audio-material')
router.register(r'image-materials', ImageMaterialViewSet, basename='image-material')
router.register(r'video-materials', VideoMaterialViewSet, basename='video-material')
urlpatterns = [
path('api/', include(router.urls)),
]
Ensure this urls.py is included in your project's main urls.py.
# backend/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('backend.apps.archive.urls')),
# ... other urls ...
]
5. Frontend: Update the Vue Component to Fetch and Utilize OPTIONS Metadata
Now, update your Vue component to fetch the metadata using the OPTIONS request and utilize it to dynamically render the field names and their values.
a. Update the API Utility Functions
Ensure your API utility functions can handle OPTIONS requests.
// src/api/default_api_promises.js
import api from "@/plugins/axios.js";
function recordBase(method, options) {
const defaultAxios = {
method: method,
...options,
};
return function (params) {
return api({ ...defaultAxios, params });
};
}
export function getRecordList(options) {
return recordBase("get", options);
}
export function getRecordDetail(options) {
return recordBase("get", options);
}
export function getOptions(options) {
return recordBase("options", options);
}
b. Update the Child Component to Fetch Metadata
Assuming you're modifying the DynamicDataList.vue component, update it to fetch the field metadata.
<!-- src/components/DynamicDataList.vue -->
<script setup>
import { ref, onBeforeMount, watch } from 'vue';
import { getOptions } from '@/api/default_api_promises.js';
import { useRoute } from 'vue-router';
const props = defineProps({
items: Array,
materialType: String,
});
const fields = ref({});
const iconMap = {
audio: 'mdi-volume-high',
photo: 'mdi-image-outline',
video: 'mdi-video-outline',
};
const route = useRoute();
const fetchFieldsMetadata = () => {
getOptions({ url: `/api/${props.materialType}-materials/` })
.then(response => {
if (response.data.actions && response.data.actions.GET) {
fields.value = response.data.actions.GET;
}
})
.catch(error => {
console.error('Error fetching field metadata:', error);
});
};
// Fetch metadata when materialType changes
watch(() => props.materialType, () => {
fetchFieldsMetadata();
}, { immediate: true });
</script>
<template>
<v-data-iterator :items="items" class="d-flex justify-center">
<template v-slot:default="{ items }">
<template v-for="(item, index) in items" :key="index">
<div class="item">
<div class="item-icon">
<v-icon size="110" color="primary-violet">
{{ iconMap[props.materialType] || 'mdi-file-document-outline' }}
</v-icon>
</div>
<div class="item-content">
<div v-for="(fieldInfo, key) in fields" :key="key" class="item-field">
<span class="field-label">{{ fieldInfo.label || key }}:</span>
<span class="field-value">
{{
// Use the key to get the value from the item
// Assuming item has a 'raw' attribute containing the data
item[key] || 'N/A'
}}
</span>
</div>
</div>
</div>
</template>
</template>
</v-data-iterator>
</template>
<style scoped lang="scss">
.item {
width: 900px;
padding: 15px;
margin-top: 15px;
margin-bottom: 15px;
border: 1px solid darkgray;
border-radius: 8px;
display: flex;
overflow: hidden;
}
.item-icon {
flex-shrink: 0;
width: 110px;
}
.item-content {
flex-grow: 1;
margin-left: 20px;
overflow: hidden;
}
.item-field {
display: flex;
align-items: center;
margin-bottom: 3px;
line-height: 1.2;
}
.field-label {
flex-shrink: 0;
font-size: 12px;
font-weight: bold;
color: gray;
margin-right: 5px;
}
.field-value {
font-size: 12px;
font-weight: normal;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
c. Update the Parent Component to Pass Items and Material Type
Ensure the parent component correctly passes items and materialType to the DynamicDataList component.
<!-- src/components/ParentComponent.vue -->
<script setup>
import { onBeforeMount, ref } from 'vue';
import { getRecordList, getOptions } from '@/api/default_api_promises.js';
import { useRoute, useRouter } from 'vue-router';
import Paginator from '@/components/common/Paginator.vue';
import DynamicDataList from '@/components/DynamicDataList.vue';
const route = useRoute();
const router = useRouter();
const currentTableTab = ref(route.query.material_type || 'image');
const items = ref([]);
const totalCount = ref(0);
const pageCount = ref(0);
function getItems() {
let urlSearchParams = new URLSearchParams(route.query);
getRecordList({ url: `/api/${currentTableTab.value}-materials/` })({ params: Object.fromEntries(urlSearchParams.entries()) })
.then(response => {
totalCount.value = response.data.count;
items.value = response.data.results;
pageCount.value = Math.ceil(totalCount.value / (parseInt(route.query.page_size) || 10));
})
.catch(error => {
console.error('Error fetching items:', error);
});
}
function updateTab() {
let query = { ...route.query, material_type: currentTableTab.value };
router.push({ name: route.name, query: query, params: { ...route.params } });
}
onBeforeMount(getItems);
</script>
<template>
<v-tabs
v-model="currentTableTab"
align-tabs="center"
color="primary-blue"
@update:model-value="updateTab"
>
<v-tab value="image">Фото</v-tab>
<v-tab value="audio">Фоно</v-tab>
<v-tab value="video">Видео</v-tab>
</v-tabs>
<dynamic-data-list :items="items" :material-type="currentTableTab"/>
<paginator v-if="items.length" :page-count="pageCount"/>
</template>
<style scoped lang="scss">
/* Add any necessary styles */
</style>
6. Testing the Implementation
After setting up the backend and frontend as described:
-
Start the Django Server: Ensure your Django server is running without errors.
python manage.py runserver
-
Start the Vue Development Server: Make sure your Vue application is running.
npm run serve
-
Navigate to the Application: Open your application in the browser and navigate through the different material types (Image, Audio, Video).
-
Inspect Network Requests: Use browser developer tools to inspect the OPTIONS requests made when switching material types. Ensure that the metadata returned includes the necessary field information.
-
Verify Dynamic Rendering: Check that the fields are rendered dynamically based on the metadata fetched. The field labels should correspond to the serializer labels or field names, and the values should display correctly.
7. Additional Enhancements
To further enhance this setup, consider the following:
-
Caching Metadata: Since the metadata for each material type doesn't change frequently, implement caching on the frontend to avoid redundant OPTIONS requests.
-
Error Handling: Improve error handling in your Vue components to provide user feedback when metadata or data fails to load.
-
Pagination Controls: Ensure that your Paginator component correctly interacts with the getItems function to fetch different pages based on user interaction.
-
Styling Enhancements: Adjust the styling in your Vue components to better fit your application's design requirements.
Conclusion
By following the steps outlined above, you enable your Vue frontend to dynamically fetch and display field metadata for different material types from your DRF backend. This approach ensures flexibility and scalability, allowing you to easily add new material types in the future with minimal frontend changes.