import re from django.shortcuts import get_object_or_404 from django.utils import timezone from django.views.generic.edit import CreateView from django.views.generic.detail import DetailView from . import forms, 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 ScratchProjectAddView(CreateView): form_class = forms.ScratchProjectAddForm template_name = 'scratch_show/scratchproject_form.html' def dispatch(self, request, *args, **kwargs): self.event = get_object_or_404(models.Event, date=timezone.now().date(), accept_projects=True) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): url = form.cleaned_data['url'] form.instance.project_id = get_scratch_id_from_url(url) form.instance.event = self.event return super().form_valid(form) class ScratchProjectDetailView(DetailView): model = models.ScratchProject