Enzo Yair

feature/organismo parte 1

... ... @@ -24,7 +24,7 @@ logs
# Installer logs
pip-log.txt
# Unit test / coverage reports
# Unit tests / coverage reports
.coverage
.tox
nosetests.xml
... ...
... ... @@ -28,7 +28,7 @@ def create_user(username, first_name='Admin', last_name='Root', email=None):
@pytest.fixture
def get_default_test_user():
test_user = create_user(username='test_user', first_name='Test', last_name='User', email='test@user')
test_user = create_user(username='test_user', first_name='Test', last_name='User', email='tests@user')
return test_user
... ...
from django.contrib import admin
from .models import Organismo, Dependencia
# Register your models here.
@admin.register(Organismo)
class OrganismoAdmin(admin.ModelAdmin):
model = Organismo
list_display = ('id', 'short_name')
list_filter = ('short_name',)
search_fields = ('short_name', )
def has_view_permission(self, request, obj=None):
if obj is not None:
return request.user.has_perm(f'organismo.view_{obj.short_name.lower().replace(" ", "_")}')
return request.user.has_perm('organismo.view_organismo')
def has_add_permission(self, request):
return request.user.has_perm('organismo.create_organismo')
def has_change_permission(self, request, obj=None):
if obj is not None:
return request.user.has_perm(f'organismo.edit_{obj.short_name.lower().replace(" ", "_")}')
return request.user.has_perm('organismo.edit_organismo')
def has_delete_permission(self, request, obj=None):
if obj is not None:
return request.user.has_perm(f'organismo.delete_{obj.short_name.lower().replace(" ", "_")}')
return request.user.has_perm('organismo.delete_organismo')
@admin.register(Dependencia)
class DependenciaAdmin(admin.ModelAdmin):
model = Dependencia
list_display = ('id', 'organismo', 'short_name',)
list_filter = ('organismo', 'short_name',)
search_fields = ('short_name',)
def get_queryset(self, request):
queryset = super().get_queryset(request)
if not request.user.is_superuser:
user_groups = request.user.groups.all()
return queryset
... ...
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from .models import Organismo, Dependencia
from .serializers import OrganismoSerializer, DependenciaSerializer
class OrganismoViewSets(viewsets.ReadOnlyModelViewSet):
queryset = Organismo.objects.all()
serializer_class = OrganismoSerializer
permission_classes = [IsAuthenticated, ]
lookup_field = 'id'
class DependenciaViewSets(viewsets.ReadOnlyModelViewSet):
queryset = Dependencia.objects.all()
serializer_class = DependenciaSerializer
permission_classes = [IsAuthenticated, ]
lookup_field = 'id'
... ...
from django.apps import AppConfig
class OrganismoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'organismo'
... ...
# Generated by Django 4.2.9 on 2024-09-30 15:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Organismo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('short_name', models.CharField(max_length=350, verbose_name='Nombre del organismo')),
],
options={
'verbose_name': 'Organismo',
'verbose_name_plural': 'Organismos',
},
),
migrations.CreateModel(
name='Dependencia',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('short_name', models.CharField(max_length=350, verbose_name='Nombre de la dependencia')),
('organismo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='organismo.organismo')),
],
options={
'verbose_name': 'Dependencia',
'verbose_name_plural': 'Dependencias',
},
),
]
... ...
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
# Create your models here.
class Organismo(models.Model):
class Meta:
verbose_name = 'Organismo'
verbose_name_plural = 'Organismos'
short_name = models.CharField(max_length=350, blank=False, verbose_name='Nombre del organismo')
def __str__(self):
return f'{self.short_name}'
def custom_permission_organismo_create(organismo):
content_type = ContentType.objects.get_for_model(Organismo)
action = 'view'
codename = f'{action}_{organismo.short_name.lower().replace(" ", "_")}'
if not Permission.objects.filter(codename=codename, content_type=content_type).exists():
Permission.objects.create(
codename=codename,
name=f'Can {action} {organismo.short_name}',
content_type=content_type,
)
def custom_permission_organismo_delete(organismo):
content_type = ContentType.objects.get_for_model(Organismo)
action = 'view'
codename = f'{action}_{organismo.short_name.lower().replace(" ", "_")}'
Permission.objects.filter(codename=codename, content_type=content_type).delete()
@receiver(post_save, sender=Organismo)
def manage_organismo_permissions(sender, instance, created, **kwargs):
if created:
custom_permission_organismo_create(instance)
else:
old_instance = Organismo.objects.get(pk=instance.pk)
if old_instance.short_name != instance.short_name:
custom_permission_organismo_create(old_instance)
custom_permission_organismo_delete(instance)
class Dependencia(models.Model):
objects = None
class Meta:
verbose_name = 'Dependencia'
verbose_name_plural = 'Dependencias'
organismo = models.ForeignKey('Organismo', on_delete=models.CASCADE)
short_name = models.CharField(max_length=350, blank=False, verbose_name='Nombre de la dependencia')
def __str__(self):
return f'{self.organismo} - {self.short_name}'
def custom_permission_dependencia_create(dependencia):
content_type = ContentType.objects.get_for_model(dependencia)
action = 'view'
codename = f'{action}_{dependencia.short_name.lower().replace(" ", "_")}'
if not Permission.objects.filter(codename=codename, content_type=content_type).exists():
Permission.objects.create(
codename=codename,
name=f'Can {action} {dependencia.short_name}',
content_type=content_type,
)
def custom_permissions_dependencia_delete(dependencia):
content_type = ContentType.objects.get_for_model(dependencia)
action = 'view'
codename = f'{action}_{dependencia.short_name.lower().replace(" ", "_")}'
Permission.objects.filter(codename=codename, content_type=content_type).delete()
@receiver(post_save, sender=Dependencia)
def manage_dependencia_permissions(sender, instance, created, **kwargs):
if created:
custom_permission_dependencia_create(instance)
else:
old_instance = Organismo.objects.get(pk=instance.pk)
if old_instance.short_name != instance.short_name:
custom_permissions_dependencia_delete(old_instance)
custom_permission_dependencia_create(instance)
\ No newline at end of file
... ...
from rest_framework_json_api import serializers
from .models import Dependencia, Organismo
class OrganismoSerializer(serializers.ModelSerializer):
class Meta:
model = Organismo
fields = serializers.ALL_FIELDS
class DependenciaSerializer(serializers.ModelSerializer):
class Meta:
model = Dependencia
fields = serializers.ALL_FIELDS
\ No newline at end of file
... ...
from django.test import TestCase
# Create your tests here.
... ...
import factory
from factory import SubFactory, faker, django
... ...
from django.shortcuts import render
# Create your views here.
... ...
from rest_framework import routers
from organismo import api as organismo_api
# Define routes
router = routers.DefaultRouter()
router.register(prefix='organismo', viewset=organismo_api.OrganismoViewSets)
router.register(prefix='dependencia', viewset=organismo_api.OrganismoViewSets)
\ No newline at end of file
... ...
... ... @@ -59,6 +59,7 @@ THIRD_PARTY_APPS = (
PROJECT_APPS = (
'core',
'organismo',
)
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS
... ...
... ... @@ -14,8 +14,9 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.urls import path, include, reverse_lazy
from django.conf import settings
from django.views.generic.base import RedirectView
from .router import router
... ... @@ -24,6 +25,7 @@ admin.site.site_header = getattr(settings, 'PROJECT_NAME_HEADER')
admin.site.site_title = getattr(settings, 'PROJECT_NAME_TITLE')
urlpatterns = [
path('', RedirectView.as_view(url=reverse_lazy('admin:index'))),
path('admin/', admin.site.urls),
path('api/v1/', include(router.urls)),
]
... ...