Home > Net >  Docker image url validation for django
Docker image url validation for django

Time:11-28

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?

CodePudding user response:

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 = r"(?:\.(?!-)[a-z"   URLValidator.ul   r"0-9-]{1,63}(?<!-))(?:[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 regex: (?:\.(?!-)[a-z0-9-]{1,63}(?<!-))(?:[a-z0-9-.\/:]*)

It allows as domain: .com/nginx:1.21

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

CodePudding user response:

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.

  • Related