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 1721 additions and 517 deletions
# 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,
......
......@@ -153,13 +153,6 @@
"event": 2
}
},
{
"model": "AKModel.aktag",
"pk": 1,
"fields": {
"name": "metametameta"
}
},
{
"model": "AKModel.akrequirement",
"pk": 1,
......@@ -200,6 +193,14 @@
"event": 2
}
},
{
"model": "AKModel.aktype",
"pk": 1,
"fields": {
"name": "Input",
"event": 2
}
},
{
"model": "AKModel.historicalak",
"pk": 1,
......@@ -213,7 +214,6 @@
"reso": false,
"present": true,
"notes": "",
"interest": -1,
"category": 4,
"track": null,
"event": 2,
......@@ -236,7 +236,6 @@
"reso": false,
"present": true,
"notes": "",
"interest": -1,
"category": 4,
"track": null,
"event": 2,
......@@ -259,7 +258,6 @@
"reso": false,
"present": null,
"notes": "",
"interest": -1,
"category": 5,
"track": null,
"event": 2,
......@@ -282,7 +280,6 @@
"reso": false,
"present": null,
"notes": "",
"interest": -1,
"category": 5,
"track": null,
"event": 2,
......@@ -305,7 +302,6 @@
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"interest": -1,
"category": 3,
"track": null,
"event": 2,
......@@ -328,7 +324,6 @@
"reso": false,
"present": null,
"notes": "We need to find a volunteer first...",
"interest": -1,
"category": 3,
"track": null,
"event": 2,
......@@ -351,7 +346,6 @@
"reso": false,
"present": null,
"notes": "",
"interest": -1,
"category": 5,
"track": 1,
"event": 2,
......@@ -377,11 +371,11 @@
"notes": "",
"interest": -1,
"interest_counter": 0,
"include_in_export": false,
"event": 2,
"owners": [
1
],
"tags": [],
"requirements": [
3
],
......@@ -409,9 +403,6 @@
"owners": [
2
],
"tags": [
1
],
"requirements": [],
"conflicts": [],
"prerequisites": []
......@@ -435,7 +426,6 @@
"interest_counter": 0,
"event": 2,
"owners": [],
"tags": [],
"requirements": [
4
],
......@@ -523,6 +513,19 @@
"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,
......
"""
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'),
),
]
# Generated by Django 4.1.9 on 2023-05-15 18:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0057_upgrades'),
]
operations = [
migrations.AlterModelOptions(
name='ak',
options={'ordering': ['pk'], 'verbose_name': 'AK', 'verbose_name_plural': 'AKs'},
),
]
# Generated by Django 4.2.11 on 2024-04-21 14:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0058_alter_ak_options'),
]
operations = [
migrations.AlterField(
model_name='event',
name='interest_start',
field=models.DateTimeField(blank=True, help_text='Opening time for expression of interest. When left blank, no interest indication will be possible.', null=True, verbose_name='Interest Window Start'),
),
]
# Generated by Django 4.2.11 on 2024-04-24 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0059_interest_default'),
]
operations = [
migrations.AddField(
model_name='akorgamessage',
name='resolved',
field=models.BooleanField(default=False, help_text='This message has been resolved (no further action needed)', verbose_name='Resolved'),
),
]
# Generated by Django 4.2.13 on 2025-02-25 20:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0060_orga_message_resolved'),
]
operations = [
migrations.CreateModel(
name='AKType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Name describing the type', max_length=128, verbose_name='Name')),
('event', models.ForeignKey(help_text='Associated event', on_delete=django.db.models.deletion.CASCADE, to='AKModel.event', verbose_name='Event')),
],
options={
'verbose_name': 'AK Type',
'verbose_name_plural': 'AK Types',
'ordering': ['name'],
'unique_together': {('event', 'name')},
},
),
migrations.AddField(
model_name='ak',
name='types',
field=models.ManyToManyField(blank=True, help_text='This AK is', to='AKModel.aktype', verbose_name='Types'),
),
]
# Generated by Django 4.2.13 on 2025-02-26 22:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0061_types'),
]
operations = [
migrations.RemoveField(
model_name='historicalak',
name='interest',
),
]
# Generated by Django 4.2.13 on 2025-03-03 19:59
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AKModel', '0062_interest_no_history'),
]
operations = [
migrations.AlterField(
model_name='ak',
name='name',
field=models.CharField(help_text='Name of the AK', max_length=256, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+'), django.core.validators.RegexValidator(message='Must contain at least one letter or digit', regex='[\\w\\s]+')], verbose_name='Name'),
),
migrations.AlterField(
model_name='ak',
name='short_name',
field=models.CharField(blank=True, help_text='Name displayed in the schedule', max_length=64, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+')], verbose_name='Short Name'),
),
migrations.AlterField(
model_name='akowner',
name='name',
field=models.CharField(help_text='Name to identify an AK owner by', max_length=64, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+'), django.core.validators.RegexValidator(message='Must contain at least one letter or digit', regex='[\\w\\s]+')], verbose_name='Nickname'),
),
migrations.AlterField(
model_name='historicalak',
name='name',
field=models.CharField(help_text='Name of the AK', max_length=256, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+'), django.core.validators.RegexValidator(message='Must contain at least one letter or digit', regex='[\\w\\s]+')], verbose_name='Name'),
),
migrations.AlterField(
model_name='historicalak',
name='short_name',
field=models.CharField(blank=True, help_text='Name displayed in the schedule', max_length=64, validators=[django.core.validators.RegexValidator(inverse_match=True, message='May not contain quotation marks', regex='[\'\\"´`]+')], verbose_name='Short Name'),
),
]
This diff is collapsed.
......@@ -4,36 +4,54 @@ from AKModel.models import AK, Room, AKSlot, AKTrack, AKCategory, AKOwner
class AKOwnerSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKOwner
"""
class Meta:
model = AKOwner
fields = '__all__'
class AKCategorySerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKCategory
"""
class Meta:
model = AKCategory
fields = '__all__'
class AKTrackSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKTrack
"""
class Meta:
model = AKTrack
fields = '__all__'
class AKSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AK
"""
class Meta:
model = AK
fields = '__all__'
class RoomSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for Room
"""
class Meta:
model = Room
fields = '__all__'
class AKSlotSerializer(serializers.ModelSerializer):
"""
REST Framework Serializer for AKSlot
"""
class Meta:
model = AKSlot
fields = '__all__'
......@@ -41,6 +59,9 @@ class AKSlotSerializer(serializers.ModelSerializer):
treat_as_local = serializers.BooleanField(required=False, default=False, write_only=True)
def create(self, validated_data:dict):
# Handle timezone adaption based upon the control field "treat_as_local":
# If it is set, ignore timezone submitted from the browser (will always be UTC)
# and treat it as input in the events timezone instead
if validated_data['treat_as_local']:
validated_data['start'] = validated_data['start'].replace(tzinfo=None).astimezone(
validated_data['event'].timezone)
......
from django.contrib.admin import AdminSite
from django.utils.translation import gettext_lazy as _
# from django.urls import path
from AKModel.models import Event
class AKAdminSite(AdminSite):
"""
Custom admin interface definition (extend the admin functionality of Django)
"""
index_template = "admin/ak_index.html"
site_header = f"AKPlanning - {_('Administration')}"
index_title = _('Administration')
def get_urls(self):
from django.urls import path
"""
Get URLs -- add further views that are not related to a certain model here if needed
"""
urls = super().get_urls()
urls += [
# path('...', self.admin_view(...)),
......@@ -19,6 +24,8 @@ class AKAdminSite(AdminSite):
return urls
def index(self, request, extra_context=None):
# Override index page rendering to provide extra context (the list of active events)
# to be used in the adapted template
if extra_context is None:
extra_context = {}
extra_context["active_events"] = Event.objects.filter(active=True)
......