Browse Source

Insere btn openapi em detail crud e metadata field no serializer da api

pull/3585/head
LeandroJatai 2 years ago
parent
commit
50951f0687
  1. 19
      sapl/api/core/__init__.py
  2. 12
      sapl/api/core/filters.py
  3. 3
      sapl/base/models.py
  4. 10
      sapl/crud/base.py
  5. 5
      sapl/settings.py
  6. 13
      sapl/templates/crud/detail.html
  7. 12
      sapl/templates/crud/detail_detail.html

19
sapl/api/core/__init__.py

@ -22,6 +22,7 @@ from rest_framework.viewsets import ModelViewSet
from sapl.api.core.filters import SaplFilterSetMixin
from sapl.api.permissions import SaplModelPermissions
from sapl.base.models import Metadata
# ATENÇÃO: MUDANÇAS NO CORE DEVEM SER REALIZADAS COM
# EXTREMA CAUTELA
@ -100,6 +101,7 @@ class SaplApiViewSetConstrutor():
# criada a classe sapl.api.core.serializers.{model}Serializer
class SaplSerializer(_serializer_class):
__str__ = SerializerMethodField()
metadata = SerializerMethodField()
class Meta(_meta_serializer):
if not hasattr(_meta_serializer, 'ref_name'):
@ -114,14 +116,26 @@ class SaplApiViewSetConstrutor():
if not hasattr(_meta_serializer, 'fields'):
fields = '__all__'
elif _meta_serializer.fields != '__all__':
fields = list(
_meta_serializer.fields) + ['__str__', ]
fields = list(_meta_serializer.fields) + [
'__str__', 'metadata']
else:
fields = _meta_serializer.fields
def get___str__(self, obj) -> str:
return str(obj)
def get_metadata(self, obj):
try:
metadata = Metadata.objects.get(
content_type=ContentType.objects.get_for_model(
obj._meta.model),
object_id=obj.id
).metadata
except:
metadata = {}
finally:
return metadata
_meta_filterset = object if not hasattr(
_filterset_class, 'Meta') else _filterset_class.Meta
@ -162,6 +176,7 @@ class SaplApiViewSetConstrutor():
return cls
"""
1. Constroi uma rest_framework.viewsets.ModelViewSet para
todos os models de todas as apps do sapl

12
sapl/api/core/filters.py

@ -1,18 +1,18 @@
from collections import OrderedDict
from django.contrib.postgres.fields.jsonb import JSONField
from django.db.models.fields.files import FileField
from django.template.defaultfilters import capfirst
import django_filters
from django_filters.constants import ALL_FIELDS
from django_filters.filters import CharFilter
from django_filters.filterset import FilterSet
from django_filters.utils import resolve_field, get_all_model_fields
import django_filters
# ATENÇÃO: MUDANÇAS NO CORE DEVEM SER REALIZADAS COM
# EXTREMA CAUTELA E CONSCIENTE DOS IMPACTOS NA API
class SaplFilterSetMixin(FilterSet):
o = CharFilter(method='filter_o')
@ -26,6 +26,12 @@ class SaplFilterSetMixin(FilterSet):
'lookup_expr': 'exact',
},
},
JSONField: {
'filter_class': django_filters.CharFilter,
'extra': lambda f: {
'lookup_expr': 'exact',
},
},
}
def filter_o(self, queryset, name, value):

3
sapl/base/models.py

@ -414,3 +414,6 @@ class Metadata(models.Model):
verbose_name = _('Metadado')
verbose_name_plural = _('Metadados')
unique_together = (('content_type', 'object_id'), )
def __str__(self):
return f'Metadata de {self.content_object}'

10
sapl/crud/base.py

@ -25,7 +25,7 @@ from django.views.generic.list import MultipleObjectMixin
from sapl.crispy_layout_mixin import CrispyLayoutFormMixin, get_field_display
from sapl.crispy_layout_mixin import SaplFormHelper
from sapl.rules import (RP_ADD, RP_CHANGE, RP_DELETE, RP_DETAIL,
RP_LIST)
RP_LIST)
from sapl.utils import normalize
logger = logging.getLogger(settings.BASE_DIR.name)
@ -78,6 +78,7 @@ def make_pagination(index, num_pages):
head = from_to(1, PAGINATION_LENGTH - len(tail) - 1)
return head + [None] + tail
"""
variáveis do crud:
help_topic
@ -360,6 +361,13 @@ class CrudBaseMixin(CrispyLayoutFormMixin):
if self.request.user.has_perm(
self.permission(RP_DELETE)) else ''
@property
def openapi_url(self):
obj = self.crud if hasattr(self, 'crud') else self
o = self.object
url = f'/api/{o._meta.app_label}/{o._meta.model_name}/{o.id}'
return url
def get_template_names(self):
names = super(CrudBaseMixin, self).get_template_names()
names.append("crud/%s.html" %

5
sapl/settings.py

@ -321,7 +321,8 @@ FORM_RENDERER = 'django.forms.renderers.DjangoTemplates'
# suprime texto de ajuda default do django-filter
FILTERS_HELP_TEXT_FILTER = False
LOGGING_CONSOLE_VERBOSE = config('LOGGING_CONSOLE_VERBOSE', cast=bool, default=False)
LOGGING_CONSOLE_VERBOSE = config(
'LOGGING_CONSOLE_VERBOSE', cast=bool, default=False)
LOGGING = {
'version': 1,
@ -372,7 +373,7 @@ LOGGING = {
'propagate': True,
},
'django': {
'handlers': ['applogfile'],
'handlers': ['applogfile'] + ['console_verbose'] if LOGGING_CONSOLE_VERBOSE else [],
'level': 'ERROR',
'propagate': True,
},

13
sapl/templates/crud/detail.html

@ -36,6 +36,7 @@
<div class="editons float-right">
{% block editions %}
{% if view.update_url or view.delete_url %}
<div class="actions btn-group" role="group">
{% if view.update_url %}
<a href="{{ view.update_url }}" class="btn btn-outline-primary">{% trans 'Editar' %}</a>
@ -99,6 +100,18 @@
{% endfor %}
{% endfor %}
{% endblock detail_content %}
<div class="container justify-content-end d-flex">
<div class="actions btn-group" role="group">
<a href="{{ view.openapi_url }}" class="btn btn-sm btn-info py-0">
<small class="text-white">
{% trans 'OpenAPI' %}
</small>
</a>
</div>
</div>
</div>
{% block table_content %}

12
sapl/templates/crud/detail_detail.html

@ -64,6 +64,16 @@
{% endfor %}
{% endblock detail_content %}
<div class="container justify-content-end d-flex">
<div class="actions btn-group" role="group">
<a href="{{ view.openapi_url }}" class="btn btn-sm btn-info py-0">
<small class="text-white">
{% trans 'OpenAPI' %}
</small>
</a>
</div>
</div>
<div class="actions btn-group mb-3" role="group">
{% if view.detail_set_create_url %}
<a href="{{ view.detail_set_create_url }}" class="btn btn-outline-primary">
@ -74,7 +84,7 @@
</div>
<div class="clearfix"></div>
<div class="container-table">
{% if not rows %}
<p>{{ NO_ENTRIES_MSG }}</p>

Loading…
Cancel
Save