Skip to content

Commit 13bacac

Browse files
authored
Merge pull request #126 from mpasternak/master
Django 4.x
2 parents 8e8b76f + fa72b27 commit 13bacac

File tree

13 files changed

+190
-104
lines changed

13 files changed

+190
-104
lines changed

README.rst

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ django-dbtemplates
66
:target: https://jazzband.co/
77

88
.. image:: https://github.com/jazzband/django-dbtemplates/workflows/Test/badge.svg
9-
:target: https://github.com/jazzband/django-dbtemplates/actions
10-
:alt: GitHub Actions
9+
:target: https://github.com/jazzband/django-dbtemplates/actions
1110

1211
.. image:: https://codecov.io/github/jazzband/django-dbtemplates/coverage.svg?branch=master
1312
:alt: Codecov

dbtemplates/admin.py

+20-10
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,27 @@
22
from django import forms
33
from django.contrib import admin
44
from django.core.exceptions import ImproperlyConfigured
5-
from django.utils.translation import ungettext, ugettext_lazy as _
5+
try:
6+
# Django 4.0
7+
from django.utils.translation import gettext_lazy as _
8+
from django.utils.translation import ngettext
9+
except ImportError:
10+
# Before Django 4.0
11+
from django.utils.translation import ugettext_lazy as _
12+
from django.utils.translation import ungettext as ngettext
13+
614
from django.utils.safestring import mark_safe
715

816
from dbtemplates.conf import settings
9-
from dbtemplates.models import (Template, remove_cached_template,
10-
add_template_to_cache)
17+
from dbtemplates.models import Template, add_template_to_cache, remove_cached_template
1118
from dbtemplates.utils.template import check_template_syntax
1219

1320
# Check if either django-reversion-compare or django-reversion is installed and
1421
# use reversion_compare's CompareVersionAdmin or reversion's VersionAdmin as
1522
# the base admin class if yes
1623
if settings.DBTEMPLATES_USE_REVERSION_COMPARE:
17-
from reversion_compare.admin import CompareVersionAdmin as TemplateModelAdmin
24+
from reversion_compare.admin import CompareVersionAdmin \
25+
as TemplateModelAdmin
1826
elif settings.DBTEMPLATES_USE_REVERSION:
1927
from reversion.admin import VersionAdmin as TemplateModelAdmin
2028
else:
@@ -30,7 +38,8 @@ class CodeMirrorTextArea(forms.Textarea):
3038
class Media:
3139
css = dict(screen=[posixpath.join(
3240
settings.DBTEMPLATES_MEDIA_PREFIX, 'css/editor.css')])
33-
js = [posixpath.join(settings.DBTEMPLATES_MEDIA_PREFIX, 'js/codemirror.js')]
41+
js = [posixpath.join(settings.DBTEMPLATES_MEDIA_PREFIX,
42+
'js/codemirror.js')]
3443

