Skip to content

Commit 1df3490

Browse files
cleanup shorten and refactor the things
1 parent ea8ae43 commit 1df3490

File tree

2 files changed

+55
-60
lines changed

2 files changed

+55
-60
lines changed

src/django_github_app/admin.py

Lines changed: 47 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,66 @@
11
from __future__ import annotations
22

33
import datetime
4+
from collections.abc import Sequence
45

56
from django import forms
67
from django.contrib import admin
78
from django.contrib import messages
9+
from django.core.exceptions import ValidationError
10+
from django.http import HttpRequest
11+
from django.http import HttpResponse
812
from django.http import HttpResponseRedirect
913
from django.shortcuts import render
14+
from django.urls import URLPattern
15+
from django.urls import URLResolver
1016
from django.urls import path
1117
from django.urls import reverse
1218
from django.utils import timezone
1319

20+
from ._typing import override
1421
from .conf import app_settings
1522
from .models import EventLog
1623
from .models import Installation
1724
from .models import Repository
1825

1926

20-
def get_cleanup_form(model_meta, model_class):
21-
"""Create a cleanup form with model-specific help text and save method."""
22-
23-
class CleanupForm(forms.Form):
24-
days_to_keep = forms.IntegerField(
25-
label="Days to keep",
26-
min_value=0,
27-
initial=app_settings.DAYS_TO_KEEP_EVENTS,
28-
help_text=f"{model_meta.verbose_name_plural.capitalize()} older than this number of days will be deleted.",
29-
)
30-
31-
def get_queryset_to_delete(self):
32-
"""Get the queryset of objects that will be deleted."""
33-
days_to_keep = self.cleaned_data["days_to_keep"]
34-
cutoff_date = timezone.now() - datetime.timedelta(days=days_to_keep)
35-
return model_class.objects.filter(received_at__lte=cutoff_date)
36-
37-
def save(self):
38-
"""Delete the events and return the count."""
39-
days_to_keep = self.cleaned_data["days_to_keep"]
40-
deleted_count, _ = model_class.objects.cleanup_events(days_to_keep)
41-
return deleted_count
27+
class EventLogCleanupForm(forms.Form):
28+
days_to_keep = forms.IntegerField(
29+
label="Days to keep",
30+
min_value=0,
31+
initial=app_settings.DAYS_TO_KEEP_EVENTS,
32+
help_text="Event logs older than this number of days will be deleted.",
33+
)
34+
35+
def save(self) -> int:
36+
"""Delete the events and return the count."""
37+
days_to_keep = self.cleaned_data["days_to_keep"]
38+
deleted_count, _ = EventLog.objects.cleanup_events(days_to_keep)
39+
return deleted_count
40+
41+
@property
42+
def to_delete_count(self) -> int:
43+
if not hasattr(self, "cleaned_data"):
44+
raise ValidationError(
45+
"Form must be validated before accessing to_delete_count"
46+
)
47+
return EventLog.objects.filter(received_at__lte=self.cutoff_date).count()
4248

43-
return CleanupForm
49+
@property
50+
def cutoff_date(self) -> datetime.datetime:
51+
if not hasattr(self, "cleaned_data"):
52+
raise ValidationError("Form must be validated before accessing cutoff_date")
53+
days_to_keep = self.cleaned_data["days_to_keep"]
54+
return timezone.now() - datetime.timedelta(days=days_to_keep)
4455

4556

4657
@admin.register(EventLog)
4758
class EventLogModelAdmin(admin.ModelAdmin):
4859
list_display = ["id", "event", "action", "received_at"]
4960
readonly_fields = ["event", "payload", "received_at"]
5061

51-
def get_urls(self):
62+
@override
63+
def get_urls(self) -> Sequence[URLResolver | URLPattern]: # type: ignore[override]
5264
urls = super().get_urls()
5365
custom_urls = [
5466
path(
@@ -59,9 +71,8 @@ def get_urls(self):
5971
]
6072
return custom_urls + urls
6173

62-
def cleanup_view(self, request):
63-
CleanupForm = get_cleanup_form(self.model._meta, self.model)
64-
form = CleanupForm(request.POST or None)
74+
def cleanup_view(self, request: HttpRequest) -> HttpResponse:
75+
form = EventLogCleanupForm(request.POST or None)
6576

6677
# handle confirmation
6778
if request.POST.get("post") == "yes" and form.is_valid():
@@ -77,39 +88,20 @@ def cleanup_view(self, request):
7788
reverse("admin:django_github_app_eventlog_changelist")
7889
)
7990

80-
if form.is_valid():
81-
days_to_keep = form.cleaned_data["days_to_keep"]
82-
events_to_delete = form.get_queryset_to_delete()
83-
delete_count = events_to_delete.count()
84-
cutoff_date = timezone.now() - datetime.timedelta(days=days_to_keep)
85-
86-
context = {
87-
**self.admin_site.each_context(request),
88-
"title": f"Confirm {self.model._meta.verbose_name} deletion",
89-
"days_to_keep": days_to_keep,
90-
"delete_count": delete_count,
91-
"cutoff_date": cutoff_date,
92-
"opts": self.model._meta,
93-
"object_name": self.model._meta.verbose_name,
94-
"model_count": [(self.model._meta.verbose_name_plural, delete_count)]
95-
if delete_count
96-
else [],
97-
"perms_lacking": None,
98-
"protected": None,
99-
}
100-
return render(
101-
request,
102-
"admin/django_github_app/eventlog/cleanup_confirmation.html",
103-
context,
104-
)
105-
10691
context = {
10792
**self.admin_site.each_context(request),
108-
"title": f"Clean up {self.model._meta.verbose_name_plural}",
10993
"form": form,
11094
"opts": self.model._meta,
11195
}
112-
return render(request, "admin/django_github_app/eventlog/cleanup.html", context)
96+
97+
if form.is_valid():
98+
context["title"] = f"Confirm {self.model._meta.verbose_name} deletion"
99+
template = "cleanup_confirmation.html"
100+
else:
101+
context["title"] = f"Clean up {self.model._meta.verbose_name_plural}"
102+
template = "cleanup.html"
103+
104+
return render(request, f"admin/django_github_app/eventlog/{template}", context)
113105

114106

115107
@admin.register(Installation)

src/django_github_app/templates/admin/django_github_app/eventlog/cleanup_confirmation.html

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,22 @@
55
{% endblock %}
66
{% block delete_confirm %}
77
<p>
8-
{% blocktranslate count counter=delete_count with verbose_name=opts.verbose_name verbose_name_plural=opts.verbose_name_plural %}You are about to delete {{ counter }} {{ verbose_name }} older than {{ days_to_keep }} days.{% plural %}You are about to delete {{ counter }} {{ verbose_name_plural }} older than {{ days_to_keep }} days.{% endblocktranslate %}
8+
{% blocktranslate count counter=form.to_delete_count with verbose_name=opts.verbose_name verbose_name_plural=opts.verbose_name_plural days_to_keep=form.cleaned_data.days_to_keep %}You are about to delete {{ counter }} {{ verbose_name }} older than {{ days_to_keep }} days.{% plural %}You are about to delete {{ counter }} {{ verbose_name_plural }} older than {{ days_to_keep }} days.{% endblocktranslate %}
99
</p>
1010
<p>
11-
{% blocktranslate with verbose_name_plural=opts.verbose_name_plural %}All {{ verbose_name_plural }} received before {{ cutoff_date }} will be permanently deleted.{% endblocktranslate %}
11+
{% blocktranslate with verbose_name_plural=opts.verbose_name_plural cutoff_date=form.cutoff_date %}All {{ verbose_name_plural }} received before {{ cutoff_date }} will be permanently deleted.{% endblocktranslate %}
1212
</p>
13-
{% if model_count %}
14-
{% include "admin/includes/object_delete_summary.html" %}
13+
{% if form.to_delete_count %}
14+
<h2>{% translate "Summary" %}</h2>
15+
<ul>
16+
<li>{% blocktranslate with name=opts.verbose_name_plural count=form.to_delete_count %}{{ name }}: {{ count }}{% endblocktranslate %}</li>
17+
</ul>
1518
{% endif %}
1619
<form method="post">
1720
{% csrf_token %}
1821
<div>
1922
<input type="hidden" name="post" value="yes">
20-
<input type="hidden" name="days_to_keep" value="{{ days_to_keep }}">
23+
<input type="hidden" name="days_to_keep" value="{{ form.cleaned_data.days_to_keep }}">
2124
<input type="submit" value="{% translate "Yes, I'm sure" %}">
2225
<a href="#" class="button cancel-link">{% translate 'No, take me back' %}</a>
2326
</div>

0 commit comments

Comments
 (0)