Commit 8792340e authored by Florent Chehab's avatar Florent Chehab

Validation of tagged item almost ok

parent b3952836
Pipeline #26799 passed with stages
in 2 minutes and 11 seconds
......@@ -28,7 +28,6 @@ class Scholarship(BasicModule):
class ScholarshipSerializer(BasicModuleSerializer):
def validate(self, attrs):
print(attrs)
if attrs['amount_max'] < attrs['amount_min']:
raise serializers.ValidationError(
"Amount_max should be greater or equal than amount_min")
......
from rest_framework.validators import ValidationError
def missing_field(field):
return ValidationError("{} : this field is required".format(field))
def check_required(config, content):
for field in config:
if config[field]['required']:
try:
val = content[field]
if type(val) is str:
if len(val) == 0:
raise missing_field(field)
if val is None:
raise missing_field(field)
except KeyError:
raise missing_field(field)
def check_coherence(config, content):
for field in content:
if field not in config:
raise ValidationError(
"{} : this field is not supposed to be there".format(field))
from django.db import models
from backend.models.module import BasicModule, BasicModuleSerializer, BasicModuleViewSet
from .tag import Tag
from .tagged_item_validation import tagged_item_validation
class TaggedItem(BasicModule):
......@@ -11,8 +12,11 @@ class TaggedItem(BasicModule):
class TaggedItemSerializer(BasicModuleSerializer):
pass
def validate(self, attrs):
return tagged_item_validation(attrs)
class TaggedItemViewSet(BasicModuleViewSet):
pass
def extend_queryset(self):
return self.mymodel_queryset.prefetch_related('tag')
from .checks import check_required, check_coherence
from .validators import validate_url, validate_text
def tagged_item_validation(attrs):
tag_config = attrs["tag"].config
sumbitted_content = attrs["custom_content"]
check_coherence(tag_config, sumbitted_content)
check_required(tag_config, sumbitted_content)
# Then, field validation
for field in sumbitted_content:
field_submitted = sumbitted_content[field]
field_config = tag_config[field]
field_type = field_config['type']
if field_type == 'url':
validate_url(field_config, field_submitted)
elif field_type == 'text':
validate_text(field_config, field_submitted)
else:
raise Exception("Dev, you have implement something here...")
return attrs
# my_tag_config = {
# "url": {
# "type": "url",
# "required": True,
# "validators": {
# "extension": ["jpg", "jpeg", "png"]
# },
# },
# "title": {
# "type": "text",
# "required": True,
# "validators": {
# "max_length": 200
# }
# },
# "description": {
# "required": False,
# "type": "text",
# "validators": {
# "max_length": 500
# }
# },
# "licence": {
# "type": "text",
# "required": False,
# "validators": {
# "max_length": 200
# }
# }
# }
from .url import validate_url # noqa: F401
from .text import validate_text # noqa: F401
from rest_framework.validators import ValidationError
def validate_text(config, string):
string = str(string) # might cause error with number ?
try:
validators = config['validators']
for validator in validators:
validator_content = validators[validator]
if validator == 'max_length':
if len(string) > validator_content:
raise ValidationError('Your text is too long !')
else:
raise Exception("Dev, you have implement something here...")
except KeyError:
pass
from django.core.validators import URLValidator
from rest_framework.validators import ValidationError
def validate_extension(allowed_extensions, string):
allowed_extensions = [allowed_extension.lower()
for allowed_extension in allowed_extensions]
try:
if string.split('.')[-1].lower() not in allowed_extensions:
raise ValidationError(
"The file you submitted has an unauthorized extension")
except KeyError:
raise ValidationError("File extension not recognized")
def validate_url(config, string):
string = str(string)
validate = URLValidator(schemes=('http', 'https', 'ftp', 'ftps'))
validate(string)
try:
validators = config['validators']
for validator in validators:
validator_content = validators[validator]
if validator == 'extension':
validate_extension(validator_content, string)
else:
raise Exception("Dev, you have implement something here...")
except KeyError:
pass
......@@ -12,7 +12,6 @@ def validate_with_rest_framework(serializer, value):
if not valid_ser.is_valid():
raise serializers.ValidationError(str(valid_ser.errors))
print(value)
# Also checks that no extra fields were added
if type(value) is not list:
allowed_keys = list(valid_ser.get_fields())
......
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