formatage black sur les src
This commit is contained in:
@@ -1,8 +1,31 @@
|
||||
from django.forms import ModelForm, ValidationError, TextInput, Form, URLField, MultipleHiddenInput, Textarea, CharField, ChoiceField, RadioSelect, MultipleChoiceField, BooleanField, HiddenInput, ModelChoiceField
|
||||
from django.forms import (
|
||||
ModelForm,
|
||||
ValidationError,
|
||||
TextInput,
|
||||
Form,
|
||||
URLField,
|
||||
MultipleHiddenInput,
|
||||
Textarea,
|
||||
CharField,
|
||||
ChoiceField,
|
||||
RadioSelect,
|
||||
MultipleChoiceField,
|
||||
BooleanField,
|
||||
HiddenInput,
|
||||
ModelChoiceField,
|
||||
)
|
||||
from datetime import date
|
||||
from django_better_admin_arrayfield.forms.widgets import DynamicArrayWidget
|
||||
|
||||
from .models import Event, BatchImportation, RecurrentImport, CategorisationRule, ModerationAnswer, ModerationQuestion, Place
|
||||
from .models import (
|
||||
Event,
|
||||
BatchImportation,
|
||||
RecurrentImport,
|
||||
CategorisationRule,
|
||||
ModerationAnswer,
|
||||
ModerationQuestion,
|
||||
Place,
|
||||
)
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from string import ascii_uppercase as auc
|
||||
from .templatetags.utils_extra import int_to_abc
|
||||
@@ -12,6 +35,7 @@ from django.utils.formats import localize
|
||||
from .templatetags.event_extra import event_field_verbose_name, field_to_html
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -22,45 +46,63 @@ class EventSubmissionForm(Form):
|
||||
class DynamicArrayWidgetURLs(DynamicArrayWidget):
|
||||
template_name = "agenda_culturel/widgets/widget-urls.html"
|
||||
|
||||
|
||||
class DynamicArrayWidgetTags(DynamicArrayWidget):
|
||||
template_name = "agenda_culturel/widgets/widget-tags.html"
|
||||
|
||||
|
||||
class RecurrentImportForm(ModelForm):
|
||||
class Meta:
|
||||
model = RecurrentImport
|
||||
fields = '__all__'
|
||||
fields = "__all__"
|
||||
widgets = {
|
||||
'defaultTags': DynamicArrayWidgetTags(),
|
||||
"defaultTags": DynamicArrayWidgetTags(),
|
||||
}
|
||||
|
||||
|
||||
class CategorisationRuleImportForm(ModelForm):
|
||||
class Meta:
|
||||
model = CategorisationRule
|
||||
fields = '__all__'
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class EventForm(ModelForm):
|
||||
|
||||
class Meta:
|
||||
model = Event
|
||||
exclude = ["possibly_duplicated", "imported_date", "modified_date", "moderated_date"]
|
||||
exclude = [
|
||||
"possibly_duplicated",
|
||||
"imported_date",
|
||||
"modified_date",
|
||||
"moderated_date",
|
||||
]
|
||||
widgets = {
|
||||
'start_day': TextInput(attrs={'type': 'date', 'onchange': 'update_datetimes(event);', "onfocus": "this.oldvalue = this.value;"}),
|
||||
'start_time': TextInput(attrs={'type': 'time', 'onchange': 'update_datetimes(event);', "onfocus": "this.oldvalue = this.value;"}),
|
||||
'end_day': TextInput(attrs={'type': 'date'}),
|
||||
'end_time': TextInput(attrs={'type': 'time'}),
|
||||
'uuids': MultipleHiddenInput(),
|
||||
'import_sources': MultipleHiddenInput(),
|
||||
'reference_urls': DynamicArrayWidgetURLs(),
|
||||
'tags': DynamicArrayWidgetTags(),
|
||||
"start_day": TextInput(
|
||||
attrs={
|
||||
"type": "date",
|
||||
"onchange": "update_datetimes(event);",
|
||||
"onfocus": "this.oldvalue = this.value;",
|
||||
}
|
||||
),
|
||||
"start_time": TextInput(
|
||||
attrs={
|
||||
"type": "time",
|
||||
"onchange": "update_datetimes(event);",
|
||||
"onfocus": "this.oldvalue = this.value;",
|
||||
}
|
||||
),
|
||||
"end_day": TextInput(attrs={"type": "date"}),
|
||||
"end_time": TextInput(attrs={"type": "time"}),
|
||||
"uuids": MultipleHiddenInput(),
|
||||
"import_sources": MultipleHiddenInput(),
|
||||
"reference_urls": DynamicArrayWidgetURLs(),
|
||||
"tags": DynamicArrayWidgetTags(),
|
||||
}
|
||||
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
is_authenticated = kwargs.pop('is_authenticated', False)
|
||||
is_authenticated = kwargs.pop("is_authenticated", False)
|
||||
super().__init__(*args, **kwargs)
|
||||
if not is_authenticated:
|
||||
del self.fields['status']
|
||||
|
||||
del self.fields["status"]
|
||||
|
||||
def clean_end_day(self):
|
||||
start_day = self.cleaned_data.get("start_day")
|
||||
@@ -82,40 +124,71 @@ class EventForm(ModelForm):
|
||||
# both start and end time are defined
|
||||
if start_time is not None and end_time is not None:
|
||||
if start_time > end_time:
|
||||
raise ValidationError(_("The end time cannot be earlier than the start time."))
|
||||
raise ValidationError(
|
||||
_("The end time cannot be earlier than the start time.")
|
||||
)
|
||||
|
||||
return end_time
|
||||
|
||||
|
||||
|
||||
class BatchImportationForm(Form):
|
||||
json = CharField(label="JSON", widget=Textarea(attrs={"rows":"10"}), help_text=_("JSON in the format expected for the import."), required=True)
|
||||
json = CharField(
|
||||
label="JSON",
|
||||
widget=Textarea(attrs={"rows": "10"}),
|
||||
help_text=_("JSON in the format expected for the import."),
|
||||
required=True,
|
||||
)
|
||||
|
||||
|
||||
class FixDuplicates(Form):
|
||||
|
||||
|
||||
action = ChoiceField()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
nb_events = kwargs.pop('nb_events', None)
|
||||
nb_events = kwargs.pop("nb_events", None)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if nb_events == 2:
|
||||
choices = [("NotDuplicates", "Ces événements sont différents")]
|
||||
choices += [("SelectA", "Ces événements sont identiques, on garde A et on met B à la corbeille")]
|
||||
choices += [("SelectB", "Ces événements sont identiques, on garde B et on met A à la corbeille")]
|
||||
choices += [("Merge", "Ces événements sont identiques, on fusionne à la main")]
|
||||
choices += [
|
||||
(
|
||||
"SelectA",
|
||||
"Ces événements sont identiques, on garde A et on met B à la corbeille",
|
||||
)
|
||||
]
|
||||
choices += [
|
||||
(
|
||||
"SelectB",
|
||||
"Ces événements sont identiques, on garde B et on met A à la corbeille",
|
||||
)
|
||||
]
|
||||
choices += [
|
||||
("Merge", "Ces événements sont identiques, on fusionne à la main")
|
||||
]
|
||||
else:
|
||||
choices = [("NotDuplicates", "Ces événements sont tous différents")]
|
||||
for i in auc[0:nb_events]:
|
||||
choices += [("Remove" + i, "L'événement " + i + " n'est pas identique aux autres, on le rend indépendant")]
|
||||
choices += [
|
||||
(
|
||||
"Remove" + i,
|
||||
"L'événement "
|
||||
+ i
|
||||
+ " n'est pas identique aux autres, on le rend indépendant",
|
||||
)
|
||||
]
|
||||
for i in auc[0:nb_events]:
|
||||
choices += [("Select" + i, "Ces événements sont identiques, on garde " + i + " et on met les autres à la corbeille")]
|
||||
choices += [("Merge", "Ces événements sont identiques, on fusionne à la main")]
|
||||
choices += [
|
||||
(
|
||||
"Select" + i,
|
||||
"Ces événements sont identiques, on garde "
|
||||
+ i
|
||||
+ " et on met les autres à la corbeille",
|
||||
)
|
||||
]
|
||||
choices += [
|
||||
("Merge", "Ces événements sont identiques, on fusionne à la main")
|
||||
]
|
||||
|
||||
|
||||
self.fields['action'].choices = choices
|
||||
self.fields["action"].choices = choices
|
||||
|
||||
def is_action_no_duplicates(self):
|
||||
return self.cleaned_data["action"] == "NotDuplicates"
|
||||
@@ -145,26 +218,28 @@ class FixDuplicates(Form):
|
||||
|
||||
|
||||
class SelectEventInList(Form):
|
||||
|
||||
event = ChoiceField()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
events = kwargs.pop('events', None)
|
||||
events = kwargs.pop("events", None)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.fields['event'].choices = [(e.pk, str(e.start_day) + " " + e.title + ", " + e.location) for e in events]
|
||||
self.fields["event"].choices = [
|
||||
(e.pk, str(e.start_day) + " " + e.title + ", " + e.location) for e in events
|
||||
]
|
||||
|
||||
|
||||
class MergeDuplicates(Form):
|
||||
|
||||
checkboxes_fields = ["reference_urls", "description"]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.duplicates = kwargs.pop('duplicates', None)
|
||||
self.duplicates = kwargs.pop("duplicates", None)
|
||||
nb_events = self.duplicates.nb_duplicated()
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
choices = [("event" + i, "Valeur de l'évenement " + i) for i in auc[0:nb_events]]
|
||||
choices = [
|
||||
("event" + i, "Valeur de l'évenement " + i) for i in auc[0:nb_events]
|
||||
]
|
||||
|
||||
for f in self.duplicates.get_items_comparison():
|
||||
if not f["similar"]:
|
||||
@@ -172,42 +247,61 @@ class MergeDuplicates(Form):
|
||||
self.fields[f["key"]] = MultipleChoiceField(choices=choices)
|
||||
self.fields[f["key"]].initial = choices[0][0]
|
||||
else:
|
||||
self.fields[f["key"]] = ChoiceField(widget=RadioSelect, choices=choices)
|
||||
self.fields[f["key"]] = ChoiceField(
|
||||
widget=RadioSelect, choices=choices
|
||||
)
|
||||
self.fields[f["key"]].initial = choices[0][0]
|
||||
|
||||
|
||||
def as_grid(self):
|
||||
result = '<div class="grid">'
|
||||
for i, e in enumerate(self.duplicates.get_duplicated()):
|
||||
result += '<div class="grid entete-badge">'
|
||||
result += '<div class="badge-large">' + int_to_abc(i) + '</div>'
|
||||
result += '<ul>'
|
||||
result += '<li><a href="' + e.get_absolute_url() + '">' + e.title + '</a></li>'
|
||||
result += '<li>Création : ' + localize(localtime(e.created_date)) + '</li>'
|
||||
result += '<li>Dernière modification : ' + localize(localtime(e.modified_date)) + '</li>'
|
||||
result += '<div class="badge-large">' + int_to_abc(i) + "</div>"
|
||||
result += "<ul>"
|
||||
result += (
|
||||
'<li><a href="' + e.get_absolute_url() + '">' + e.title + "</a></li>"
|
||||
)
|
||||
result += (
|
||||
"<li>Création : " + localize(localtime(e.created_date)) + "</li>"
|
||||
)
|
||||
result += (
|
||||
"<li>Dernière modification : "
|
||||
+ localize(localtime(e.modified_date))
|
||||
+ "</li>"
|
||||
)
|
||||
if e.imported_date:
|
||||
result += '<li>Dernière importation : ' + localize(localtime(e.imported_date)) + '</li>'
|
||||
result += '</ul>'
|
||||
result += '</div>'
|
||||
result += '</div>'
|
||||
result += (
|
||||
"<li>Dernière importation : "
|
||||
+ localize(localtime(e.imported_date))
|
||||
+ "</li>"
|
||||
)
|
||||
result += "</ul>"
|
||||
result += "</div>"
|
||||
result += "</div>"
|
||||
|
||||
for e in self.duplicates.get_items_comparison():
|
||||
key = e["key"]
|
||||
result += "<h3>" + event_field_verbose_name(e["key"]) + "</h3>"
|
||||
if e["similar"]:
|
||||
result += '<div class="comparison-item">Identique :' + str(field_to_html(e["values"], e["key"])) + '</div>'
|
||||
result += (
|
||||
'<div class="comparison-item">Identique :'
|
||||
+ str(field_to_html(e["values"], e["key"]))
|
||||
+ "</div>"
|
||||
)
|
||||
else:
|
||||
result += '<fieldset>'
|
||||
result += "<fieldset>"
|
||||
result += '<div class="grid comparison-item">'
|
||||
if hasattr(self, "cleaned_data"):
|
||||
checked = self.cleaned_data.get(key)
|
||||
else:
|
||||
checked = self.fields[key].initial
|
||||
|
||||
for i, (v, radio) in enumerate(zip(e["values"], self.fields[e["key"]].choices)):
|
||||
for i, (v, radio) in enumerate(
|
||||
zip(e["values"], self.fields[e["key"]].choices)
|
||||
):
|
||||
result += '<div class="duplicated">'
|
||||
id = 'id_' + key + '_' + str(i)
|
||||
value = 'event' + auc[i]
|
||||
id = "id_" + key + "_" + str(i)
|
||||
value = "event" + auc[i]
|
||||
|
||||
result += '<input id="' + id + '" name="' + key + '"'
|
||||
if key in MergeDuplicates.checkboxes_fields:
|
||||
@@ -219,13 +313,18 @@ class MergeDuplicates(Form):
|
||||
if checked == value:
|
||||
result += " checked"
|
||||
result += ' value="' + value + '"'
|
||||
result += '>'
|
||||
result += '<div class="badge-small">' + int_to_abc(i) + '</div>' + str(field_to_html(v, e["key"])) + '</div>'
|
||||
result += ">"
|
||||
result += (
|
||||
'<div class="badge-small">'
|
||||
+ int_to_abc(i)
|
||||
+ "</div>"
|
||||
+ str(field_to_html(v, e["key"]))
|
||||
+ "</div>"
|
||||
)
|
||||
result += "</div></fieldset>"
|
||||
|
||||
return mark_safe(result)
|
||||
|
||||
|
||||
def get_selected_events_id(self, key):
|
||||
value = self.cleaned_data.get(key)
|
||||
if not key in self.fields:
|
||||
@@ -240,20 +339,20 @@ class MergeDuplicates(Form):
|
||||
class ModerationQuestionForm(ModelForm):
|
||||
class Meta:
|
||||
model = ModerationQuestion
|
||||
fields = '__all__'
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class ModerationAnswerForm(ModelForm):
|
||||
class Meta:
|
||||
model = ModerationAnswer
|
||||
exclude = ['question']
|
||||
exclude = ["question"]
|
||||
widgets = {
|
||||
'adds_tags': DynamicArrayWidgetTags(),
|
||||
'removes_tags': DynamicArrayWidgetTags()
|
||||
"adds_tags": DynamicArrayWidgetTags(),
|
||||
"removes_tags": DynamicArrayWidgetTags(),
|
||||
}
|
||||
|
||||
|
||||
class ModerateForm(ModelForm):
|
||||
|
||||
class Meta:
|
||||
model = Event
|
||||
fields = []
|
||||
@@ -265,75 +364,104 @@ class ModerateForm(ModelForm):
|
||||
mas = ModerationAnswer.objects.all()
|
||||
|
||||
for q in mqs:
|
||||
self.fields[q.complete_id()] = ChoiceField(widget=RadioSelect, label=q.question, choices=[(a.pk, a.html_description()) for a in mas if a.question == q], required=True)
|
||||
self.fields[q.complete_id()] = ChoiceField(
|
||||
widget=RadioSelect,
|
||||
label=q.question,
|
||||
choices=[(a.pk, a.html_description()) for a in mas if a.question == q],
|
||||
required=True,
|
||||
)
|
||||
for a in mas:
|
||||
if a.question == q and a.valid_event(self.instance):
|
||||
self.fields[q.complete_id()].initial = a.pk
|
||||
break
|
||||
|
||||
class CategorisationForm(Form):
|
||||
|
||||
class CategorisationForm(Form):
|
||||
def __init__(self, *args, **kwargs):
|
||||
if "events" in kwargs:
|
||||
events = kwargs.pop('events', None)
|
||||
events = kwargs.pop("events", None)
|
||||
else:
|
||||
events = []
|
||||
for f in args[0]:
|
||||
logger.warning('fff: ' + f)
|
||||
if '_' not in f:
|
||||
if f + '_cat' in args[0]:
|
||||
events.append((Event.objects.get(pk=int(f)), args[0][f + '_cat']))
|
||||
logger.warning("fff: " + f)
|
||||
if "_" not in f:
|
||||
if f + "_cat" in args[0]:
|
||||
events.append(
|
||||
(Event.objects.get(pk=int(f)), args[0][f + "_cat"])
|
||||
)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
for e, c in events:
|
||||
self.fields[str(e.pk)] = BooleanField(initial=False, label=_('Apply category {} to the event {}').format(c, e.title), required=False)
|
||||
self.fields[str(e.pk)] = BooleanField(
|
||||
initial=False,
|
||||
label=_("Apply category {} to the event {}").format(c, e.title),
|
||||
required=False,
|
||||
)
|
||||
self.fields[str(e.pk) + "_cat"] = CharField(initial=c, widget=HiddenInput())
|
||||
|
||||
def get_validated(self):
|
||||
return [(e, self.cleaned_data.get(e + '_cat')) for e in self.fields if '_' not in e and self.cleaned_data.get(e)]
|
||||
return [
|
||||
(e, self.cleaned_data.get(e + "_cat"))
|
||||
for e in self.fields
|
||||
if "_" not in e and self.cleaned_data.get(e)
|
||||
]
|
||||
|
||||
|
||||
class EventAddPlaceForm(Form):
|
||||
|
||||
place = ModelChoiceField(label=_("Place"), queryset=Place.objects.all().order_by("name"), empty_label=_("Create a missing place"), required=False)
|
||||
place = ModelChoiceField(
|
||||
label=_("Place"),
|
||||
queryset=Place.objects.all().order_by("name"),
|
||||
empty_label=_("Create a missing place"),
|
||||
required=False,
|
||||
)
|
||||
add_alias = BooleanField(initial=True, required=False)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.instance = kwargs.pop('instance', False)
|
||||
self.instance = kwargs.pop("instance", False)
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.instance.location:
|
||||
self.fields["add_alias"].label = _("Add \"{}\" to the aliases of the place").format(self.instance.location)
|
||||
self.fields["add_alias"].label = _(
|
||||
'Add "{}" to the aliases of the place'
|
||||
).format(self.instance.location)
|
||||
else:
|
||||
self.fields.pop("add_alias")
|
||||
|
||||
def modified_event(self):
|
||||
return self.cleaned_data.get('place')
|
||||
return self.cleaned_data.get("place")
|
||||
|
||||
def save(self):
|
||||
if self.cleaned_data.get("place"):
|
||||
place = self.cleaned_data.get("place")
|
||||
self.instance.exact_location = place
|
||||
self.instance.save()
|
||||
if self.cleaned_data.get('add_alias'):
|
||||
if self.cleaned_data.get("add_alias"):
|
||||
place.aliases.append(self.instance.location)
|
||||
place.save()
|
||||
|
||||
|
||||
return self.instance
|
||||
|
||||
|
||||
class PlaceForm(ModelForm):
|
||||
apply_to_all = BooleanField(initial=True, label=_('On saving, use aliases to detect all matching events with missing place'), required=False)
|
||||
apply_to_all = BooleanField(
|
||||
initial=True,
|
||||
label=_(
|
||||
"On saving, use aliases to detect all matching events with missing place"
|
||||
),
|
||||
required=False,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Place
|
||||
fields = '__all__'
|
||||
widgets = {
|
||||
'location': TextInput()
|
||||
}
|
||||
|
||||
def as_grid(self):
|
||||
return mark_safe('<div class="grid"><div>' + super().as_p() + '</div><div><div class="map-widget">' +
|
||||
'<div id="map_location" style="width: 100%; aspect-ratio: 16/9"></div><p>Cliquez pour ajuster la position GPS</p></div></div></div>')
|
||||
fields = "__all__"
|
||||
widgets = {"location": TextInput()}
|
||||
|
||||
def as_grid(self):
|
||||
return mark_safe(
|
||||
'<div class="grid"><div>'
|
||||
+ super().as_p()
|
||||
+ '</div><div><div class="map-widget">'
|
||||
+ '<div id="map_location" style="width: 100%; aspect-ratio: 16/9"></div><p>Cliquez pour ajuster la position GPS</p></div></div></div>'
|
||||
)
|
||||
|
||||
def apply(self):
|
||||
return self.cleaned_data.get("apply_to_all")
|
||||
return self.cleaned_data.get("apply_to_all")
|
||||
|
||||
Reference in New Issue
Block a user