import re from django import forms from . import models SCRATCH_ID_REGEX = re.compile(r'https://scratch\.mit\.edu/projects/([0-9]+)') def get_scratch_id_from_url(url): match = SCRATCH_ID_REGEX.search(url) return int(match.group(1)) class ScratchURLField(forms.URLField): def clean(self, value): url = super().clean(value) scratch_id = get_scratch_id_from_url(url) return scratch_id class ScratchProjectAddForm(forms.ModelForm): url = ScratchURLField(label='Lien Scratch du projet (URL)') class Meta: fields = ('name', 'author_name', 'url') model = models.ScratchProject