Skip to content

Commit

Permalink
Unify CRUD views
Browse files Browse the repository at this point in the history
- Create generic classes, which simplify majority of the operation
- Main benefit is less locales and templates, code is around the same
  • Loading branch information
pehala committed Dec 22, 2024
1 parent c59515a commit edf6e11
Show file tree
Hide file tree
Showing 13 changed files with 203 additions and 160 deletions.
97 changes: 97 additions & 0 deletions backend/generic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""Generic CRUD views"""

from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.utils.translation import gettext_lazy as _
from django.views.generic import DeleteView, UpdateView, CreateView

from backend.mixins import RedirectToNextMixin

# pylint: disable=no-member


class UniversalView(RedirectToNextMixin):
"""Mixing for rest of the classes, simplifies object identifier and verbose name retrieval"""

def get_verbose_name(self):
"""Returns model verbose name"""
return self.model._meta.verbose_name

def get_object_identifier(self, obj):
"""Returns Object identifier"""
if hasattr(obj, "name"):
return obj.name
return obj.id


class UniversalDeleteView(UniversalView, DeleteView):
"""
Universal Delete view for all Models
You need to add 'success_url' and 'model' class parameters
"""

template_name = "base/verbs/delete.html"
success_message = _("%(class)s %(identifier)s was successfully deleted")

def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
obj = ctx["object"]
ctx["success_url"] = self.success_url
ctx["model_verbose_name"] = self.get_verbose_name()
ctx["identifier"] = self.get_object_identifier(obj)
return ctx

def post(self, request, *args, **kwargs):
obj = self.get_object()
response = super().post(request, *args, **kwargs)
messages.success(
self.request,
self.success_message % {"class": self.get_verbose_name(), "identifier": self.get_object_identifier(obj)},
)
return response


class UniversalEditView(
UniversalView,
SuccessMessageMixin,
):
"""UniversalEditView base class"""

template_name = "base/verbs/add.html"
success_message = _("%(class)s %(identifier)s was successfully updated")

def get_success_message(self, cleaned_data):
return self.success_message % {
"class": self.get_verbose_name(),
"identifier": self.get_object_identifier(self.object),
}


class UniversalUpdateView(UniversalEditView, UpdateView):
"""
Universal Update view for all Models
You need to add 'success_url', 'form_class' and 'model' class parameters
"""

success_message = _("%(class)s %(identifier)s was successfully updated")
title_message = _("Update %(class)s (%(id)s)")

def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx["title"] = self.title_message % {"class": self.get_verbose_name(), "id": self.object.id}
return ctx


class UniversalCreateView(UniversalEditView, CreateView):
"""
Universal Update view for all Models
You need to add 'success_url', 'form_class' and 'model' class parameters
"""

success_message = _("%(class)s %(identifier)s was successfully created")
title_message = _("Create %(class)s")

def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx["title"] = self.title_message % {"class": self.get_verbose_name()}
return ctx
59 changes: 26 additions & 33 deletions backend/locale/cs/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-04-07 16:49+0000\n"
"POT-Creation-Date: 2024-12-22 22:03+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
Expand All @@ -19,6 +19,31 @@ msgstr ""
"Plural-Forms: nplurals=4; plural=(n == 1 && n % 1 == 0) ? 0 : (n >= 2 && n "
"<= 4 && n % 1 == 0) ? 1: (n % 1 != 0 ) ? 2 : 3;\n"

#: backend/generic.py:29
#, python-format
msgid "%(class)s %(identifier)s was successfully deleted"
msgstr "%(class)s %(identifier)s byla úspěšně smazána"

#: backend/generic.py:59 backend/generic.py:69
#, python-format
msgid "%(class)s %(identifier)s was successfully updated"
msgstr "%(class)s %(identifier)s byla úspěšně upravena"

#: backend/generic.py:70
#, python-format
msgid "Update %(class)s (%(id)s)"
msgstr "%(class)s (%(id)s) - Editor"

#: backend/generic.py:79
#, python-format
msgid "%(class)s %(identifier)s was successfully created"
msgstr "%(class)s %(identifier)s byla úspěšně vytvořena"

#: backend/generic.py:80
#, python-format
msgid "Create %(class)s"
msgstr "Nová %(class)s"

#: backend/menus.py:10
msgid "Analytics"
msgstr "Statistiky"
Expand Down Expand Up @@ -87,23 +112,6 @@ msgstr "Text"
msgid "Song"
msgstr "Písnička"

#: backend/templates/songs/add.html:4 backend/templates/songs/add.html:5
msgid "Song Editor"
msgstr "Editor písničky"

#: backend/templates/songs/confirm_delete.html:5
#: backend/templates/songs/confirm_delete.html:6
msgid "Please confirm removal"
msgstr "Potvrďte odstranění"

#: backend/templates/songs/confirm_delete.html:9
msgid "Are you sure you wanna delete song"
msgstr "Jste si jisti že chcete smazat písničku"

#: backend/templates/songs/confirm_delete.html:10
msgid "Confirm"
msgstr "Potvrdit"

#: backend/templates/songs/index.html:27
msgid "Hide chords"
msgstr "Skrýt akordy"
Expand Down Expand Up @@ -139,18 +147,3 @@ msgstr "Vyhledávání"
#: backend/templates/songs/index.html:107
msgid "Number, text or author"
msgstr "Číslo, text nebo autor"

#: backend/views.py:101
#, python-format
msgid "Song %(name)s was successfully created"
msgstr "Písnička %(name)s byla úspěšně přidána"

#: backend/views.py:124
#, python-format
msgid "Song %(name)s was successfully updated"
msgstr "Písnička %(name)s byla úspěšně upravena"

#: backend/views.py:140
#, python-format
msgid "Song %s was successfully deleted"
msgstr "Písnička %s byla úspěšně odstraněna"
5 changes: 0 additions & 5 deletions backend/templates/songs/add.html

This file was deleted.

12 changes: 0 additions & 12 deletions backend/templates/songs/confirm_delete.html

This file was deleted.

26 changes: 8 additions & 18 deletions backend/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@
import json
from typing import Dict

from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.core.serializers.json import DjangoJSONEncoder
from django.forms import model_to_dict
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
from django.views.generic import ListView, CreateView, UpdateView, DeleteView, RedirectView
from django.views.generic import ListView, RedirectView

from backend.forms import SongForm
from backend.mixins import RegenerateViewMixin, PassRequestToFormMixin, LocalAdminRequired, RedirectToNextMixin
from backend.mixins import RegenerateViewMixin, PassRequestToFormMixin, LocalAdminRequired
from backend.models import Song
from backend.utils import regenerate_pdf, regenerate_prerender
from backend.generic import UniversalDeleteView, UniversalUpdateView, UniversalCreateView


def transform_song(song: Song, number: int) -> Dict:
Expand Down Expand Up @@ -92,13 +91,11 @@ def get_redirect_url(self, *args, **kwargs):
return self.request.tenant.index_redirect


class SongCreateView(LocalAdminRequired, PassRequestToFormMixin, SuccessMessageMixin, CreateView):
class SongCreateView(LocalAdminRequired, PassRequestToFormMixin, UniversalCreateView):
"""Creates new song"""

form_class = SongForm
model = Song
template_name = "songs/add.html"
success_message = _("Song %(name)s was successfully created")
success_url = reverse_lazy("backend:index")

def get_success_url(self):
Expand All @@ -110,18 +107,14 @@ def get_success_url(self):
class SongUpdateView(
LocalAdminRequired,
PassRequestToFormMixin,
SuccessMessageMixin,
RegenerateViewMixin,
RedirectToNextMixin,
UpdateView,
UniversalUpdateView,
):
"""Updates existing song"""

form_class = SongForm
model = Song
template_name = "songs/add.html"
default_next_page = reverse_lazy("backend:index")
success_message = _("Song %(name)s was successfully updated")
success_url = reverse_lazy("backend:index")

def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
Expand All @@ -131,16 +124,13 @@ def post(self, request, *args, **kwargs):
return response


class SongDeleteView(LocalAdminRequired, RedirectToNextMixin, DeleteView):
class SongDeleteView(LocalAdminRequired, UniversalDeleteView):
"""Removes song"""

model = Song
template_name = "songs/confirm_delete.html"
default_next_page = reverse_lazy("backend:index")
success_message = _("Song %s was successfully deleted")
success_url = reverse_lazy("backend:index")

def post(self, request, *args, **kwargs):
regenerate_pdf(self.get_object())
response = super().post(request, *args, **kwargs)
messages.success(self.request, self.success_message % self.object.name)
return response
53 changes: 11 additions & 42 deletions category/locale/cs/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-04-07 16:49+0000\n"
"POT-Creation-Date: 2024-12-22 21:56+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
Expand Down Expand Up @@ -61,31 +61,7 @@ msgstr "Přesun kategorii do jiného Zpěvníku"

#: category/templates/admin/category/migrate.html:7
msgid "To Tenant"
msgstr "Do Tenanta"

#: category/templates/category/add.html:4
#: category/templates/category/add.html:5
msgid "Category Editor"
msgstr "Editor Kategorie"

#: category/templates/category/confirm_delete.html:5
#: category/templates/category/confirm_delete.html:6
msgid "Please confirm removal"
msgstr "Prosím potrvďte odstranění"

#: category/templates/category/confirm_delete.html:9
msgid "Are you sure, you want to delete Category"
msgstr "Jste si jisti že chcete smazat Kategorii"

#: category/templates/category/confirm_delete.html:11
#: category/templates/category/list.html:23
msgid "No"
msgstr "Ne"

#: category/templates/category/confirm_delete.html:12
#: category/templates/category/list.html:23
msgid "Yes"
msgstr "Ano"
msgstr "Do Zpěvníku"

#: category/templates/category/list.html:14
msgid "Language"
Expand All @@ -95,6 +71,14 @@ msgstr "Jazyk"
msgid "Actions"
msgstr ""

#: category/templates/category/list.html:23
msgid "Yes"
msgstr "Ano"

#: category/templates/category/list.html:23
msgid "No"
msgstr "Ne"

#: category/templates/category/list.html:27
msgid "Edit"
msgstr "Upravit"
Expand Down Expand Up @@ -124,22 +108,7 @@ msgstr "Přidat Kategorii"
msgid "Category with url /%(slug)s does not exist"
msgstr "Kategorie s url /%(slug)s neexistuje"

#: category/views.py:73
#, python-format
msgid "Category %(name)s was successfully created"
msgstr "Kategorie %(name)s byla úspěšně vytvořena"

#: category/views.py:90
#, python-format
msgid "Category %(name)s was successfully updated"
msgstr "Kategorie %(name)s byla úspěšně upravena"

#: category/views.py:111
#: category/views.py:113
#, python-format
msgid "Category %s was successfully staged for PDF generation"
msgstr "PDF pro Kategorii %s bylo přidáno do fronty"

#: category/views.py:122
#, python-format
msgid "Category %(name)s was successfully deleted"
msgstr "Kategorie %(name)s byla úspěšně smazána"
5 changes: 0 additions & 5 deletions category/templates/category/add.html

This file was deleted.

15 changes: 0 additions & 15 deletions category/templates/category/confirm_delete.html

This file was deleted.

Loading

0 comments on commit edf6e11

Please sign in to comment.