3544
def render(self, name, value, attrs=None, renderer=None):
3645
result = []
@@ -119,7 +128,7 @@ def invalidate_cache(self, request, queryset):
119128
for template in queryset:
120129
remove_cached_template(template)
121130
count = queryset.count()
122-
message = ungettext(
131+
message = ngettext(
123132
"Cache of one template successfully invalidated.",
124133
"Cache of %(count)d templates successfully invalidated.",
125134
count)
@@ -131,7 +140,7 @@ def repopulate_cache(self, request, queryset):
131140
for template in queryset:
132141
add_template_to_cache(template)
133142
count = queryset.count()
134-
message = ungettext(
143+
message = ngettext(
135144
"Cache successfully repopulated with one template.",
136145
"Cache successfully repopulated with %(count)d templates.",
137146
count)
@@ -147,15 +156,16 @@ def check_syntax(self, request, queryset):
147156
errors.append(f'{template.name}: {error}')
148157
if errors:
149158
count = len(errors)
150-
message = ungettext(
159+
message = ngettext(
151160
"Template syntax check FAILED for %(names)s.",
152-
"Template syntax check FAILED for %(count)d templates: %(names)s.",
161+
"Template syntax check FAILED for "
162+
"%(count)d templates: %(names)s.",
153163
count)
154164
self.message_user(request, message %
155165
{'count': count, 'names': ', '.join(errors)})
156166
else:
157167
count = queryset.count()
158-
message = ungettext(
168+
message = ngettext(
159169
"Template syntax OK.",
160170
"Template syntax OK for %(count)d templates.", count)
161171
self.message_user(request, message % {'count': count})

dbtemplates/apps.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
from django.apps import AppConfig
2-
from django.utils.translation import ugettext_lazy as _
2+
try:
3+
from django.utils.translation import ugettext_lazy as _
4+
except ImportError:
5+
from django.utils.translation import gettext_lazy as _
36

47

58
class DBTemplatesConfig(AppConfig):

dbtemplates/conf.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ def configure_use_reversion(self, value):
4747

4848
def configure_use_reversion_compare(self, value):
4949
if value and 'reversion_compare' not in settings.INSTALLED_APPS:
50-
raise ImproperlyConfigured("Please add 'reversion_compare' to your "
51-
"INSTALLED_APPS setting to make "
50+
raise ImproperlyConfigured("Please add 'reversion_compare' to your"
51+
" INSTALLED_APPS setting to make "
5252
"use of it in dbtemplates.")
5353
return value
5454

dbtemplates/loader.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ def get_contents(self, origin):
3030
content, _ = self._load_template_source(origin.template_name)
3131
return content
3232

33-
def _load_and_store_template(self, template_name, cache_key, site, **params):
33+
def _load_and_store_template(self, template_name, cache_key, site,
34+
**params):
3435
template = Template.objects.get(name__exact=template_name, **params)
3536
db = router.db_for_read(Template, instance=template)
3637
display_name = f'dbtemplates:{db}:{template_name}:{site.domain}'
@@ -73,11 +74,11 @@ def _load_template_source(self, template_name, template_dirs=None):
7374

7475
try:
7576
return self._load_and_store_template(template_name, cache_key,
76-
site, sites__in=[site.id])
77+
site, sites__in=[site.id])
7778
except (Template.MultipleObjectsReturned, Template.DoesNotExist):
7879
try:
7980
return self._load_and_store_template(template_name, cache_key,
80-
site, sites__isnull=True)
81+
site, sites__isnull=True)
8182
except (Template.MultipleObjectsReturned, Template.DoesNotExist):
8283
pass
8384

dbtemplates/management/commands/sync_templates.py

+80-46
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,86 @@
11
import os
2-
from django.contrib.sites.models import Site
3-
from django.core.management.base import CommandError, BaseCommand
4-
from django.template.utils import get_app_template_dirs
5-
from django.template.loader import _engine_list
62

73
from dbtemplates.models import Template
4+
from django.contrib.sites.models import Site
5+
from django.core.management.base import BaseCommand, CommandError
6+
from django.template.loader import _engine_list
7+
from django.template.utils import get_app_template_dirs
88

9-
ALWAYS_ASK, FILES_TO_DATABASE, DATABASE_TO_FILES = ('0', '1', '2')
9+
ALWAYS_ASK, FILES_TO_DATABASE, DATABASE_TO_FILES = ("0", "1", "2")
1010

1111
DIRS = []
1212
for engine in _engine_list():
1313
DIRS.extend(engine.dirs)
1414
DIRS = tuple(DIRS)
15-
app_template_dirs = get_app_template_dirs('templates')
15+
app_template_dirs = get_app_template_dirs("templates")
1616

1717

1818
class Command(BaseCommand):
1919
help = "Syncs file system templates with the database bidirectionally."
2020

2121
def add_arguments(self, parser):
2222
parser.add_argument(
23-
"-e", "--ext",
24-
dest="ext", action="store", default="html",
23+
"-e",
24+
"--ext",
25+
dest="ext",
26+
action="store",
27+
default="html",
2528
help="extension of the files you want to "
26-
"sync with the database [default: %(default)s]")
29+
"sync with the database [default: %(default)s]",
30+
)
2731
parser.add_argument(
28-
"-f", "--force",
29-
action="store_true", dest="force", default=False,
30-
help="overwrite existing database templates")
32+
"-f",
33+
"--force",
34+
action="store_true",
35+
dest="force",
36+
default=False,
37+
help="overwrite existing database templates",
38+
)
3139
parser.add_argument(
32-
"-o", "--overwrite",
33-
action="store", dest="overwrite", default='0',
40+
"-o",
41+
"--overwrite",
42+
action="store",
43+
dest="overwrite",
44+
default="0",
3445
help="'0' - ask always, '1' - overwrite database "
35-
"templates from template files, '2' - overwrite "
36-
"template files from database templates")
46+
"templates from template files, '2' - overwrite "
47+
"template files from database templates",
48+
)
3749
parser.add_argument(
38-
"-a", "--app-first",
39-
action="store_true", dest="app_first", default=False,
50+
"-a",
51+
"--app-first",
52+
action="store_true",
53+
dest="app_first",
54+
default=False,
4055
help="look for templates in applications "
41-
"directories before project templates")
56+
"directories before project templates",
57+
)
4258
parser.add_argument(
43-
"-d", "--delete",
44-
action="store_true", dest="delete", default=False,
45-
help="Delete templates after syncing")
59+
"-d",
60+
"--delete",
61+
action="store_true",
62+
dest="delete",
63+
default=False,
64+
help="Delete templates after syncing",
65+
)
4666

