class FacilityUpdateLocationParamsSerializer(Serializer): # The Google geocoder returns points with 7 decimals of precision, which is # "[the] practical limit of commercial surveying" # https://en.wikipedia.org/wiki/Decimal_degrees lat = DecimalField(max_digits=None, decimal_places=7, required=True) lng = DecimalField(max_digits=None, decimal_places=7, required=True) contributor_id = IntegerField(required=False) notes = CharField(required=False) def validate_lat(self, lat): if lat < -90 or lat > 90: raise ValidationError('lat must be between -90 and 90.') def validate_lng(self, lat): if lat < -180 or lat > 180: raise ValidationError('lng must be between -180 and 180.') def validate_contributor_id(self, contributor_id): if not Contributor.objects.filter(id=contributor_id).exists(): raise ValidationError( 'Contributor {} does not exist.'.format(contributor_id))
class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read_only=True) email = EmailField(label='Email') class Meta: model = CustomUser fields = ['email', 'password', 'token'] extra_kwargs = {'password': {'write_only': True}} def validate(self, data): email = data.get('email', None) password = data['password'] user = get_object_or_404(CustomUser, email=email) if user: if user.check_password(password): data['token'] = 'random number' return data else: raise ValidationError('Incorrect Password') else: raise ValidationError('email is not valid')
class UserUpdateSerializer(ModelSerializer): username = CharField() email = EmailField() class Meta: model = User fields = [ 'id' 'username', 'email', ] def validate(self, data): return data def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] userObj = User(username=username, email=email) userObj.save() return validated_data
class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' article_type = SerializerMethodField() status = SerializerMethodField() position = SerializerMethodField() source = CharField(source="source.name") def get_article_type(self, obj): """文章类型""" return obj.get_article_type_display() def get_status(self, obj): """文章在线情况""" return obj.get_status_display() def get_position(self, obj): """文章配图设置""" return obj.get_position_display()
class UserSerializer(ModelSerializer): """User serialiser.""" role = CharField(default='user') class Meta: fields = ( 'first_name', 'last_name', 'username', 'bio', 'email', 'role', 'confirmation_code' ) model = User extra_kwargs = { 'confirmation_code': {'write_only': True}, 'username': {'required': True}, 'email': {'required': True} }
class ReviewSerializer(ModelSerializer): author = CharField(source='author.username', read_only=True) score = IntegerField(validators=[score_limits]) class Meta: model = Review fields = ['id', 'text', 'author', 'score', 'pub_date'] read_only_fields = ['id', 'score', 'pub_date'] def validate(self, data): title_id = self.context.get('view').kwargs.get('title_id') user = self.context.get('request').user if self.context.get('request').method == 'POST': if (not Titles.objects.filter( id=title_id).exists()) or not bool(data): return ValidationError if Review.objects.filter(author=user, title__id=title_id).exists(): raise ValidationError return data
class OrderDetailSerializer(ModelSerializer): # id = UUIDField(required=False) created_at = TimestampField(required=False) updated_at = TimestampField(required=False) sku_name = StringRelatedField(source='sku.sku_name') specification = StringRelatedField(source='sku.specification') bar_code = StringRelatedField(source='sku.bar_code') item_code = StringRelatedField(source='sku.item_code', default='') price = StringRelatedField(source='sku.price') sku_id = CharField(source='sku.id') available_quantity = StringRelatedField(source='sku.available_quantity') class Meta: model = OrderDetail fields = [ 'id', 'created_at', 'updated_at', 'is_gift', 'price', 'quantity', 'sku_name', 'bar_code', 'item_code', 'available_quantity', 'specification', 'sku_id' ]
class PresetModelSerializer(WithNestedSerializer): preset_id = CharField(source='slug') arguments = PresetArgModelSerializer(many=True) nested_objects = ['arguments'] class Meta: model = Preset list_serializer_class = PresetListSerializer exclude = ('form', 'slug') def validate_preset_id(self, slug): if slug not in presets_register.keys(): raise ValidationError('{} is not an available preset'.format(slug)) return slug def validate(self, data): if not data.get('message'): data['message'] = presets_register[data['slug']].default_message return super(PresetModelSerializer, self).validate(data)
class OaiProviderMetadataFormatSerializer(DocumentSerializer): schema_url = CharField(required=True, write_only=True) class Meta(object): model = OaiProviderMetadataFormat fields = "__all__" depth = 1 read_only_fields = ( "id", "is_default", "is_template", "template", "schema", "xml_schema", "metadata_namespace", ) def create(self, validated_data): return oai_provider_metadata_format_api.add_metadata_format( **validated_data, request=self.context["request"])
class LocationCreateSerializer(ModelSerializer): loc_type = CharField(max_length=250) type_id = IntegerField(min_value=0) class Meta: model = Location fields = [ 'id', 'latitude', 'longitude', 'speed', 'loc_type', 'type_id' ] def create(self, validated_data): type_id = validated_data.get('type_id') longitude = validated_data.get("longitude") latitude = validated_data.get("latitude") speed = validated_data.get("speed") loc_type = validated_data.get('loc_type') location = Location.objects.create(latitude=latitude, longitude=longitude, speed=speed, loc_type=loc_type, type_id=str(type_id)) if loc_type == 'user': user = User.objects.filter(id=type_id).first() created_user = UserLocation.objects.create(user=user, location=location) else: transport = Transport.objects.filter(gps_id=type_id).first() TransportLocation.objects.create(transport=transport, location=location) return { "id": location.id, "latitude": location.latitude, "longitude": location.longitude, "speed": location.speed, "loc_type": loc_type, 'type_id': type_id }
class CreditCardSerializer(serializers.ModelSerializer): cvv = CharField(max_length=4, min_length=3, write_only=True, label=_(u'Cryptogramme de sécurité'), help_text=_(u'Les 3 derniers chiffres au dos de la carte.'), ) keep = BooleanField(default=False, write_only=True) def validate_expires(self, attrs, source): try: expires = attrs.pop(source) attrs.update(dict(zip(('expires_0', 'expires_1'), (expires[:2], expires[2:4])))) except (KeyError, IndexError): raise ValidationError(_("Attribute missed or invalid: 'expires'")) return attrs def validate(self, attrs): keep = attrs['keep'] if not keep: attrs.pop('holder', None) self.form = form = CreditCardForm(attrs) if not form.is_valid(): raise ValidationError(form.errors) new_attrs = form.clean() new_attrs['keep'] = keep return new_attrs def save_object(self, obj, **kwargs): if not obj.pk: obj.subscriber_reference = uuid.uuid4().hex elif not obj.keep and obj.holder: obj.holder = None self.form.instance = obj self.form.save(commit=True) class Meta: model = models.CreditCard fields = ('id', 'masked_number', 'expires', 'holder_name', 'card_number', 'cvv', 'holder', 'keep') read_only_fields = ('masked_number',) write_only_fields = ('card_number',) immutable_fields = ('expires', 'holder_name', 'holder', 'card_number', 'cvv')
class UserCreateSerializer(ModelSerializer): email = EmailField(label='Email address') email2 = EmailField(label='Confirm email') password = CharField(style={'input_type': 'password'}) class Meta: model = User fields = [ 'username', 'email', 'email2', 'password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): email = data['email'] user_qs = User.objects.filter(email=email) if user_qs.exists(): raise ValidationError("This user is already registered.") return data def validate_email2(self, value): data = self.get_initial() email1 = data.get("email") email2 = value if email1 != email2: raise ValidationError("Emails must match!") return value def create(self, validated_data): print(validated_data) username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User(username=username, email=email) user_obj.set_password(password) user_obj.save() return validated_data
class UserCreateSerializer(ModelSerializer): email = EmailField(label='Email Address') email2 = EmailField(label='Confirm Email') password2 = CharField(style={'input_type': 'password'}, label='Confirm Password', write_only=True) class Meta: model = User fields = ['username', 'email', 'email2', 'password', 'password2'] extra_kwargs = {'password': {'write_only': True}} def validate_email2(self, value): data = self.get_initial() email = data['email'] email2 = value user_qs = User.objects.filter(email=email2) if user_qs.exists(): raise ValidationError( "User already registered with this email address.") if email2 != email: raise ValidationError("Email must match.") return value def validate_password2(self, value): data = self.get_initial() password = data['password'] password2 = value if password2 != password: raise ValidationError("Password must match.") return value def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User(username=username, email=email) user_obj.set_password(password) user_obj.save() return validated_data
class FacilityCreateBodySerializer(Serializer): country = CharField(required=True) name = CharField(required=True, max_length=200) address = CharField(required=True, max_length=200) ppe_product_types = ListField(required=False, child=CharField(required=True, max_length=50)) ppe_contact_phone = CharField(required=False, max_length=20) ppe_contact_email = CharField(required=False) ppe_website = URLField(required=False) def validate_country(self, value): try: return get_country_code(value) except ValueError as ve: raise ValidationError(ve)
class UserCreateSerializer(ModelSerializer): password2 = CharField(label="Confirm password") class Meta: model = User fields = [ "username", "password", "password2", ] extra_kwargs = { "password": { "write_only": True } } def validate_password2(self, value): data = self.get_initial() password1 = data.get("password") if password1 != value: raise ValidationError("Passwords do not match") return value # def validate(self, data): # email = data['email'] # user_qs = User.objects.filter(email=email) # if user_qs.exists: # raise ValidationError("User with this email address already exists") # return data def create(self, validated_data): print(validated_data) username = validated_data["username"] password = validated_data["password"] user_obj = User( username=username ) user_obj.set_password(password) user_obj.save() return validated_data
class FactorySerializer(ModelSerializer): images = ImageSerializer(many=True, read_only=True) type = CharField(source="factory_type") reported_at = SerializerMethodField() class Meta: model = Factory fields = [ "id", "lat", "lng", "name", "landcode", "factory_type", "type", "status", "images", "reported_at", ] def get_reported_at(self, obj): report_records = ReportRecord.objects.only("created_at").filter( factory=obj) if len(report_records) == 0: return None reported_date = [record.created_at for record in report_records] return sorted(reported_date, reverse=True)[0] def validate_lat(self, value): if value < settings.TAIWAN_MIN_LATITUDE or value > settings.TAIWAN_MAX_LATITUDE: raise ValidationError( f"latitude should be within {settings.TAIWAN_MIN_LATITUDE} ~ {settings.TAIWAN_MAX_LATITUDE}, but got {value}" ) def validate_lng(self, value): if value < settings.TAIWAN_MIN_LONGITUDE or value > settings.TAIWAN_MAX_LONGITUDE: raise ValidationError( f"longitude should be within {settings.TAIWAN_MIN_LONGITUDE} ~ {settings.TAIWAN_MAX_LONGITUDE}, but got {value}" )
class SaveAddressForPrizeSerilizer(ModelSerializer): post_id = CharField(error_messages={ 'required': 'post key is required', 'blank': 'post_id is required' }) country = CharField(max_length=100, error_messages={ 'required': 'country key is required', 'blank': 'country is required' }) street = CharField(max_length=200, error_messages={ 'required': 'street key is required', 'blank': 'street is required' }) city = CharField(max_length=100, error_messages={ 'required': 'city key is required', 'blank': 'city is required' }) zip_code = CharField(max_length=8, error_messages={ 'required': 'zip_code key is required', 'blank': 'zip_code is required' }) country_code = CharField(max_length=4, error_messages={ 'required': 'country_code key is required', 'blank': 'country_code is required' }) mobile_number = CharField(max_length=12, error_messages={ 'required': 'mobile_number key is required', 'blank': 'mobile_number is required' }) class Meta: model = SaveAddressForCompetitionPrize fields = [ 'post_id', 'country', 'street', 'city', 'zip_code', 'country_code', 'mobile_number' ]
class BagBaseSr(ModelSerializer): area_uid = SerializerMethodField() class Meta: model = Bag exclude = () read_only_fields = ('id', ) uid = CharField( validators=[ UniqueValidator( queryset=Bag.objects.all(), message="Duplicate bill of landing code", ) ], required=False, ) def get_area_uid(self, obj): if not obj.area: return '' return obj.area.uid
class DirectoryUserSerializer(ModelSerializer): profile_image_url = CharField(source='get_api_profile_image_url',read_only=True) joined = SerializerMethodField('time_since') is_friend = SerializerMethodField('is_user_friend') def time_since(self,obj): from django.utils.timesince import timesince return timesince(obj.created_on) def is_user_friend(self,obj): user = self.context['request'].user if obj in user.friends.all(): friend = True else: friend = False return friend class Meta: model = GolfUser fields = ('id','first_name','last_name','email','phone','is_private','zipcode','profile_image_url', 'joined','is_friend')
class CrazyHotelsQuerySerializer(Serializer): From = DateField(required=False) To = DateField(required=False) city = CharField(required=False) adultsCount = IntegerField(required=False) def to_internal_value(self, data): data = super(CrazyHotelsQuerySerializer, self).to_internal_value(data) if not (("From" in data and "To" in data) or ("From" not in data and "To" not in data)): missing = "To" if "From" in data else "From" errors = OrderedDict({ missing: "can't search without %s field" % missing }) raise ValidationError(errors) print(data) return data def to_representation(self, instance): data = super(CrazyHotelsQuerySerializer, self).to_representation(instance) kwargs = {} if "From" and "To" in data: kwargs.update({"availability__range": [data["From"], data["To"]]}) if "city" in data: kwargs.update({ "city": data["city"] }) if "adultsCount" in data: kwargs.update({ "number_of_adults": data["adultsCount"] }) return kwargs
class SaveDocumentFileAnswerSerializer(SaveAnswerSerializer): value = CharField(write_only=True, source="file") value_id = PrimaryKeyRelatedField(read_only=True, source="file") def set_file(self, validated_data): file_name = validated_data.get("file") file = models.File.objects.create(name=file_name) validated_data["file"] = file return validated_data def create(self, validated_data): validated_data = self.set_file(validated_data) return super().create(validated_data) def update(self, instance, validated_data): if instance.file.name is not validated_data["file"]: instance.file.delete() validated_data = self.set_file(validated_data) return super().update(instance, validated_data) class Meta(SaveAnswerSerializer.Meta): fields = SaveAnswerSerializer.Meta.fields + ("value_id", )
class IsUsernameExistSerializer(ModelSerializer): username = CharField() class Meta: model = User fields = ['username'] def validate(self, data): # username = data['username'] # user_qs = User.objects.filter(username=username) # if user_qs.exists(): # raise ValidationError("This user has already registered.") return data def validate_username(self, value): data = self.get_initial() username = data.get("username") user_qs = User.objects.filter(username=username) if user_qs.exists(): raise ValidationError("This username has already registered.") return value
class UserCreateSL(ModelSerializer): conf_password = CharField(label="Confirm password") class Meta: model = User fields = [ 'username', 'email', 'password', 'conf_password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): username = data['username'] user_chk = User.objects.filter(username=username) if user_chk.exists(): raise ValidationError("User Already register with this username") return data def validate_conf_password(self, value): data = self.get_initial() password = data.get("password") conf_password = data.get("conf_password") if password != conf_password: raise ValidationError("Password and Confirm Password Not match") return value def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( username=username, password=password, ) user_obj.set_password(password) user_obj.save() return validated_data
class UserLoginSerializer(HyperlinkedModelSerializer): user_obj = None username = CharField(required=True, allow_blank=True) class Meta: model = CustomUser fields = ('username', 'password') extra_kwargs = {"password": {"write_only": True}} def validate(self, data): username = data.get('username', None) password = data["password"] user = CustomUser.objects.filter(Q(username=username)).distinct() if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError('not valid') if user_obj: if not user_obj.check_password(password): raise ValidationError('wrong pasword') return data
class PollingStationGeoSerializer(PollingStationSerializer, GeoFeatureModelSerializer): station_id = CharField(source='internal_council_id', read_only=True) id = SerializerMethodField('generate_id') urls = SerializerMethodField('generate_urls') council = SerializerMethodField('generate_council') def generate_council(self, record): return reverse('council-detail', request=self.context['request'], kwargs={'pk': record.council_id}) def generate_id(self, record): return "%s.%s" % (record.council_id, record.internal_council_id) class Meta: model = PollingStation geo_field = 'location' id_field = 'id' fields = ('id', 'urls', 'council', 'station_id', 'postcode', 'address', 'location')
class EventSerializer(ModelSerializer): tmp_duration = CharField(source='reminder4api') class Meta: model = Event fields = ( 'title', 'need_remind', 'date_start', 'date_stop', 'tmp_duration', 'user_event', ) def save(self, *args, **kwargs): #logger.warning(str(self.validated_data)) for item in CHOICE_DELTA: if self.validated_data['reminder4api'] == item[1]: self.validated_data['reminder'] = item[0] del self.validated_data["reminder4api"] self.validated_data.update(kwargs) super().save(*args, **kwargs)
class Event1Serializer(ModelSerializer): host = CharField(max_length=1000) eventid = IntegerField() start_date = DateField(format="%d %b %Y") end_date = DateField(format="%d %b %Y") class Meta: model = Event fields = [ 'eventid', 'host', 'description', 'title', 'fee', 'rules', 'prerequistes', 'venue', 'start_date', 'end_date', 'start_time', 'end_time', ]
class AuthTokenMailSerializer(AuthTokenSerializer): email = EmailField(label="Email", required=False) username = CharField(label="Username", required=False) msg = 'Unable to log in with provided credentials.' msg_email_pass = '******' msg_username_pass = '******' def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') email = attrs.get('email') if email: if email and password: qs = User.objects.filter( email=email).values('username').first() if qs: username = qs.get('username', None) user = authenticate(username=username, password=password) if not user: raise ValidationError(self.msg, code='authorization') else: raise ValidationError(self.msg, code='authorization') else: raise ValidationError(self.msg_email_pass, code='authorization') else: if username and password: user = authenticate(username=username, password=password) if not user: raise ValidationError(self.msg, code='authorization') else: raise ValidationError(self.msg_username_pass, code='authorization') attrs['user'] = user return attrs
class RecipeListSerializer(ModelSerializer): """ Main GET LIST Serializer for Recipes without all the details """ comment_count = IntegerField(read_only=True) ul_count = IntegerField(read_only=True) uc_count = IntegerField(read_only=True) ingredients = QuantityIngredientSerializer(source='quantity_set', many=True, read_only=True) slug = CharField(read_only=True) tags = TagSerializer(many=True) added_by = NestedUserSerializer(read_only=True, default=CreateOnlyDefault( CurrentUserDefault())) class Meta: model = Recipe fields = ( 'id', 'slug', 'name', 'created', 'added_by', 'ingredients', 'comment_count', 'ul_count', 'uc_count', 'tags', ) @staticmethod def setup_eager_loading(queryset): "Perform necessary eager loading of data." queryset = queryset.select_related('added_by') queryset = queryset.prefetch_related('tags', 'quantity_set', 'quantity_set__ingredient') return queryset
class ManSerializer(PersonSerializer): sex = CharField(read_only=True) class Meta(PersonSerializer.Meta): model = Man fields = fields = [ "name", "dni", "address", "history_id", "date_of_birth", "age", "observations", "doner", "alcoholic", "drinks_coffee", "smokes", "diseases", "risk_factors", "home_lockdowns", "sex", ]