skip to Main Content

I want to get docker image URL from the user but URLs can’t be acceptable with models.URLField() in django.
For example, this URL: hub.something.com/nginx:1.21, got an error.
How can fix it?

2

Answers


  1. Chosen as BEST ANSWER
    from django.db import models
    from django.core.validators import RegexValidator
    
    
    class App(models.Model):
        image = models.CharField(
            max_length=200,
            validators=[
                RegexValidator(
                    regex=r'^(?:(?=[^:/]{1,253})(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(?:.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*(?::[0-9]{1,5})?/)?((?![._-])(?:[a-z0-9._-]*)(?<![._-])(?:/(?![._-])[a-z0-9._-]*(?<![._-]))*)(?::(?![.-])[a-zA-Z0-9_.-]{1,128})?$',
                    message='image is not valid',
                    code='invalid_url'
                )
            ]
        )
    

    Regex reference is here and you can check matchs.


  2. Try this out:

    from django.core.validators import URLValidator
    from django.utils.deconstruct import deconstructible
    from django.db import models
    
    # I suggest to move this class to validators.py outside of this app folder 
    # so it can be easily accessible by all models
    @deconstructible
    class DockerHubURLValidator(URLValidator):
        domain_re = URLValidator.domain_re + '(?:[a-z0-9-./:]*)'
    
    
    class ModelName(models.Model):
        image = models.CharField(max_length=200, validators=[DockerHubURLValidator()])
    

    I am not great at regexes but I believe I did it right, when I try new domain_re regex, it allows as domain: .com/nginx:1.21. The rest of url is handled automatically by django

    If there will be another case of regex, or for some reason this regex won’t work as I expect, I believe from here you will find a way 😉
    Just check the URLValidator code and modify accordingly.

    PS. Sorry for being late, was out with dog

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search