4767
def handle(self, **options):
48-
extension = options.get('ext')
49-
force = options.get('force')
50-
overwrite = options.get('overwrite')
51-
app_first = options.get('app_first')
52-
delete = options.get('delete')
68+
extension = options.get("ext")
69+
force = options.get("force")
70+
overwrite = options.get("overwrite")
71+
app_first = options.get("app_first")
72+
delete = options.get("delete")
5373

5474
if not extension.startswith("."):
5575
extension = f".{extension}"
5676

5777
try:
5878
site = Site.objects.get_current()
5979
except Exception:
60-
raise CommandError("Please make sure to have the sites contrib "
61-
"app installed and setup with a site object")
80+
raise CommandError(
81+
"Please make sure to have the sites contrib "
82+
"app installed and setup with a site object"
83+
)
6284

6385
if app_first:
6486
tpl_dirs = app_template_dirs + DIRS
@@ -68,11 +90,14 @@ def handle(self, **options):
6890

6991
for templatedir in templatedirs:
7092
for dirpath, subdirs, filenames in os.walk(templatedir):
71-
for f in [f for f in filenames
72-
if f.endswith(extension) and not f.startswith(".")]:
93+
for f in [
94+
f
95+
for f in filenames
96+
if f.endswith(extension) and not f.startswith(".")
97+
]:
7398
path = os.path.join(dirpath, f)
7499
name = path.split(str(templatedir))[1]
75-
if name.startswith('/'):
100+
if name.startswith("/"):
76101
name = name[1:]
77102
try:
78103
t = Template.on_site.get(name__exact=name)
@@ -81,27 +106,35 @@ def handle(self, **options):
81106
confirm = input(
82107
"\nA '%s' template doesn't exist in the "
83108
"database.\nCreate it with '%s'?"
84-
" (y/[n]): """ % (name, path))
85-
if force or confirm.lower().startswith('y'):
86-
with open(path, encoding='utf-8') as f:
109+
" (y/[n]): "
110+
"" % (name, path)
111+
)
112+
if force or confirm.lower().startswith("y"):
113+
with open(path, encoding="utf-8") as f:
87114
t = Template(name=name, content=f.read())
88115
t.save()
89116
t.sites.add(site)
90117
else:
91-
while 1:
118+
while True:
92119
if overwrite == ALWAYS_ASK:
93-
confirm = input(
120+
_i = (
94121
"\n%(template)s exists in the database.\n"
95-
"(1) Overwrite %(template)s with '%(path)s'\n"
96-
"(2) Overwrite '%(path)s' with %(template)s\n"
97-
"Type 1 or 2 or press <Enter> to skip: " %
98-
{'template': t.__repr__(), 'path': path})
122+
"(1) Overwrite %(template)s with '%(path)s'\n" # noqa
123+
"(2) Overwrite '%(path)s' with %(template)s\n" # noqa
124+
"Type 1 or 2 or press <Enter> to skip: "
125+
% {"template": t.__repr__(), "path": path}
126+
)
127+
128+
confirm = input(_i)
99129
else:
100130
confirm = overwrite
101-
if confirm in ('', FILES_TO_DATABASE,
102-
DATABASE_TO_FILES):
131+
if confirm in (
132+
"",
133+
FILES_TO_DATABASE,
134+
DATABASE_TO_FILES,
135+
):
103136
if confirm == FILES_TO_DATABASE:
104-
with open(path, encoding='utf-8') as f:
137+
with open(path, encoding="utf-8") as f:
105138
t.content = f.read()
106139
t.save()
107140
t.sites.add(site)
@@ -110,9 +143,10 @@ def handle(self, **options):
110143
os.remove(path)
111144
except OSError:
112145
raise CommandError(
113-
f"Couldn't delete {path}")
146+
f"Couldn't delete {path}"
147+
)
114148
elif confirm == DATABASE_TO_FILES:
115-
with open(path, 'w', encoding='utf-8') as f:
149+
with open(path, "w", encoding="utf-8") as f: # noqa
116150
f.write(t.content)
117151
if delete:
118152
t.delete()

0 commit comments

Comments
 (0)