Commit 8a8e8cf6 authored by Florent Chehab's avatar Florent Chehab
Browse files

Merge branch 'frontend' into 'master'

New Frontend initialize

Closes #11

See merge request chehabfl/outgoing_rex!15
parents f7b3fc08 a157cc69
from rest_framework import serializers
from django.utils import timezone
from .pendingModeration import PendingModeration
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from backend.utils import is_member
from .myModel import MyModel
class MyModelSerializer(serializers.ModelSerializer):
moderated_on = serializers.DateTimeField(
format="%Y-%m-%d %H:%M:%S", read_only=True)
updated_on = serializers.DateTimeField(
format="%Y-%m-%d %H:%M:%S", read_only=True)
moderated_by = serializers.CharField(read_only=True)
updated_by = serializers.CharField(read_only=True)
# TODO : updated_by_username useless ? See in rest API
updated_by_username = serializers.SerializerMethodField(read_only=True)
def get_updated_by_username(self, obj):
if obj.updated_by:
return obj.updated_by.username
else:
return None
class Meta:
model = MyModel
def moderation_required(self):
if hasattr(self.Meta, 'NEVER_MODERATE') and self.Meta.NEVER_MODERATE:
return False
user = self.get_user_in_request()
request = self.context['request']
if user.is_staff:
return False
if settings.MODERATION_ACTIVATED:
if request.method in ['POST', 'PUT']: # should be always the case
return not is_member('Moderators', request.user)
return False
def get_user_in_request(self):
return self.context['request'].user
def set_model_attr_no_moder(self, moderated_and_updated):
user = self.get_user_in_request()
now = timezone.now()
self.override_validated_data({
'moderated_by': user,
'moderated_on': now,
})
if moderated_and_updated:
self.override_validated_data({
'updated_by': user,
'updated_on': now,
})
def clean_validated_data(self):
self.override_validated_data({
'moderated_by': None,
'moderated_on': None,
'updated_by': None,
'updated_on': None,
})
def get_pending_models(self):
ct = ContentType.objects.get_for_model(self.Meta.model)
return PendingModeration.objects.filter(
content_type=ct, object_id=self.instance.pk)
def override_validated_data(self, new_data):
"""
Method used to force specific attributes when saving a model
"""
for key in new_data:
self.validated_data[key] = new_data[key]
def my_pre_save(self):
pass
def save(self, **kwargs):
user = self.get_user_in_request()
self.clean_validated_data()
self.my_pre_save()
if self.moderation_required():
if self.instance is None: # we need to create the main model
self.instance = super(
MyModelSerializer, self).save(**kwargs)
objs_pending_db = self.get_pending_models()
self.clean_validated_data() # Make that it is done...
if len(objs_pending_db) > 0:
pending_instance = objs_pending_db[0]
pending_instance.updated_on = timezone.now()
pending_instance.updated_by = user
pending_instance.new_object = self.validated_data
else:
pending_instance = PendingModeration(
referenced_object=self.instance,
updated_by=user,
updated_on=timezone.now(),
new_object=self.validated_data
)
pending_instance.save()
return self.instance
else:
moderated_and_updated = True
if self.instance is None:
self.set_model_attr_no_moder(moderated_and_updated)
return super(MyModelSerializer, self).save(**kwargs)
else:
# We check if we don't have any moderation pending
objs_pending_db = self.get_pending_models()
if len(objs_pending_db) > 0:
obj_pending_db = objs_pending_db[0]
self.clean_validated_data() # Make that it is done...
if obj_pending_db.new_object == self.validated_data:
moderated_and_updated = False
self.validated_data['updated_by'] = obj_pending_db.updated_by
self.validated_data['updated_on'] = obj_pending_db.updated_on
objs_pending_db.delete()
self.set_model_attr_no_moder(moderated_and_updated)
return super(MyModelSerializer, self).save(**kwargs)
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
from backend.signals import new_revision_saved
import reversion
class MyModelVersionned(MyModel):
class Meta:
abstract = True
class MyModelVersionnedSerializer(MyModelSerializer):
def save(self, **kwargs):
# Retrieve the user info from the request
user = self.context['request'].user
with reversion.create_revision():
super(MyModelSerializer, self).save(**kwargs)
reversion.set_user(user)
# Signal save to perform squash of revisions
new_revision_saved.send(sender=self.__class__, obj=self.instance)
class MyModelVersionnedViewSet(MyModelViewSet):
serializer_class = MyModelVersionnedSerializer
from rest_framework import permissions
from .myModelSerializer import MyModelSerializer
from backend.models.tools import NoDeleteIfNotAdmin
from backend.models.tools import DictModeViewSet
class MyModelViewSet(DictModeViewSet):
serializer_class = MyModelSerializer
permission_classes = (
permissions.IsAuthenticated,
NoDeleteIfNotAdmin,
)
def get_queryset(self):
"""
Extended default rest framework behavior
to prefetch some table and enhance performances
"""
self.mymodel_queryset = self.queryset.prefetch_related(
'moderated_by', 'updated_by')
return self.extend_queryset()
def extend_queryset(self):
"""
Function to extend get_queryset when subclassing
"""
return self.mymodel_queryset
from django.db import models
from rest_framework import serializers, viewsets, permissions
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.postgres.fields import JSONField
from django.contrib.auth.models import User
class PendingModeration(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.CharField(max_length=100) # 100 should be ok
referenced_object = GenericForeignKey('content_type', 'object_id')
updated_by = models.ForeignKey(User, on_delete=models.CASCADE)
updated_on = models.DateTimeField(null=True)
new_object = JSONField(default={})
class Meta:
unique_together = ('content_type', 'object_id')
class PendingModerationSerializer(serializers.ModelSerializer):
class Meta:
model = PendingModeration
fields = '__all__'
class PendingModerationViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAdminUser,)
queryset = PendingModeration.objects.all() # pylint: disable=E1101
serializer_class = PendingModerationSerializer
from django.db import models
from rest_framework import serializers, viewsets, permissions
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
from rest_framework import permissions
class Department(models.Model):
class Department(MyModel):
code = models.CharField(primary_key=True, max_length=6)
name = models.CharField(max_length=100)
active = models.BooleanField()
class DepartmentSerializer(serializers.ModelSerializer):
class DepartmentSerializer(MyModelSerializer):
class Meta:
model = Department
fields = '__all__'
class DepartmentViewSet(viewsets.ModelViewSet):
class DepartmentViewSet(MyModelViewSet):
permission_classes = (permissions.IsAdminUser,)
queryset = Department.objects.all() # pylint: disable=E1101
serializer_class = DepartmentSerializer
from django.db import models
from rest_framework import serializers, viewsets, permissions
from rest_framework import permissions
from backend.models.university import University
from backend.models.otherCore import Semester, Specialty
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
class Offer(models.Model):
class Offer(MyModel):
semester = models.ForeignKey(Semester, on_delete=models.PROTECT)
university = models.ForeignKey(University, on_delete=models.PROTECT)
......@@ -20,13 +21,13 @@ class Offer(models.Model):
unique_together = ('semester', 'university')
class OfferSerializer(serializers.ModelSerializer):
class OfferSerializer(MyModelSerializer):
class Meta:
model = Offer
fields = '__all__'
class OfferViewSet(viewsets.ModelViewSet):
class OfferViewSet(MyModelViewSet):
permission_classes = (permissions.IsAdminUser,)
queryset = Offer.objects.all() # pylint: disable=E1101
serializer_class = OfferSerializer
from django.db import models
from rest_framework import serializers, viewsets, permissions
from rest_framework import permissions
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
class Semester(models.Model):
class Semester(MyModel):
code = models.CharField(primary_key=True, max_length=6)
class SemesterSerializer(serializers.ModelSerializer):
class SemesterSerializer(MyModelSerializer):
class Meta:
model = Semester
fields = '__all__'
class SemesterViewSet(viewsets.ModelViewSet):
class SemesterViewSet(MyModelViewSet):
permission_classes = (permissions.IsAdminUser,)
queryset = Semester.objects.all() # pylint: disable=E1101
serializer_class = SemesterSerializer
from django.db import models
from rest_framework import serializers, viewsets, permissions
from rest_framework import permissions
from backend.models.otherCore import Department
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
class Specialty(models.Model):
class Specialty(MyModel):
code = models.CharField(max_length=6)
department = models.ForeignKey(Department, on_delete=models.PROTECT)
name = models.CharField(max_length=100)
......@@ -14,13 +15,13 @@ class Specialty(models.Model):
# TODO add documentation : you should add departement.
class SpecialtySerializer(serializers.ModelSerializer):
class SpecialtySerializer(MyModelSerializer):
class Meta:
model = Specialty
fields = '__all__'
class SpecialtyViewSet(viewsets.ModelViewSet):
class SpecialtyViewSet(MyModelViewSet):
permission_classes = (permissions.IsAdminUser,)
queryset = Specialty.objects.all() # pylint: disable=E1101
serializer_class = SpecialtySerializer
from .DictModeViewSet import DictModeViewSet # noqa: F401
from .usefullLinksField import UsefullLinksField # noqa: F401
from .validateWithRestFramework import validate_with_rest_framework # noqa: F401
from .noDeleteIfNotAdmin import NoDeleteIfNotAdmin # noqa: F401
from .isOwner import IsOwner # noqa: F401
from .noDelete import NoDelete # noqa: F401
from rest_framework.permissions import BasePermission
class IsOwner(BasePermission):
def has_object_permission(self, request, view, obj):
if request.user == obj.owner:
return True
else:
return False
from rest_framework.permissions import BasePermission
class NoDelete(BasePermission):
def has_permission(self, request, view):
if request.method == 'DELETE':
return False
return True
from rest_framework.permissions import BasePermission
class NoDeleteIfNotAdmin(BasePermission):
def has_permission(self, request, view):
if (not request.user.is_staff) and request.method == 'DELETE':
return False
return True
from .university import University # noqa: F401
from .campus import Campus, CampusViewSet, CampusSerializer # noqa: F401
from .campus import Campus, CampusViewSet, CampusSerializer, MainCampusViewSet # noqa: F401
from .universityAPI import UniversitySerializer, UniversityViewSet # noqa: F401
from .universityScholarship import UniversityScholarship, UniversityScholarshipViewSet # noqa: F401
from .universityDri import UniversityDri, UniversityDriViewSet # noqa: F401
from .universityInfo import UniversityInfo, UniversityInfoViewSet # noqa: F401
from .universitySemestersDates import UniversitySemestersDates, UniversitySemestersDatesViewSet # noqa: F401
from .universityBasicModules import UniversityInsurance, UniversityInsuranceViewSet # noqa: F401
from .universityBasicModules import UniversityCourses, UniversityCoursesViewSet # noqa: F401
from .universityBasicModules import UniversityCulture, UniversityCultureViewSet # noqa: F401
from .universityBasicModules import UniversityOtherStuff, UniversityOtherStuffViewSet # noqa: F401
from .universityBasicModules import UniversitySpecialOffer, UniversitySpecialOfferViewSet # noqa: F401
from .universityScholarship import UniversityScholarship, UniversityScholarshipSerializer, UniversityScholarshipViewSet # noqa: F401
from .universityDri import UniversityDri, UniversityDriSerializer, UniversityDriViewSet # noqa: F401
from .universityInfo import UniversityInfo, UniversityInfoSerializer, UniversityInfoViewSet # noqa: F401
from .universitySemestersDates import UniversitySemestersDates, UniversitySemestersDatesSerializer, UniversitySemestersDatesViewSet # noqa: F401
from .universityBasicModules import UniversityInsurance, UniversityInsuranceSerializer, UniversityInsuranceViewSet # noqa: F401
from .universityBasicModules import UniversityCourses, UniversityCoursesSerializer, UniversityCoursesViewSet # noqa: F401
from .universityBasicModules import UniversityCulture, UniversityCultureSerializer, UniversityCultureViewSet # noqa: F401
from .universityBasicModules import UniversityOtherStuff, UniversityOtherStuffSerializer, UniversityOtherStuffViewSet # noqa: F401
from .universityBasicModules import UniversitySpecialOffer, UniversitySpecialOfferSerializer, UniversitySpecialOfferViewSet # noqa: F401
from .campusBasicModules import CampusAccommodation, CampusAccommodationViewSet # noqa: F401
from .campusBasicModules import CampusTransport, CampusTransportViewSet # noqa: F401
from .campusBasicModules import CampusCultureAndStudentLife, CampusCultureAndStudentLifeViewSet # noqa: F401
from .campusBasicModules import CampusOtherStuff, CampusOtherStuffViewSet # noqa: F401
from .campusBasicModules import CampusAccommodation, CampusAccommodationSerializer, CampusAccommodationViewSet # noqa: F401
from .campusBasicModules import CampusTransport, CampusTransportSerializer, CampusTransportViewSet # noqa: F401
from .campusBasicModules import CampusCultureAndStudentLife, CampusCultureAndStudentLifeSerializer, CampusCultureAndStudentLifeViewSet # noqa: F401
from .campusBasicModules import CampusOtherStuff, CampusOtherStuffSerializer, CampusOtherStuffViewSet # noqa: F401
from .universityPhoto import UniversityPhoto, UniversityPhotoViewSet # noqa: F401
from .universityPhoto import UniversityPhoto, UniversityPhotoSerializer, UniversityPhotoViewSet # noqa: F401
from .universityModulesAPI import UniversityModulesViewSet # noqa: F401
from django.db import models
from backend.models.module import BasicModule, BasicModuleSerializer
from backend.models.module import BasicModule, BasicModuleSerializer, BasicModuleViewSet
from backend.models.location import City
from backend.models.university import University
from django.core.validators import MinValueValidator, MaxValueValidator
from rest_framework import viewsets, permissions
class Campus(BasicModule):
module_icon = "You forget to override the icon in the sub-class : I know"
module_name = "Campus principal"
module_description = "Campus de l'université."
is_main_campus = models.BooleanField(null=False)
name = models.CharField(max_length=200, null=True)
comment = models.TextField(null=True, blank=True)
city = models.ForeignKey(City, on_delete=models.PROTECT, null=False)
university = models.ForeignKey(
University, on_delete=models.PROTECT, null=False, related_name="univCampus")
University, on_delete=models.PROTECT, null=False, related_name="univ_campus")
lat = models.DecimalField(
max_digits=10,
......@@ -46,7 +42,11 @@ class CampusSerializer(BasicModuleSerializer):
fields = '__all__'
class CampusViewSet(viewsets.ModelViewSet): # TODO switch to dict
permission_classes = (permissions.DjangoModelPermissions,)
class CampusViewSet(BasicModuleViewSet):
queryset = Campus.objects.all() # pylint: disable=E1101
serializer_class = CampusSerializer
class MainCampusViewSet(BasicModuleViewSet):
queryset = Campus.objects.filter(is_main_campus=True)
serializer_class = CampusSerializer
from django.db import models
from backend.models.module import BasicModule
from backend.models.university import Campus
from rest_framework import viewsets, permissions
from backend.models.module import BasicModuleSerializer
from backend.models.module import BasicModule, BasicModuleSerializer, BasicModuleViewSet
####################
# CultureAndStudentLife
......@@ -20,9 +18,7 @@ class CampusCultureAndStudentLifeSerializer(BasicModuleSerializer):
fields = '__all__'
# TODO switch to dict
class CampusCultureAndStudentLifeViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.DjangoModelPermissions,)
class CampusCultureAndStudentLifeViewSet(BasicModuleViewSet):
queryset = CampusCultureAndStudentLife.objects.all() # pylint: disable=E1101
serializer_class = CampusCultureAndStudentLifeSerializer
......@@ -45,8 +41,7 @@ class CampusAccommodationSerializer(BasicModuleSerializer):
fields = '__all__'
class CampusAccommodationViewSet(viewsets.ModelViewSet): # TODO switch to dict
permission_classes = (permissions.DjangoModelPermissions,)
class CampusAccommodationViewSet(BasicModuleViewSet):
queryset = CampusAccommodation.objects.all() # pylint: disable=E1101
serializer_class = CampusAccommodationSerializer
......@@ -69,8 +64,7 @@ class CampusTransportSerializer(BasicModuleSerializer):
fields = '__all__'
class CampusTransportViewSet(viewsets.ModelViewSet): # TODO switch to dict
permission_classes = (permissions.DjangoModelPermissions,)
class CampusTransportViewSet(BasicModuleViewSet):
queryset = CampusTransport.objects.all() # pylint: disable=E1101
serializer_class = CampusTransportSerializer
......@@ -94,8 +88,6 @@ class CampusOtherStuffSerializer(BasicModuleSerializer):
fields = '__all__'
# TODO switch to dict
class CampusOtherStuffViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.DjangoModelPermissions,)
class CampusOtherStuffViewSet(BasicModuleViewSet):
queryset = CampusOtherStuff.objects.all() # pylint: disable=E1101
serializer_class = CampusOtherStuffSerializer
from django.db import models
from backend.models.module import VersionnedModule
from backend.models.my_model import MyModel
from backend.utils.friendly_path import friendly_path
path_and_rename = friendly_path("uploads/universities/logos/", 'name')
class University(VersionnedModule):
class University(MyModel):
"""
Model storing information about universities
"""
......
from backend.models.university import University
from rest_framework import serializers, viewsets, permissions
from backend.models.university.campus import CampusSerializer
from rest_framework import permissions
from backend.models.tools import NoDeleteIfNotAdmin
from backend.models.my_model import MyModelSerializer, MyModelViewSet
class UniversitySerializer(serializers.ModelSerializer):
univCampus = CampusSerializer(many=True, read_only=True)
class UniversitySerializer(MyModelSerializer):
class Meta:
model = University
fields = ('name', 'acronym', 'logo', 'id', 'univCampus')
fields = '__all__'
class UniversityViewSet(viewsets.ModelViewSet): # TODO switch to dict
permission_classes = (permissions.DjangoModelPermissions,)
queryset = University.objects.all() # pylint: disable=E1101
class UniversityViewSet(MyModelViewSet):
serializer_class = UniversitySerializer
permission_classes = (
permissions.IsAuthenticated,
NoDeleteIfNotAdmin,
)
queryset = University.objects.all() # pylint: disable=E1101
from django.db import models
from backend.models.module import BasicModule
from backend.models.module import BasicModule, BasicModuleSerializer, BasicModuleViewSet
from backend.models.university import University
from rest_framework import viewsets, permissions
from backend.models.module import BasicModuleSerializer
####################
# Insurance
......@@ -20,8 +19,7 @@ class UniversityInsuranceSerializer(BasicModuleSerializer):
fields = '__all__'
class UniversityInsuranceViewSet(viewsets.ModelViewSet): # TODO switch to dict
permission_classes = (permissions.DjangoModelPermissions,)
class UniversityInsuranceViewSet(BasicModuleViewSet):
queryset = UniversityInsurance.objects.all() # pylint: disable=E1101
serializer_class = UniversityInsuranceSerializer
......@@ -44,8 +42,7 @@ class UniversityCultureSerializer(BasicModuleSerializer):
fields = '__all__'
class UniversityCultureViewSet(viewsets.ModelViewSet): # TODO switch to dict
permission_classes = (permissions.DjangoModelPermissions,)
class UniversityCultureViewSet(BasicModuleViewSet):
queryset = UniversityCulture.objects.all() # pylint: disable=E1101
serializer_class = UniversityCultureSerializer
......@@ -68,8 +65,7 @@ class UniversityCoursesSerializer(BasicModuleSerializer):
fields = '__all__'
class UniversityCoursesViewSet(viewsets.ModelViewSet): # TODO switch to dict
permission_classes = (permissions.DjangoModelPermissions,)
class UniversityCoursesViewSet(BasicModuleViewSet):