简体   繁体   中英

Docker image url validation for django

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM