django_coreprotect/admin.py

55 lines
1.9 KiB
Python
Raw Permalink Normal View History

import ast
from django import forms
from django.contrib import admin
from django.contrib.admin import widgets as admin_widgets
from django_coreprotect.models import CoWorld, Preset
from django_coreprotect.utils import time_to_form, form_to_time
class PresetAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PresetAdminForm, self).__init__(*args, **kwargs)
worlds = tuple([(world.id, world.world) for world in CoWorld.objects.all()])
self.fields['worlds'].widget = forms.SelectMultiple(choices=worlds)
self.fields['date_from'].widget = admin_widgets.AdminSplitDateTime()
self.fields['date_to'].widget = admin_widgets.AdminSplitDateTime()
if self.instance:
if "worlds" in self.initial and self.initial["worlds"]:
self.initial["worlds"] = tuple(self.initial["worlds"])
if "date_from" in self.initial and self.initial["date_from"]:
self.initial["date_from"] = time_to_form(self.initial["date_from"])
if "date_to" in self.initial and self.initial["date_to"]:
self.initial["date_to"] = time_to_form(self.initial["date_to"])
def clean(self):
cleaned = super(PresetAdminForm, self).clean()
worlds = cleaned.get("worlds", "")
if worlds:
worlds = ast.literal_eval(worlds)
cleaned.update({"worlds": ",".join(worlds)})
date_from = cleaned.get("date_from", "")
if date_from:
cleaned.update({"date_from": form_to_time(date_from)})
date_to = cleaned.get("date_to", "")
if date_to:
cleaned.update({"date_to": form_to_time(date_to)})
return cleaned
class Meta:
model = Preset
fields = "__all__"
class PresetAdmin(admin.ModelAdmin):
form = PresetAdminForm
try:
admin.site.register(Preset, PresetAdmin)
except admin.sites.AlreadyRegistered:
pass