0

I have a model like the below. No matter which url is input, I wanna remove protocols in each url such as http:// or https:// before it is stored into database. Is there any filtering feature for that?

class Store(models.Model):
    url = models.CharField(max_length=100)
    ...

2 Answers 2

1

You should override the save method in order to manipulate any model fields before they are stored in the database. For example:

class Store(models.Model):
    url = models.CharField(max_length=100)
    ...
    def save(self, *args, **kwargs):
        self.url = self.url.split('//')[-1]
        super(Store, self).save(*args, **kwargs)

Also see this answer for a more compliant method of removing the scheme (http or https part) from any URL.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Thank you!
1

You can use a regex to remove the protocol and then save it on the model.

import re
from .models import Store

address_before_cleaning = "https://www.google.com"
address_after_cleaning = re.sub('[\d\w]+://', '', address_before_cleaning)
store_object = Store()
store_object.url = address_after_cleaning
store_object.save()

There is documentations for re in this link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.