Home > Blockchain >  Django Serializer - how to check if a ListField is valid?
Django Serializer - how to check if a ListField is valid?

Time:12-02

I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). I'm working on unit tests to ensure that emails are valid. I'm working with serializers for the first time and I'm trying to move past some issues I've been having.

Functionality: the user enters in a friend's email address. For the purposes of this test, the email address needs to be at least 6 characters long. So something like "[email protected]" (6 char) would be acceptable, but "[email protected]" (5 char) would not be accepted. Users can enter up to 10 emails at a time.

What I'm currently struggling with is what function to use for "is_valid"? I know Django forms has something for this, but I haven't found a satisfactory method for serializers.

Here is what's currently in serializers.py.

from django.core.validators import MinValueValidator, MaxValueValidator
from rest.framework.fields import ListField
from rest.framework import serializers

class EmailList(ListField):
 """Will validate the email input"""

 def to_internal_value(self, data):
 # if the EmailList is not valid, then a ValidationError should be raised--here's where I'm wondering what to put
 raise serializers.ValidationError({"invalid_email": "Email is invalid, please recheck".})

class EmailListSerializer(serializers.Serializer):
"""Serializer for the email list"""
 emails = EmailList(
  required=True
  child=Serializers.CharField(
   validators= [
    MinLengthValidator(6, message="too short"),
    MaxLengthValidator(50, message="too long"),
    ],
   ),
  max_length=10,
  error_messages = ({"invalid_email": "Email is invalid, please recheck."}
 )

Can anyone assist as to what function I should put in the to_internal_value method of the EmailList class to check that the emails are valid?

CodePudding user response:

if you are getting email in list then write for loop to get each mail to validate, in your to_internal_value function write code as below:

from django.core.validators import validate_email
    
def to_internal_value(data):
    for email in data:
        try:
            validate_email(email)
        except:
            raise serializers.ValidationError({"invalid_email": "Email is invalid, please recheck".})

let me know if this works for you or not

CodePudding user response:

You do not have to implement a custom serializer field for the reason u mentioned. all u have to do is have a email field under a list field. for min and max length u can just pass the kwargs because EmailField inherits CharField. In case you want to customize the error message u can pass error_messages kwarg to the email filed.

class EmailSerialilizer(serializers.Serializer):
      emails = serilizers.ListField(child=Serializers.EmailField(
               min_length = 6, 
               max_length = 50,
               error_messages = {
               "invalid": "Email is invalid, please recheck"
               }
      ),
  • Related