Search code examples
pythondjangodjango-rest-framework

django model add scheme to url field if not represented


I have a model with a URL field in my Django rest framework project. I want to ensure that a scheme (like https://) is added to the URL if it doesn't exist.

from django.db import models
class MyModel(models.Model):
    url = models.URLField()

I've tried using the clean, save, clean_fields methods, but none of them seem to work. I feel there should be a straightforward way to accomplish this, but I can't find one.

For example I want to send "google.com" in my POST request and add https:// before validating via URLField. If I change the field value in save or clean methods, it still gives me a validation error: 'Enter a valid URL'.

Any suggestions or best practices would be greatly appreciated.

Thanks!


Solution

  • I found a solution to my own question, which overrides the to_internal_value method of URLField in the serializer, I realized that I should change the data in my serializer instead of the model.

    class CustomURLField(serializers.URLField):
        def to_internal_value(self, value):
            value = super().to_internal_value(value)
            if value and not (value.startswith('http://') or 
     value.startswith('https://')):
                value = 'https://' + value
            return value
    
    class MyModelSerializer(serializers.ModelSerializer):
        url = CustomURLField()
    
        class Meta:
            model = MyModel
        fields = '__all__'
    

    If I didn't use Django REST Framework, I guess that I would have to override the to_python method in the model field instead.