Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • konstantin/akplanning
  • matedealer/akplanning
  • kif/akplanning
  • mirco/akplanning
  • lordofthevoid/akplanning
  • voidptr/akplanning
  • xayomer/akplanning-fork
  • mollux/akplanning
  • neumantm/akplanning
  • mmarx/akplanning
  • nerf/akplanning
  • felix_bonn/akplanning
  • sebastian.uschmann/akplanning
13 results
Show changes
Showing
with 2383 additions and 500 deletions
# This part of the code was adapted from pretalx (https://github.com/pretalx/pretalx)
# Copyright 2017-2019, Tobias Kunze
# Original Copyrights licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
# Changes are marked in the code
# Documentation was mainly added by us, other changes are marked in the code
from django.utils import timezone
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer
......@@ -10,19 +10,35 @@ from AKModel.availability.models import Availability
class AvailabilitySerializer(ModelSerializer):
"""
REST Framework Serializer for Availability
"""
allDay = SerializerMethodField()
start = SerializerMethodField()
end = SerializerMethodField()
def get_allDay(self, obj):
def get_allDay(self, obj): # pylint: disable=invalid-name
"""
Bridge between naming conventions of python and fullcalendar by providing the all_day field as allDay, too
"""
return obj.all_day
# Use already localized strings in serialized field
# (default would be UTC, but that would require heavy timezone calculation on client side)
def get_start(self, obj):
"""
Get start timestamp
Use already localized strings in serialized field
(default would be UTC, but that would require heavy timezone calculation on client side)
"""
return timezone.localtime(obj.start, obj.event.timezone).strftime("%Y-%m-%dT%H:%M:%S")
def get_end(self, obj):
"""
Get end timestamp
Use already localized strings in serialized field
(default would be UTC, but that would require heavy timezone calculation on client side)
"""
return timezone.localtime(obj.end, obj.event.timezone).strftime("%Y-%m-%dT%H:%M:%S")
class Meta:
......
# environment.py
"""
Environment definitions
Needed for tex compilation
"""
import re
from django_tex.environment import environment
# Used to filter all very special UTF-8 chars that are probably not contained in the LaTeX fonts
# and would hence cause compilation errors
utf8_replace_pattern = re.compile(u'[^\u0000-\u206F]', re.UNICODE)
utf8_replace_pattern = re.compile('[^\u0000-\u206F]', re.UNICODE)
def latex_escape_utf8(value):
......@@ -17,12 +20,14 @@ def latex_escape_utf8(value):
:return: escaped string
:rtype: str
"""
return utf8_replace_pattern.sub('', value).replace('&', '\&').replace('_', '\_').replace('#', '\#').replace('$',
'\$').replace(
'%', '\%').replace('{', '\{').replace('}', '\}')
return (utf8_replace_pattern.sub('', value).replace('&', r'\&').replace('_', r'\_').replace('#', r'\#').
replace('$', r'\$').replace('%', r'\%').replace('{', r'\{').replace('}', r'\}'))
def improved_tex_environment(**options):
"""
Encapsulate our improved latex environment for usage
"""
env = environment(**options)
env.filters.update({
'latex_escape_utf8': latex_escape_utf8,
......
[
{
"model": "AKModel.event",
"pk": 1,
"fields": {
"name": "KIF 23",
"slug": "kif23",
"place": "Neuland",
"timezone": "Europe/Berlin",
"start": "2020-10-01T17:41:22Z",
"end": "2020-10-04T17:41:30Z",
"reso_deadline": "2020-10-03T10:00:00Z",
"interest_start": null,
"interest_end": null,
"public": true,
"active": false,
"plan_hidden": true,
"plan_published_at": null,
"base_url": "",
"wiki_export_template_name": "",
"default_slot": "2.00",
"contact_email": "dummy@eyample.org"
}
},
{
"model": "AKModel.event",
"pk": 2,
"fields": {
"name": "KIF 42",
"slug": "kif42",
"place": "Neuland noch neuer",
"timezone": "Europe/Berlin",
"start": "2020-11-06T17:51:26Z",
"end": "2020-11-10T17:51:27Z",
"reso_deadline": "2020-11-08T17:51:42Z",
"interest_start": null,
"interest_end": null,
"public": true,
"active": true,
"plan_hidden": false,
"plan_published_at": "2022-12-01T21:50:01Z",
"base_url": "",
"wiki_export_template_name": "",
"default_slot": "2.00",
"contact_email": "dummy@example.org"
}
},
{
"model": "AKModel.akowner",
"pk": 1,
"fields": {
"name": "a",
"slug": "a",
"institution": "Uni X",
"link": "",
"event": 2
}
},
{
"model": "AKModel.akowner",
"pk": 2,
"fields": {
"name": "b",
"slug": "b",
"institution": "Hochschule Y",
"link": "",
"event": 2
}
},
{
"model": "AKModel.akowner",
"pk": 3,
"fields": {
"name": "c",
"slug": "c",
"institution": "",
"link": "",
"event": 1
}
},
{
"model": "AKModel.akowner",
"pk": 4,
"fields": {
"name": "d",
"slug": "d",
"institution": "",
"link": "",
"event": 1
}
},
{
"model": "AKModel.akcategory",
"pk": 1,
"fields": {
"name": "Spa▀",
"color": "275246",
"description": "",
"present_by_default": true,
"event": 1
}
},
{
"model": "AKModel.akcategory",
"pk": 2,
"fields": {
"name": "Ernst",
"color": "234567",
"description": "",
"present_by_default": true,
"event": 1
}
},
{
"model": "AKModel.akcategory",
"pk": 3,
"fields": {
"name": "Spa▀/Kultur",
"color": "333333",
"description": "",
"present_by_default": true,
"event": 2
}
},
{
"model": "AKModel.akcategory",
"pk": 4,
"fields": {
"name": "Inhalt",
"color": "456789",
"description": "",
"present_by_default": true,
"event": 2
}
},
{
"model": "AKModel.akcategory",
"pk": 5,
"fields": {
"name": "Meta",
"color": "111111",
"description": "",
"present_by_default": true,
"event": 2
}
},
{
"model": "AKModel.aktrack",
"pk": 1,
"fields": {
"name": "Track 1",
"color": "",
"event": 2
}
},
{
"model": "AKModel.akrequirement",
"pk": 1,
"fields": {
"name": "Beamer",
"event": 1
}
},
{
"model": "AKModel.akrequirement",
"pk": 2,
"fields": {
"name": "Internet",
"event": 1
}
},
{
"model": "AKModel.akrequirement",
"pk": 3,
"fields": {
"name": "BBB",
"event": 2
}
},
{
"model": "AKModel.akrequirement",
"pk": 4,
"fields": {
"name": "Mumble",
"event": 2
}
},
{
"model": "AKModel.akrequirement",
"pk": 5,
"fields": {
"name": "Matrix",
"event": 2
}
},
{
"model": "AKModel.aktype",
"pk": 1,
"fields": {
"name": "Input",
"event": 2
}
},
{
"model": "AKModel.historicalak",
"pk": 1,
"fields": {
"id": 1,
"name": "Test AK Inhalt",
"short_name": "test1",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": true,
"notes": "",
"category": 4,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:28:59.265Z",
"history_change_reason": null,
"history_type": "+",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 2,
"fields": {
"id": 1,
"name": "Test AK Inhalt",
"short_name": "test1",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": true,
"notes": "",
"category": 4,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:28:59.305Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 3,
"fields": {
"id": 2,
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "",
"category": 5,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:29:40.296Z",
"history_change_reason": null,
"history_type": "+",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 4,
"fields": {
"id": 2,
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "",
"category": 5,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:29:40.355Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 5,
"fields": {
"id": 3,
"name": "AK Wish",
"short_name": "wish1",
"description": "Description of my Wish",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"category": 3,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:30:59.469Z",
"history_change_reason": null,
"history_type": "+",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 6,
"fields": {
"id": 3,
"name": "AK Wish",
"short_name": "wish1",
"description": "Description of my Wish",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"category": 3,
"track": null,
"event": 2,
"history_date": "2021-05-04T10:30:59.509Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.historicalak",
"pk": 7,
"fields": {
"id": 2,
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"reso": false,
"present": null,
"notes": "",
"category": 5,
"track": 1,
"event": 2,
"history_date": "2022-12-02T12:27:14.277Z",
"history_change_reason": null,
"history_type": "~",
"history_user": null
}
},
{
"model": "AKModel.ak",
"pk": 1,
"fields": {
"name": "Test AK Inhalt",
"short_name": "test1",
"description": "",
"link": "",
"protocol_link": "",
"category": 4,
"track": null,
"reso": false,
"present": true,
"notes": "",
"interest": -1,
"interest_counter": 0,
"include_in_export": false,
"event": 2,
"owners": [
1
],
"requirements": [
3
],
"conflicts": [],
"prerequisites": []
}
},
{
"model": "AKModel.ak",
"pk": 2,
"fields": {
"name": "Test AK Meta",
"short_name": "test2",
"description": "",
"link": "",
"protocol_link": "",
"category": 5,
"track": 1,
"reso": false,
"present": null,
"notes": "",
"interest": -1,
"interest_counter": 0,
"event": 2,
"owners": [
2
],
"requirements": [],
"conflicts": [],
"prerequisites": []
}
},
{
"model": "AKModel.ak",
"pk": 3,
"fields": {
"name": "AK Wish",
"short_name": "wish1",
"description": "Description of my Wish",
"link": "",
"protocol_link": "",
"category": 3,
"track": null,
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"interest": -1,
"interest_counter": 0,
"event": 2,
"owners": [],
"requirements": [
4
],
"conflicts": [
1
],
"prerequisites": [
2
]
}
},
{
"model": "AKModel.room",
"pk": 1,
"fields": {
"name": "Testraum",
"location": "BBB",
"capacity": -1,
"event": 2,
"properties": [
3
]
}
},
{
"model": "AKModel.room",
"pk": 2,
"fields": {
"name": "Testraum 2",
"location": "",
"capacity": 30,
"event": 2,
"properties": []
}
},
{
"model": "AKModel.akslot",
"pk": 1,
"fields": {
"ak": 1,
"room": 2,
"start": "2020-11-06T18:30:00Z",
"duration": "2.00",
"fixed": false,
"event": 2,
"updated": "2022-12-02T12:23:11.856Z"
}
},
{
"model": "AKModel.akslot",
"pk": 2,
"fields": {
"ak": 2,
"room": 1,
"start": "2020-11-08T12:30:00Z",
"duration": "2.00",
"fixed": false,
"event": 2,
"updated": "2022-12-02T12:23:18.279Z"
}
},
{
"model": "AKModel.akslot",
"pk": 3,
"fields": {
"ak": 3,
"room": null,
"start": null,
"duration": "1.50",
"fixed": false,
"event": 2,
"updated": "2021-05-04T10:30:59.523Z"
}
},
{
"model": "AKModel.akslot",
"pk": 4,
"fields": {
"ak": 3,
"room": null,
"start": null,
"duration": "3.00",
"fixed": false,
"event": 2,
"updated": "2021-05-04T10:30:59.528Z"
}
},
{
"model": "AKModel.akslot",
"pk": 5,
"fields": {
"ak": 1,
"room": null,
"start": null,
"duration": "2.00",
"fixed": false,
"event": 2,
"updated": "2022-12-02T12:23:11.856Z"
}
},
{
"model": "AKModel.constraintviolation",
"pk": 1,
"fields": {
"type": "soa",
"level": 10,
"event": 2,
"ak_owner": null,
"room": null,
"requirement": null,
"category": null,
"comment": "",
"timestamp": "2022-12-02T12:23:11.875Z",
"manually_resolved": false,
"aks": [
1
],
"ak_slots": [
1
]
}
},
{
"model": "AKModel.constraintviolation",
"pk": 2,
"fields": {
"type": "rng",
"level": 10,
"event": 2,
"ak_owner": null,
"room": 2,
"requirement": 3,
"category": null,
"comment": "",
"timestamp": "2022-12-02T12:23:11.890Z",
"manually_resolved": false,
"aks": [
1
],
"ak_slots": [
1
]
}
},
{
"model": "AKModel.constraintviolation",
"pk": 3,
"fields": {
"type": "soa",
"level": 10,
"event": 2,
"ak_owner": null,
"room": null,
"requirement": null,
"category": null,
"comment": "",
"timestamp": "2022-12-02T12:23:18.301Z",
"manually_resolved": false,
"aks": [
2
],
"ak_slots": [
2
]
}
},
{
"model": "AKModel.availability",
"pk": 1,
"fields": {
"event": 2,
"person": null,
"room": null,
"ak": 1,
"ak_category": null,
"start": "2020-11-07T08:00:00Z",
"end": "2020-11-07T18:00:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 2,
"fields": {
"event": 2,
"person": null,
"room": null,
"ak": 1,
"ak_category": null,
"start": "2020-11-09T10:00:00Z",
"end": "2020-11-09T16:30:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 3,
"fields": {
"event": 2,
"person": null,
"room": 1,
"ak": null,
"ak_category": null,
"start": "2020-11-06T17:51:26Z",
"end": "2020-11-10T23:00:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 4,
"fields": {
"event": 2,
"person": null,
"room": 2,
"ak": null,
"ak_category": null,
"start": "2020-11-06T17:51:26Z",
"end": "2020-11-06T21:00:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 5,
"fields": {
"event": 2,
"person": null,
"room": 2,
"ak": null,
"ak_category": null,
"start": "2020-11-08T15:30:00Z",
"end": "2020-11-08T19:30:00Z"
}
},
{
"model": "AKModel.availability",
"pk": 6,
"fields": {
"event": 2,
"person": null,
"room": 2,
"ak": null,
"ak_category": null,
"start": "2020-11-07T18:30:00Z",
"end": "2020-11-07T21:30:00Z"
}
}
]
"""
Central and admin forms
"""
import csv
import io
from bootstrap_datepicker_plus import DateTimePickerInput
from django import forms
from django.forms.utils import ErrorList
from django.utils.translation import gettext_lazy as _
from AKModel.models import Event, AKCategory, AKRequirement
from AKModel.availability.forms import AvailabilitiesFormMixin
from AKModel.models import Event, AKCategory, AKRequirement, Room, AKType
class DateTimeInput(forms.DateInput):
"""
Simple widget for datetime input fields using the HTML5 datetime-local input type
"""
input_type = 'datetime-local'
class NewEventWizardStartForm(forms.ModelForm):
"""
Initial view of new event wizard
This form is a model form for Event, but only with a subset of the required fields.
It is therefore not possible to really create an event using this form, but only to enter
information, in particular the timezone, that is needed to correctly handle/parse the user
inputs for further required fields like start and end of the event.
The form will be used for this partial input, the input of the remaining required fields
will then be handled by :class:`NewEventWizardSettingsForm` (see below).
"""
class Meta:
model = Event
fields = ['name', 'slug', 'timezone', 'plan_hidden']
......@@ -17,26 +39,40 @@ class NewEventWizardStartForm(forms.ModelForm):
'plan_hidden': forms.HiddenInput(),
}
# Special hidden field for wizard state handling
is_init = forms.BooleanField(initial=True, widget=forms.HiddenInput)
class NewEventWizardSettingsForm(forms.ModelForm):
"""
Form for second view of the event creation wizard.
Will handle the input of the remaining required as well as some optional fields.
See also :class:`NewEventWizardStartForm`.
"""
class Meta:
model = Event
exclude = []
fields = "__all__"
exclude = ['plan_published_at']
widgets = {
'name': forms.HiddenInput(),
'slug': forms.HiddenInput(),
'timezone': forms.HiddenInput(),
'active': forms.HiddenInput(),
'start': DateTimePickerInput(options={"format": "YYYY-MM-DD HH:mm"}),
'end': DateTimePickerInput(options={"format": "YYYY-MM-DD HH:mm"}),
'reso_deadline': DateTimePickerInput(options={"format": "YYYY-MM-DD HH:mm"}),
'start': DateTimeInput(),
'end': DateTimeInput(),
'interest_start': DateTimeInput(),
'interest_end': DateTimeInput(),
'reso_deadline': DateTimeInput(),
'plan_hidden': forms.HiddenInput(),
}
class NewEventWizardPrepareImportForm(forms.Form):
"""
Wizard form for choosing an event to import/copy elements (requirements, categories, etc) from.
Is used to restrict the list of elements to choose from in the next step (see :class:`NewEventWizardImportForm`).
"""
import_event = forms.ModelChoiceField(
queryset=Event.objects.all(),
label=_("Copy ak requirements and ak categories of existing event"),
......@@ -45,6 +81,12 @@ class NewEventWizardPrepareImportForm(forms.Form):
class NewEventWizardImportForm(forms.Form):
"""
Wizard form for excaclty choosing which elemments to copy/import for the newly created event.
Possible elements are categories, requirements, and dashboard buttons if AKDashboard is active.
The lists are restricted to elements from the event selected in the previous step
(see :class:`NewEventWizardPrepareImportForm`).
"""
import_categories = forms.ModelMultipleChoiceField(
queryset=AKCategory.objects.all(),
widget=forms.CheckboxSelectMultiple,
......@@ -59,6 +101,14 @@ class NewEventWizardImportForm(forms.Form):
required=False,
)
import_types = forms.ModelMultipleChoiceField(
queryset=AKType.objects.all(),
widget=forms.CheckboxSelectMultiple,
label=_("Copy types"),
required=False,
)
# pylint: disable=too-many-arguments
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None,
renderer=None):
......@@ -68,23 +118,55 @@ class NewEventWizardImportForm(forms.Form):
event=self.initial["import_event"])
self.fields["import_requirements"].queryset = self.fields["import_requirements"].queryset.filter(
event=self.initial["import_event"])
self.fields["import_types"].queryset = self.fields["import_types"].queryset.filter(
event=self.initial["import_event"])
# pylint: disable=import-outside-toplevel
# Local imports used to prevent cyclic imports and to only import when AKDashboard is available
from django.apps import apps
if apps.is_installed("AKDashboard"):
# If AKDashboard is active, allow to copy dashboard buttons, too
from AKDashboard.models import DashboardButton
self.fields["import_buttons"] = forms.ModelMultipleChoiceField(
queryset=DashboardButton.objects.filter(event=self.initial["import_event"]),
widget=forms.CheckboxSelectMultiple,
label=_("Copy dashboard buttons"),
required=False,
)
class NewEventWizardActivateForm(forms.ModelForm):
"""
Wizard form to activate the newly created event
"""
class Meta:
fields = ["active"]
model = Event
class AdminIntermediateForm(forms.Form):
pass
"""
Base form for admin intermediate views (forms used there should inherit from this,
by default, the form is empty since it is only needed for the confirmation button)
"""
class AdminIntermediateActionForm(AdminIntermediateForm):
"""
Form for Admin Action Confirmation views -- has a pks field needed to handle the serialization/deserialization of
the IDs of the entities the user selected for the admin action to be performed on
"""
pks = forms.CharField(widget=forms.HiddenInput)
class SlideExportForm(AdminIntermediateForm):
"""
Form to control the slides generated from the AK list of an event
The user can select how many upcoming AKs are displayed at the footer to inform people that it is their turn soon,
whether the AK list should be restricted to those AKs that where marked for presentation, and whether ther should
be a symbol and empty space to take notes on for wishes
"""
num_next = forms.IntegerField(
min_value=0,
max_value=6,
......@@ -109,10 +191,14 @@ class SlideExportForm(AdminIntermediateForm):
class DefaultSlotEditorForm(AdminIntermediateForm):
"""
Form for default slot editor
"""
availabilities = forms.CharField(
label=_('Default Slots'),
help_text=_(
'Click and drag to mark the availability during the event, double-click to delete.' # Adapted help text
'Click and drag to add default slots, double-click to delete. '
'Or use the start and end inputs to add entries to the calendar view.'
),
widget=forms.TextInput(attrs={'class': 'availabilities-editor-data'}),
required=True,
......@@ -120,6 +206,12 @@ class DefaultSlotEditorForm(AdminIntermediateForm):
class RoomBatchCreationForm(AdminIntermediateForm):
"""
Form for room batch creation
Allows to input a list of room details and choose whether default availabilities should be generated for these
rooms. Will check that the input follows a CSV format with at least a name column present.
"""
rooms = forms.CharField(
label=_('New rooms'),
help_text=_('Enter room details in CSV format. Required colum is "name", optional colums are "location", '
......@@ -127,8 +219,20 @@ class RoomBatchCreationForm(AdminIntermediateForm):
widget=forms.Textarea,
required=True,
)
create_default_availabilities = forms.BooleanField(
label=_('Default availabilities?'),
help_text=_('Create default availabilities for all rooms?'),
required=False
)
def clean_rooms(self):
"""
Validate and transform the input for the rooms textfield
Treat the input as CSV and turn it into a dict containing the relevant information.
:return: a dict containing the raw room information
:rtype: dict[str, str]
"""
rooms_raw_text = self.cleaned_data["rooms"]
rooms_raw_dict = csv.DictReader(io.StringIO(rooms_raw_text), delimiter=";")
......@@ -136,3 +240,44 @@ class RoomBatchCreationForm(AdminIntermediateForm):
raise forms.ValidationError(_("CSV must contain a name column"))
return rooms_raw_dict
class RoomForm(forms.ModelForm):
"""
Room (creation) form (basic), will be extended for handling of availabilities
(see :class:`RoomFormWithAvailabilities`) and also for creating hybrid rooms in AKOnline (if active)
"""
class Meta:
model = Room
fields = ['name',
'location',
'capacity',
'event',
]
class RoomFormWithAvailabilities(AvailabilitiesFormMixin, RoomForm):
"""
Room (update) form including handling of availabilities, extends :class:`RoomForm`
"""
class Meta:
model = Room
fields = ['name',
'location',
'capacity',
'properties',
'event',
]
widgets = {
'properties': forms.CheckboxSelectMultiple,
}
def __init__(self, *args, **kwargs):
# Init availability mixin
kwargs['initial'] = {}
super().__init__(*args, **kwargs)
self.initial = {**self.initial, **kwargs['initial']}
# Filter possible values for m2m when event is specified
if hasattr(self.instance, "event") and self.instance.event is not None:
self.fields["properties"].queryset = AKRequirement.objects.filter(event=self.instance.event)
"""
Ensure PO files are generated using forward slashes in the location comments on all operating systems
"""
import os
from django.core.management.commands.makemessages import Command as MakeMessagesCommand
class Command(MakeMessagesCommand):
"""
Adapted version of the :class:`MakeMessagesCommand`
Ensure PO files are generated using forward slashes in the location comments on all operating systems
"""
def find_files(self, root):
# Replace backward slashes with forward slashes if necessary in file list
all_files = super().find_files(root)
if os.sep != "\\":
return all_files
......@@ -21,17 +23,19 @@ class Command(MakeMessagesCommand):
return all_files
def build_potfiles(self):
# Replace backward slashes with forward slashes if necessary in the files itself
pot_files = super().build_potfiles()
if os.sep != "\\":
return pot_files
for filename in pot_files:
lines = open(filename, "r", encoding="utf-8").readlines()
fixed_lines = []
for line in lines:
if line.startswith("#: "):
line = line.replace("\\", "/")
fixed_lines.append(line)
with open(filename, "r", encoding="utf-8") as f:
lines = f.readlines()
fixed_lines = []
for line in lines:
if line.startswith("#: "):
line = line.replace("\\", "/")
fixed_lines.append(line)
with open(filename, "w", encoding="utf-8") as f:
f.writelines(fixed_lines)
......
from AKModel.metaviews.status import StatusManager
# create on instance of the :class:`AKModel.metaviews.status.StatusManager`
# that can then be accessed everywhere (singleton pattern)
status_manager = StatusManager()
from abc import ABC, abstractmethod
from django.contrib import admin, messages
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import FormView
from AKModel.forms import AdminIntermediateForm, AdminIntermediateActionForm
from AKModel.models import Event
class EventSlugMixin:
"""
Mixin to handle views with event slugs
This will make the relevant event available as self.event in all kind types of requests
(generic GET and POST views, list views, dispatching, create views)
"""
# pylint: disable=no-member
event = None
def _load_event(self):
"""
Perform the real loading of the event data (as specified by event_slug in the URL) into self.event
"""
# Find event based on event slug
if self.event is None:
self.event = get_object_or_404(Event, slug=self.kwargs.get("event_slug", None))
def get(self, request, *args, **kwargs):
"""
Override GET request handling to perform loading event first
"""
self._load_event()
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
"""
Override POST request handling to perform loading event first
"""
self._load_event()
return super().post(request, *args, **kwargs)
def list(self, request, *args, **kwargs):
"""
Override list view request handling to perform loading event first
"""
self._load_event()
return super().list(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
"""
Override create view request handling to perform loading event first
"""
self._load_event()
return super().create(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs):
"""
Override dispatch which is called in many generic views to perform loading event first
"""
if self.event is None:
self._load_event()
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, *, object_list=None, **kwargs):
"""
Override `get_context_data` to make the event information available in the rendering context as `event`. too
"""
context = super().get_context_data(object_list=object_list, **kwargs)
# Add event to context (to make it accessible in templates)
context["event"] = self.event
return context
class FilterByEventSlugMixin(EventSlugMixin):
"""
Mixin to filter different querysets based on a event slug from the request url
"""
def get_queryset(self):
"""
Get adapted queryset:
Filter current queryset based on url event slug or return 404 if event slug is invalid
:return: Queryset
"""
return super().get_queryset().filter(event=self.event)
class AdminViewMixin:
"""
Mixin to provide context information needed in custom admin views
Will either use default information for `site_url` and `title` or allows to set own values for that
"""
# pylint: disable=too-few-public-methods
site_url = ''
title = ''
def get_context_data(self, **kwargs):
"""
Extend context
"""
extra = admin.site.each_context(self.request)
extra.update(super().get_context_data(**kwargs))
if self.site_url != '':
extra["site_url"] = self.site_url
if self.title != '':
extra["title"] = self.title
return extra
class IntermediateAdminView(AdminViewMixin, FormView):
"""
Metaview: Handle typical "action but with preview and confirmation step before" workflow
"""
template_name = "admin/AKModel/action_intermediate.html"
form_class = AdminIntermediateForm
def get_preview(self):
"""
Render a preview of the action to be performed.
Default is empty
:return: preview (html)
:rtype: str
"""
return ""
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["title"] = self.title
context["preview"] = self.get_preview()
return context
class WizardViewMixin:
"""
Mixin to create wizard-like views.
This visualizes the progress of the user in the creation process and provides the interlinking to the next step
In the current implementation, the steps of the wizard are hardcoded here,
hence this mixin can only be used for the event creation wizard
"""
# pylint: disable=too-few-public-methods
def get_context_data(self, **kwargs):
"""
Extend context
"""
context = super().get_context_data(**kwargs)
context["wizard_step"] = self.wizard_step
context["wizard_steps"] = [
_("Start"),
_("Settings"),
_("Event created, Prepare Import"),
_("Import categories & requirements"),
_("Activate?"),
_("Finish")
]
context["wizard_step_text"] = context["wizard_steps"][self.wizard_step - 1]
context["wizard_steps_total"] = len(context["wizard_steps"])
return context
class IntermediateAdminActionView(IntermediateAdminView, ABC):
"""
Abstract base view: Intermediate action view (preview & confirmation see :class:`IntermediateAdminView`)
for custom admin actions (marking multiple objects in a django admin model instances list with a checkmark and then
choosing an action from the dropdown).
This will automatically handle the decoding of the URL encoding of the list of primary keys django does to select
which objects the action should be run on, then display a preview, perform the action after confirmation and
redirect again to the object list including display of a confirmation message
"""
# pylint: disable=no-member
form_class = AdminIntermediateActionForm
entities = None
def get_queryset(self, pks=None):
"""
Get the queryset of objects to perform the action on
"""
if pks is None:
pks = self.request.GET['pks']
return self.model.objects.filter(pk__in=pks.split(","))
def get_initial(self):
initial = super().get_initial()
initial['pks'] = self.request.GET['pks']
return initial
def get_preview(self):
self.entities = self.get_queryset()
joined_entities = '\n'.join(str(e) for e in self.entities)
return f"{self.confirmation_message}:\n\n {joined_entities}"
def get_success_url(self):
return reverse(f"admin:{self.model._meta.app_label}_{self.model._meta.model_name}_changelist")
@abstractmethod
def action(self, form):
"""
The real action to perform
:param form: form holding the data probably needed for the action
"""
def form_valid(self, form):
self.entities = self.get_queryset(pks=form.cleaned_data['pks'])
self.action(form)
messages.add_message(self.request, messages.SUCCESS, self.success_message)
return super().form_valid(form)
class LoopActionMixin(ABC):
"""
Mixin for the typical kind of action where one needs to loop over all elements
and perform a certain function on each of them
The action is performed by overriding `perform_action(self, entity)`
further customization can be reached with the two callbacks `pre_action()` and `post_action()`
that are called before and after performing the action loop
"""
def action(self, form): # pylint: disable=unused-argument
"""
The real action to perform.
Will perform the loop, perform the action on each aelement and call the callbacks
:param form: form holding the data probably needed for the action
"""
self.pre_action()
for entity in self.entities:
self.perform_action(entity)
entity.save()
self.post_action()
@abstractmethod
def perform_action(self, entity):
"""
Action to perform on each entity
:param entity: entity to perform the action on
"""
def pre_action(self):
"""
Callback for custom action before loop starts
"""
def post_action(self):
"""
Callback for custom action after loop finished
"""
from abc import ABC, abstractmethod
from collections import defaultdict
from django.template import loader
from django.views.generic import TemplateView
from AKModel.metaviews.admin import AdminViewMixin
class StatusWidget(ABC):
"""
Abstract parent for status page widgets
"""
title = "Status Widget"
actions = []
status = "primary"
@property
@abstractmethod
def required_context_type(self) -> str:
"""
Which model/context is needed to render this widget?
"""
def get_context_data(self, context) -> dict:
"""
Allow to manipulate the context
:return: context (with or without changes)
"""
return context
def render(self, context: {}, request) -> dict:
"""
Render widget based on context
:param context: Context for rendering
:param request: HTTP request, needed for rendering
:return: Dictionary containing the rendered/prepared information
"""
context = self.get_context_data(context)
return {
"body": self.render_body(context, request),
"title": self.render_title(context),
"actions": self.render_actions(context),
"status": self.render_status(context),
}
def render_title(self, context: {}) -> str: # pylint: disable=unused-argument
"""
Render title for widget based on context
By default, the title attribute is used without modification
:param context: Context for rendering
:return: Rendered title
"""
return self.title
def render_status(self, context: {}) -> str: # pylint: disable=unused-argument
"""
Render status for widget based on context
By default, the status attribute is used without modification
:param context: Context for rendering
:return: Rendered title
"""
return self.status
@abstractmethod
def render_body(self, context: {}, request) -> str: # pylint: disable=unused-argument
"""
Render body for widget based on context
:param context: Context for rendering
:param request: HTTP request (needed for rendering)
:return: Rendered widget body (HTML)
"""
def render_actions(self, context: {}) -> list[dict]: # pylint: disable=unused-argument
"""
Render actions for widget based on context
By default, all actions specified for this widget are returned without modification
:param context: Context for rendering
:return: List of actions
"""
return self.actions
class TemplateStatusWidget(StatusWidget):
"""
A :class:`StatusWidget` that produces its content by rendering a given html template
"""
@property
@abstractmethod
def template_name(self) -> str:
"""
Configure the template to use
:return: name of the template to use
"""
def render_body(self, context: {}, request) -> str:
"""
Render the body of the widget using the template rendering method from django
(load and render template using the provided context)
:param context: context to use for rendering
:param request: HTTP request (needed by django)
:return: rendered content (HTML)
"""
template = loader.get_template(self.template_name)
return template.render(context, request)
class StatusManager:
"""
Registry for all status widgets
Allows to register status widgets using the `@status_manager.register(name="xyz")` decorator
"""
widgets = {}
widgets_by_context_type = defaultdict(list)
def register(self, name: str):
"""
Call this as
@status_manager.register(name="xyz")
to register a status widget
:param name: name of this widget (only used internally). Has to be unique.
"""
def _register(widget_class):
w = widget_class()
self.widgets[name] = w
self.widgets_by_context_type[w.required_context_type].append(w)
return widget_class
return _register
def get_by_context_type(self, context_type: str):
"""
Filter widgets for ones suitable for provided context
:param context_type: name of the model provided as context
:return: a list of all matching widgets
"""
if context_type in self.widgets_by_context_type.keys():
return self.widgets_by_context_type[context_type]
return []
class StatusView(ABC, AdminViewMixin, TemplateView):
"""
Abstract view: A generic base view to create a status page holding multiple widgets
"""
template_name = "admin/AKModel/status/status.html"
@property
@abstractmethod
def provided_context_type(self) -> str:
"""
Which model/context is provided by this status view?
"""
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
# Load status manager (local import to prevent cyclic import)
from AKModel.metaviews import status_manager # pylint: disable=import-outside-toplevel
# Render all widgets and provide them as part of the context
context['widgets'] = [w.render(context, self.request)
for w in status_manager.get_by_context_type(self.provided_context_type)]
return self.render_to_response(context)
# Generated by Django 3.2.16 on 2022-12-26 22:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0054_default_slots'),
]
operations = [
migrations.AddField(
model_name='ak',
name='include_in_export',
field=models.BooleanField(default=True, help_text='Include AK in wiki export?', verbose_name='Export?'),
),
]
# Generated by Django 3.2.16 on 2023-01-01 18:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0055_ak_export'),
]
operations = [
migrations.RemoveField(
model_name='ak',
name='tags',
),
migrations.DeleteModel(
name='AKTag',
),
]
# Generated by Django 4.1.5 on 2023-01-03 17:04
from django.db import migrations
import timezone_field.fields
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0056_remove_tags'),
]
operations = [
migrations.AlterField(
model_name='event',
name='timezone',
field=timezone_field.fields.TimeZoneField(choices_display='WITH_GMT_OFFSET', default='Europe/Berlin', help_text='Time Zone where this event takes place in', verbose_name='Time Zone'),
),
]
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.