Commit 69b66577 authored by Florent Chehab's avatar Florent Chehab

Removed my_validate from django models, make use of super instead

parent 9a61b32d
...@@ -38,14 +38,17 @@ class BasicModuleSerializer(MyModelVersionnedSerializer): ...@@ -38,14 +38,17 @@ class BasicModuleSerializer(MyModelVersionnedSerializer):
Custom serializer that performs checks on the Basic module filed Custom serializer that performs checks on the Basic module filed
""" """
def my_validate(self, attrs): def validate(self, attrs):
""" """
Checks that the useful_links have been filled properly Checks that the useful_links have been filled properly
""" """
attrs = super().validate(attrs)
content = {"useful_links": attrs["useful_links"]} content = {"useful_links": attrs["useful_links"]}
config = {"useful_links": USEFULL_LINKS_CONFIG} config = {"useful_links": USEFULL_LINKS_CONFIG}
validate_content_against_config(config, content) validate_content_against_config(config, content)
return attrs return attrs
class Meta: class Meta:
......
...@@ -6,6 +6,7 @@ from backend_app.permissions import is_moderation_required ...@@ -6,6 +6,7 @@ from backend_app.permissions import is_moderation_required
from backend_app.utils import get_user_level from backend_app.utils import get_user_level
from rest_framework import serializers from rest_framework import serializers
from rest_framework.validators import ValidationError from rest_framework.validators import ValidationError
from shared.obj_moderation_permission import DEFAULT_OBJ_MODERATION_LV
from .myModel import MyModel from .myModel import MyModel
from .pendingModeration import PendingModeration, PendingModerationSerializer from .pendingModeration import PendingModeration, PendingModerationSerializer
...@@ -88,42 +89,42 @@ class MyModelSerializer(MySerializerWithJSON): ...@@ -88,42 +89,42 @@ class MyModelSerializer(MySerializerWithJSON):
class Meta: class Meta:
model = MyModel model = MyModel
def my_validate(self, attrs):
"""
Function to be redefined in the subclasses to validate class fields.
"""
return attrs
def validate(self, attrs): def validate(self, attrs):
""" """
Validate `MyModel` fields and enforce certain field at the backend level. Validate `MyModel` fields and enforce certain field at the backend level.
TODO unit test this TODO unit test this
""" """
# Enforce fields values based on request
self.user = self.context["request"].user
self.user_level = get_user_level(self.user)
if "obj_moderation_level" in attrs: if "obj_moderation_level" in attrs:
requested_obj_moder_lv = attrs["obj_moderation_level"] requested_obj_moder_lv = attrs["obj_moderation_level"]
if requested_obj_moder_lv > self.user_level: try:
user = self.context["request"].user
user_level = get_user_level(user)
except KeyError:
# if for some reason we don't have the user in the request
# we set the level to the default one
# this can occur during testing.
user_level = DEFAULT_OBJ_MODERATION_LV
if requested_obj_moder_lv > user_level:
raise ValidationError( raise ValidationError(
"You can't request moderation for a higher rank than you." "You can't request moderation for a higher rank than you."
) )
return self.my_validate(attrs) return attrs
def set_model_attr_no_moder(self, moderated_and_updated): def set_model_attr_no_moder(self, user, moderated_and_updated):
""" """
TODO TODO
TODO: rename ? TODO: rename ?
""" """
now = timezone.now() now = timezone.now()
self.override_validated_data({"moderated_by": self.user, "moderated_on": now}) self.override_validated_data({"moderated_by": user, "moderated_on": now})
if moderated_and_updated: if moderated_and_updated:
self.override_validated_data({"updated_by": self.user, "updated_on": now}) self.override_validated_data({"updated_by": user, "updated_on": now})
def clean_validated_data(self): def clean_validated_data(self):
""" """
...@@ -156,16 +157,20 @@ class MyModelSerializer(MySerializerWithJSON): ...@@ -156,16 +157,20 @@ class MyModelSerializer(MySerializerWithJSON):
Function that handles all the moderation in a smart way. Function that handles all the moderation in a smart way.
Nothing has to be done to tell that we won't the data to be moderated, it is detected automatically. Nothing has to be done to tell that we won't the data to be moderated, it is detected automatically.
""" """
user = self.context["request"].user
user_level = get_user_level(user)
self.clean_validated_data() self.clean_validated_data()
self.my_pre_save() self.my_pre_save()
ct = ContentType.objects.get_for_model(self.Meta.model) ct = ContentType.objects.get_for_model(self.Meta.model)
if is_moderation_required( if is_moderation_required(
self.get_model_config(), self.instance, self.user, self.user_level self.get_model_config(), self.instance, user, user_level
): ):
if self.instance is None: # we need to create the main model if self.instance is None: # we need to create the main model
# Store the user for squashing data in versions models # Store the user for squashing data in versions models
self.validated_data.updated_by = self.user self.validated_data.updated_by = user
self.instance = super().save(*args, **kwargs) self.instance = super().save(*args, **kwargs)
data_to_save = dict() data_to_save = dict()
...@@ -185,7 +190,7 @@ class MyModelSerializer(MySerializerWithJSON): ...@@ -185,7 +190,7 @@ class MyModelSerializer(MySerializerWithJSON):
object_id=self.instance.pk, object_id=self.instance.pk,
defaults={ defaults={
"updated_on": timezone.now(), "updated_on": timezone.now(),
"updated_by": self.user, "updated_by": user,
"new_object": data_to_save, "new_object": data_to_save,
}, },
) )
...@@ -195,7 +200,7 @@ class MyModelSerializer(MySerializerWithJSON): ...@@ -195,7 +200,7 @@ class MyModelSerializer(MySerializerWithJSON):
moderated_and_updated = True moderated_and_updated = True
if self.instance is None: if self.instance is None:
self.set_model_attr_no_moder(moderated_and_updated) self.set_model_attr_no_moder(user, moderated_and_updated)
return super().save(*args, **kwargs) return super().save(*args, **kwargs)
else: else:
try: try:
...@@ -221,5 +226,5 @@ class MyModelSerializer(MySerializerWithJSON): ...@@ -221,5 +226,5 @@ class MyModelSerializer(MySerializerWithJSON):
except PendingModeration.DoesNotExist: except PendingModeration.DoesNotExist:
pass pass
self.set_model_attr_no_moder(moderated_and_updated) self.set_model_attr_no_moder(user, moderated_and_updated)
return super().save(*args, **kwargs) return super().save(*args, **kwargs)
...@@ -55,11 +55,13 @@ class ScholarshipSerializer(BasicModuleSerializer): ...@@ -55,11 +55,13 @@ class ScholarshipSerializer(BasicModuleSerializer):
FORCE_FULL_DISPLAY = True FORCE_FULL_DISPLAY = True
def my_validate(self, attrs): def validate(self, attrs):
""" """
Custom attribute validation Custom attribute validation
""" """
attrs = super(ScholarshipSerializer, self).my_validate(attrs)
attrs = super().validate(attrs)
if attrs["amount_min"] is not None: if attrs["amount_min"] is not None:
if attrs["currency"] is None: if attrs["currency"] is None:
raise serializers.ValidationError( raise serializers.ValidationError(
......
...@@ -29,7 +29,9 @@ class TaggedItemSerializer(BasicModuleSerializer): ...@@ -29,7 +29,9 @@ class TaggedItemSerializer(BasicModuleSerializer):
FORCE_FULL_DISPLAY = True FORCE_FULL_DISPLAY = True
def my_validate(self, attrs): def validate(self, attrs):
attrs = super().validate(attrs)
tagged_item_validation(attrs) tagged_item_validation(attrs)
return attrs return attrs
......
...@@ -37,8 +37,8 @@ class UniversitySemestersDates(BasicModule): ...@@ -37,8 +37,8 @@ class UniversitySemestersDates(BasicModule):
class UniversitySemestersDatesSerializer(BasicModuleSerializer): class UniversitySemestersDatesSerializer(BasicModuleSerializer):
def my_validate(self, attrs): def validate(self, attrs):
attrs = super(UniversitySemestersDatesSerializer, self).my_validate(attrs) attrs = super().validate(attrs)
s_b, s_e = attrs["spring_begin"], attrs["spring_end"] s_b, s_e = attrs["spring_begin"], attrs["spring_end"]
a_b, a_e = attrs["autumn_begin"], attrs["autumn_end"] a_b, a_e = attrs["autumn_begin"], attrs["autumn_end"]
......
...@@ -19,8 +19,8 @@ class ScholarshipTestCase(TestCase): ...@@ -19,8 +19,8 @@ class ScholarshipTestCase(TestCase):
with pytest.raises(ValidationError): with pytest.raises(ValidationError):
attrs["amount_min"] = 200 attrs["amount_min"] = 200
attrs["amount_max"] = 100 attrs["amount_max"] = 100
ser.my_validate(attrs) ser.validate(attrs)
attrs["amount_min"] = 100 attrs["amount_min"] = 100
attrs["amount_max"] = 200 attrs["amount_max"] = 200
ser.my_validate(attrs) ser.validate(attrs)
...@@ -16,11 +16,11 @@ class SemesterDatesTestCase(TestCase): ...@@ -16,11 +16,11 @@ class SemesterDatesTestCase(TestCase):
def _test_attrs_error(attrs): def _test_attrs_error(attrs):
with pytest.raises(ValidationError): with pytest.raises(ValidationError):
self.ser.my_validate(attrs) self.ser.validate(attrs)
self.ser = UniversitySemestersDatesSerializer() self.ser = UniversitySemestersDatesSerializer()
_test_attrs_error(build([None, 3, None, None])) _test_attrs_error(build([None, 3, None, None]))
_test_attrs_error(build([2, 3, 3, 2])) _test_attrs_error(build([2, 3, 3, 2]))
self.ser.my_validate(build([None] * 4)) self.ser.validate(build([None] * 4))
self.ser.my_validate(build([2, 3, None, None])) self.ser.validate(build([2, 3, None, None]))
self.ser.my_validate(build([2, 3, 2, 3])) self.ser.validate(build([2, 3, 2, 3]))
...@@ -2,7 +2,7 @@ from .__is_member import is_member ...@@ -2,7 +2,7 @@ from .__is_member import is_member
from shared import OBJ_MODERATION_PERMISSIONS from shared import OBJ_MODERATION_PERMISSIONS
def get_user_level(user): def get_user_level(user) -> int:
""" """
TODO unit test TODO unit test
""" """
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment