Ajout d'une tâche pour traiter les événements soumis

This commit is contained in:
Jean-Marie Favreau 2023-10-15 11:05:46 +02:00
parent 00df29ef4d
commit 380271b48d
9 changed files with 151 additions and 17 deletions

View File

@ -1,4 +1,5 @@
from django.contrib import admin
from .models import Event
from .models import Event, EventSubmissionForm
admin.site.register(Event)
admin.site.register(Event)
admin.site.register(EventSubmissionForm)

View File

@ -2,6 +2,8 @@ import os
from celery import Celery
from celery.schedules import crontab
from celery.utils.log import get_task_logger
# Set the default Django settings module for the 'celery' program.
APP_ENV = os.getenv("APP_ENV", "dev")
@ -9,6 +11,9 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", f"agenda_culturel.settings.{APP_
app = Celery("agenda_culturel")
logger = get_task_logger(__name__)
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
@ -20,16 +25,15 @@ app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print(f"Request: {self.request!r}")
def create_event_from_submission(self, url):
logger.info(f"{url=}")
try:
logger.info("About to create event from submission")
# TODO
except BadHeaderError:
logger.info("BadHeaderError")
except Exception as e:
logger.error(e)
app.conf.beat_schedule = {
"delete_job_files": {
"task": "test_periodic_task",
# Every 1 minute for testing purposes
"schedule": crontab(minute="*/1"),
},
}
app.conf.timezone = "UTC"
app.conf.timezone = "Europe/Paris"

View File

@ -0,0 +1,11 @@
from django.forms import ModelForm
from django.views.generic import FormView
from .models import EventSubmissionForm
class EventSubmissionModelForm(ModelForm):
class Meta:
model = EventSubmissionForm
fields = ["url"]

View File

@ -0,0 +1,38 @@
# Generated by Django 4.2.1 on 2023-10-14 16:33
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_date', models.DateTimeField(auto_now_add=True)),
('modified_date', models.DateTimeField(auto_now=True)),
('title', models.CharField(help_text='Short title', max_length=512, verbose_name='Title')),
('status', models.CharField(choices=[('published', 'Published'), ('trash', 'Trash'), ('draft', 'Draft')], default='published', max_length=20, verbose_name='Status')),
('start_day', models.DateField(help_text='Day of the event', verbose_name='Day of the event')),
('start_time', models.TimeField(blank=True, help_text='Starting time', null=True, verbose_name='Starting time')),
('end_day', models.DateField(blank=True, help_text='End day of the event, only required if different from the start day.', null=True, verbose_name='End day of the event')),
('end_time', models.TimeField(blank=True, help_text='Final time', null=True, verbose_name='Final time')),
('location', models.CharField(help_text='Address of the event', max_length=512, verbose_name='Location')),
('description', models.TextField(blank=True, help_text='General description of the event', null=True, verbose_name='Description')),
('image', models.URLField(blank=True, help_text='URL of the illustration image', null=True, verbose_name='Illustration')),
('image_alt', models.CharField(blank=True, help_text='Alternative text used by screen readers for the image', max_length=512, null=True, verbose_name='Illustration description')),
('reference_urls', django.contrib.postgres.fields.ArrayField(base_field=models.URLField(), blank=True, help_text='List of all the urls where this event can be found.', null=True, size=None, verbose_name='URLs')),
],
options={
'verbose_name': 'Event',
'verbose_name_plural': 'Events',
},
),
]

View File

@ -0,0 +1,31 @@
# Generated by Django 4.2.1 on 2023-10-15 08:51
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agenda_culturel', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='EventSubmissionForm',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('url', models.URLField(help_text='URL where this event can be found.', max_length=512, verbose_name='URL')),
],
options={
'verbose_name': 'Event submission form',
'verbose_name_plural': 'Event submissions forms',
'db_table': 'eventsubmissionform',
},
),
migrations.AlterField(
model_name='event',
name='reference_urls',
field=django.contrib.postgres.fields.ArrayField(base_field=models.URLField(max_length=512), blank=True, help_text='List of all the urls where this event can be found.', null=True, size=None, verbose_name='URLs'),
),
]

View File

@ -35,7 +35,7 @@ class Event(models.Model):
image = models.URLField(verbose_name=_('Illustration'), help_text=_("URL of the illustration image"), max_length=200, blank=True, null=True)
image_alt = models.CharField(verbose_name=_('Illustration description'), help_text=_('Alternative text used by screen readers for the image'), blank=True, null=True, max_length=512)
reference_urls = ArrayField(models.URLField(max_length=200), verbose_name=_('URLs'), help_text=_("List of all the urls where this event can be found."), blank=True, null=True)
reference_urls = ArrayField(models.URLField(max_length=512), verbose_name=_('URLs'), help_text=_("List of all the urls where this event can be found."), blank=True, null=True)
def get_absolute_url(self):
return reverse("view_event", kwargs={"pk": self.pk, "extra": self.title})
@ -45,4 +45,16 @@ class Event(models.Model):
class Meta:
verbose_name = _('Event')
verbose_name_plural = _('Events')
verbose_name_plural = _('Events')
class EventSubmissionForm(models.Model):
url = models.URLField(max_length=512, verbose_name=_('URL'), help_text=_("URL where this event can be found."))
class Meta:
db_table = "eventsubmissionform"
verbose_name = _("Event submission form")
verbose_name_plural = _("Event submissions forms")
def __str__(self):
return self.url

View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Proposer un événement</title>
</head>
<body>
<h2>Formulaire de proposition d'événement</h2>
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Proposer un événement">
</form>
</body>
</html>

View File

@ -11,8 +11,10 @@ urlpatterns = [
path("", EventListView.as_view(), name="home"),
re_path(r'^(?P<mode>' + '|'.join([dm.value for dm in DisplayModes]) + ')/$', view_interval, name='view_interval'),
path("event/<pk>-<extra>", EventDetailView.as_view(), name="view_event"),
path("proposer", EventSubmissionFormView.as_view(), name="event_submission_form"),
path("admin/", admin.site.urls),
path("test_app/", include("test_app.urls")),
]
if settings.DEBUG:

View File

@ -1,5 +1,9 @@
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic import ListView, DetailView, FormView
from .forms import EventSubmissionModelForm
from .celery import create_event_from_submission
from .models import Event
from django.utils import timezone
from enum import StrEnum
@ -33,4 +37,20 @@ class EventDetailView(DetailView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["now"] = timezone.now()
return context
return context
class EventSubmissionFormView(FormView):
form_class = EventSubmissionModelForm
template_name = "agenda_culturel/submission.html"
success_url = "/"
def form_valid(self, form):
form.save()
self.create_event(form.cleaned_data)
return super().form_valid(form)
def create_event(self, valid_data):
url = valid_data["url"]
create_event_from_submission.delay(url)