-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMakefile
2649 lines (2274 loc) · 78.8 KB
/
Makefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Project Makefile
#
# A generic makefile for projects.
#
# https://github.com/project-makefile/project-makefile
# --------------------------------------------------------------------------------
# Variables (override)
# --------------------------------------------------------------------------------
.DEFAULT_GOAL := git-commit-push
UNAME := $(shell uname)
RANDIR := $(shell openssl rand -base64 12 | sed 's/\///g')
TMPDIR := $(shell mktemp -d)
PROJECT_EMAIL := [email protected]
PROJECT_MAKEFILE := project.mk
PROJECT_NAME = project-makefile
PROJECT_DIRS = backend contactpage home privacy siteuser
WAGTAIL_CLEAN_DIRS = home search backend sitepage siteuser privacy frontend contactpage model_form_demo
WAGTAIL_CLEAN_FILES = README.rst .dockerignore Dockerfile manage.py requirements.txt requirements-test.txt docker-compose.yml
REVIEW_EDITOR = subl
GIT_BRANCHES = $(shell git branch -a | grep remote | grep -v HEAD | grep -v main |\
grep -v master)
GIT_MESSAGE = "Update $(PROJECT_NAME)"
GIT_COMMIT = git commit -a -m $(GIT_MESSAGE)
GIT_PUSH = git push
GIT_PUSH_FORCE = git push --force-with-lease
GET_DATABASE_URL = eb ssh -c "source /opt/elasticbeanstalk/deployment/custom_env_var;\
env | grep DATABASE_URL"
DATABASE_AWK = awk -F\= '{print $$2}'
DATABASE_HOST = $(shell $(GET_DATABASE_URL) | $(DATABASE_AWK) |\
python -c 'import dj_database_url; url = input(); url = dj_database_url.parse(url); print(url["HOST"])')
DATABASE_NAME = $(shell $(GET_DATABASE_URL) | $(DATABASE_AWK) |\
python -c 'import dj_database_url; url = input(); url = dj_database_url.parse(url); print(url["NAME"])')
DATABASE_PASS = $(shell $(GET_DATABASE_URL) | $(DATABASE_AWK) |\
python -c 'import dj_database_url; url = input(); url = dj_database_url.parse(url); print(url["PASSWORD"])')
DATABASE_USER = $(shell $(GET_DATABASE_URL) | $(DATABASE_AWK) |\
python -c 'import dj_database_url; url = input(); url = dj_database_url.parse(url); print(url["USER"])')
ENV_NAME ?= $(PROJECT_NAME)-$(GIT_BRANCH)-$(GIT_REV)
INSTANCE_MAX ?= 1
INSTANCE_MIN ?= 1
INSTANCE_TYPE ?= t4g.small
INSTANCE_PROFILE ?= aws-elasticbeanstalk-ec2-role
PLATFORM ?= "Python 3.11 running on 64bit Amazon Linux 2023"
LB_TYPE ?= application
ifneq ($(wildcard $(PROJECT_MAKEFILE)),)
include $(PROJECT_MAKEFILE)
endif
# --------------------------------------------------------------------------------
# Variables (no override)
# --------------------------------------------------------------------------------
GIT_REV := $(shell git rev-parse --short HEAD)
GIT_BRANCH := $(shell git branch --show-current)
ADD_DIR := mkdir -pv
ADD_FILE := touch
COPY_DIR := cp -rv
COPY_FILE := cp -v
DEL_DIR := rm -rv
DEL_FILE := rm -v
GIT_ADD := -git add
ENSURE_PIP := python -m ensurepip
EB_DIR = .elasticbeanstalk
# --------------------------------------------------------------------------------
# Multi-line variables
# --------------------------------------------------------------------------------
define ALLAUTH_LAYOUT_BASE
{% extends 'base.html' %}
endef
define AUTHENTICATION_BACKENDS
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
endef
define BABELRC
{
"presets": [
[
"@babel/preset-react",
],
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": "3.0.0"
}
]
],
"plugins": [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-transform-class-properties"
]
}
endef
define BACKEND_APPS
from django.contrib.admin.apps import AdminConfig
class CustomAdminConfig(AdminConfig):
default_site = "backend.admin.CustomAdminSite"
endef
define BACKEND_URLS
from django.conf import settings
from django.urls import include, path
from django.contrib import admin
from wagtail.admin import urls as wagtailadmin_urls
from wagtail import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
from rest_framework import routers, serializers, viewsets
from dj_rest_auth.registration.views import RegisterView
from siteuser.models import User
urlpatterns = []
if settings.DEBUG:
urlpatterns += [
path("django/doc/", include("django.contrib.admindocs.urls")),
]
urlpatterns += [
path('accounts/', include('allauth.urls')),
path('django/', admin.site.urls),
path('wagtail/', include(wagtailadmin_urls)),
path('user/', include('siteuser.urls')),
path('search/', include('search.urls')),
path('model-form-demo/', include('model_form_demo.urls')),
path('explorer/', include('explorer.urls')),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
import debug_toolbar
urlpatterns += [
path("__debug__/", include(debug_toolbar.urls)),
]
# https://www.django-rest-framework.org/#example
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'is_staff']
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns += [
path("api/", include(router.urls)),
path("api/", include("rest_framework.urls", namespace="rest_framework")),
path("api/", include("dj_rest_auth.urls")),
# path("api/register/", RegisterView.as_view(), name="register"),
]
urlpatterns += [
path("hijack/", include("hijack.urls")),
]
urlpatterns += [
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
path("", include(wagtail_urls)),
# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
# path("pages/", include(wagtail_urls)),
]
endef
define BASE_TEMPLATE
{% load static wagtailcore_tags wagtailuserbar webpack_loader %}
<!DOCTYPE html>
<html lang="en" class="h-100" data-bs-theme="{{ request.user.user_theme_preference|default:'light' }}">
<head>
<meta charset="utf-8" />
<title>
{% block title %}
{% if page.seo_title %}{{ page.seo_title }}{% else %}{{ page.title }}{% endif %}
{% endblock %}
{% block title_suffix %}
{% wagtail_site as current_site %}
{% if current_site and current_site.site_name %}- {{ current_site.site_name }}{% endif %}
{% endblock %}
</title>
{% if page.search_description %}
<meta name="description" content="{{ page.search_description }}" />
{% endif %}
<meta name="viewport" content="width=device-width, initial-scale=1" />
{# Force all links in the live preview panel to be opened in a new tab #}
{% if request.in_preview_panel %}
<base target="_blank">
{% endif %}
{% stylesheet_pack 'app' %}
{% block extra_css %}
{# Override this in templates to add extra stylesheets #}
{% endblock %}
<style>
.success {
background-color: #d4edda;
border-color: #c3e6cb;
color: #155724;
}
.info {
background-color: #d1ecf1;
border-color: #bee5eb;
color: #0c5460;
}
.warning {
background-color: #fff3cd;
border-color: #ffeeba;
color: #856404;
}
.danger {
background-color: #f8d7da;
border-color: #f5c6cb;
color: #721c24;
}
</style>
{% include 'favicon.html' %}
{% csrf_token %}
</head>
<body class="{% block body_class %}{% endblock %} d-flex flex-column h-100">
<main class="flex-shrink-0">
{% wagtailuserbar %}
<div id="app"></div>
{% include 'header.html' %}
{% if messages %}
<div class="messages container">
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible fade show"
role="alert">
{{ message }}
<button type="button"
class="btn-close"
data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
{% endfor %}
</div>
{% endif %}
<div class="container">
{% block content %}{% endblock %}
</div>
</main>
{% include 'footer.html' %}
{% include 'offcanvas.html' %}
{% javascript_pack 'app' %}
{% block extra_js %}
{# Override this in templates to add extra javascript #}
{% endblock %}
</body>
</html>
endef
define BLOCK_CAROUSEL
<div id="carouselExampleCaptions" class="carousel slide">
<div class="carousel-indicators">
{% for image in block.value.images %}
<button type="button"
data-bs-target="#carouselExampleCaptions"
data-bs-slide-to="{{ forloop.counter0 }}"
{% if forloop.first %}class="active" aria-current="true"{% endif %}
aria-label="Slide {{ forloop.counter }}"></button>
{% endfor %}
</div>
<div class="carousel-inner">
{% for image in block.value.images %}
<div class="carousel-item {% if forloop.first %}active{% endif %}">
<img src="{{ image.file.url }}" class="d-block w-100" alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>{{ image.title }}</h5>
</div>
</div>
{% endfor %}
</div>
<button class="carousel-control-prev"
type="button"
data-bs-target="#carouselExampleCaptions"
data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next"
type="button"
data-bs-target="#carouselExampleCaptions"
data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
endef
define BLOCK_MARKETING
{% load wagtailcore_tags %}
<div class="{{ self.block_class }}">
{% if block.value.images.0 %}
{% include 'blocks/carousel_block.html' %}
{% else %}
{{ self.title }}
{{ self.content }}
{% endif %}
</div>
endef
define CONTACT_PAGE_TEST
from wagtail.models import Page, Site
from wagtail.rich_text import RichText
from wagtail.test.utils import WagtailPageTestCase
from home.models import HomePage
from contactpage.models import ContactPage
class ContactPageTest(WagtailPageTestCase):
@classmethod
def setUpTestData(cls):
root = Page.get_first_root_node()
Site.objects.create(
hostname="testserver",
root_page=root,
is_default_site=True,
site_name="testserver",
)
home = HomePage(title="Home")
root.add_child(instance=home)
cls.page = ContactPage(
title="Contact Us",
slug="contact-us",
)
home.add_child(instance=cls.page)
def test_get(self):
response = self.client.get(self.page.url)
self.assertEqual(response.status_code, 200)
endef
define COMPONENT_CLOCK
// Via ChatGPT
import React, { useState, useEffect, useCallback, useRef } from 'react';
import PropTypes from 'prop-types';
const Clock = ({ color = '#fff' }) => {
const [date, setDate] = useState(new Date());
const [blink, setBlink] = useState(true);
const timerID = useRef();
const tick = useCallback(() => {
setDate(new Date());
setBlink(prevBlink => !prevBlink);
}, []);
useEffect(() => {
timerID.current = setInterval(() => tick(), 1000);
// Return a cleanup function to be run on component unmount
return () => clearInterval(timerID.current);
}, [tick]);
const formattedDate = date.toLocaleDateString(undefined, {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
});
const formattedTime = date.toLocaleTimeString(undefined, {
hour: 'numeric',
minute: 'numeric',
});
return (
<>
<div style={{ animation: blink ? 'blink 1s infinite' : 'none' }}><span className='me-2'>{formattedDate}</span> {formattedTime}</div>
</>
);
};
Clock.propTypes = {
color: PropTypes.string,
};
export default Clock;
endef
define COMPONENT_ERROR
import { Component } from 'react';
import PropTypes from 'prop-types';
class ErrorBoundary extends Component {
constructor (props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError () {
return { hasError: true };
}
componentDidCatch (error, info) {
const { onError } = this.props;
console.error(error);
onError && onError(error, info);
}
render () {
const { children = null } = this.props;
const { hasError } = this.state;
return hasError ? null : children;
}
}
ErrorBoundary.propTypes = {
onError: PropTypes.func,
children: PropTypes.node,
};
export default ErrorBoundary;
endef
define COMPONENT_USER_MENU
// UserMenu.js
import React from 'react';
import PropTypes from 'prop-types';
function handleLogout() {
window.location.href = '/accounts/logout';
}
const UserMenu = ({ isAuthenticated, isSuperuser, textColor }) => {
return (
<div>
{isAuthenticated ? (
<li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i className="fa-solid fa-circle-user"></i>
</a>
<ul className="dropdown-menu">
<li><a className="dropdown-item" href="/user/profile/">Profile</a></li>
<li><a className="dropdown-item" href="/model-form-demo/">Model Form Demo</a></li>
{isSuperuser ? (
<>
<li><hr className="dropdown-divider"></hr></li>
<li><a className="dropdown-item" href="/django" target="_blank">Django admin</a></li>
<li><a className="dropdown-item" href="/wagtail" target="_blank">Wagtail admin</a></li>
<li><a className="dropdown-item" href="/api" target="_blank">Django REST framework</a></li>
<li><a className="dropdown-item" href="/explorer" target="_blank">SQL Explorer</a></li>
</>
) : null}
<li><hr className="dropdown-divider"></hr></li>
<li><a className="dropdown-item" href="/accounts/logout">Logout</a></li>
</ul>
</li>
) : (
<li className="nav-item">
<a className={`nav-link text-$${textColor}`} href="/accounts/login"><i className="fa-solid fa-circle-user"></i></a>
</li>
)}
</div>
);
};
UserMenu.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
isSuperuser: PropTypes.bool.isRequired,
textColor: PropTypes.string,
};
export default UserMenu;
endef
define CONTACT_PAGE_TEMPLATE
{% extends 'base.html' %}
{% load crispy_forms_tags static wagtailcore_tags %}
{% block content %}
<h1>{{ page.title }}</h1>
{{ page.intro|richtext }}
<form action="{% pageurl page %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{% endblock %}
endef
define CONTACT_PAGE_TEST
from django.test import TestCase
from wagtail.test.utils import WagtailPageTestCase
from wagtail.models import Page
from contactpage.models import ContactPage, FormField
class ContactPageTest(TestCase, WagtailPageTestCase):
def test_contact_page_creation(self):
# Create a ContactPage instance
contact_page = ContactPage(
title='Contact',
intro='Welcome to our contact page!',
thank_you_text='Thank you for reaching out.'
)
# Save the ContactPage instance
self.assertEqual(contact_page.save_revision().publish().get_latest_revision_as_page(), contact_page)
def test_form_field_creation(self):
# Create a ContactPage instance
contact_page = ContactPage(
title='Contact',
intro='Welcome to our contact page!',
thank_you_text='Thank you for reaching out.'
)
# Save the ContactPage instance
contact_page_revision = contact_page.save_revision()
contact_page_revision.publish()
# Create a FormField associated with the ContactPage
form_field = FormField(
page=contact_page,
label='Your Name',
field_type='singleline',
required=True
)
form_field.save()
# Retrieve the ContactPage from the database
contact_page_from_db = Page.objects.get(id=contact_page.id).specific
# Check if the FormField is associated with the ContactPage
self.assertEqual(contact_page_from_db.form_fields.first(), form_field)
def test_contact_page_form_submission(self):
# Create a ContactPage instance
contact_page = ContactPage(
title='Contact',
intro='Welcome to our contact page!',
thank_you_text='Thank you for reaching out.'
)
# Save the ContactPage instance
contact_page_revision = contact_page.save_revision()
contact_page_revision.publish()
# Simulate a form submission
form_data = {
'your_name': 'John Doe',
# Add other form fields as needed
}
response = self.client.post(contact_page.url, form_data)
# Check if the form submission is successful (assuming a 302 redirect)
self.assertEqual(response.status_code, 302)
# You may add more assertions based on your specific requirements
endef
define CONTACT_PAGE_MODEL
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
class FormField(AbstractFormField):
page = ParentalKey('ContactPage', on_delete=models.CASCADE, related_name='form_fields')
class ContactPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
class Meta:
verbose_name = "Contact Page"
endef
define CONTACT_PAGE_LANDING
{% extends 'base.html' %}
{% block content %}<div class="container"><h1>Thank you!</h1></div>{% endblock %}
endef
define CUSTOM_ADMIN
# admin.py
from django.contrib.admin import AdminSite
class CustomAdminSite(AdminSite):
site_header = 'Project Makefile'
site_title = 'Project Makefile'
index_title = 'Project Makefile'
custom_admin_site = CustomAdminSite(name='custom_admin')
endef
define DOCKERFILE
FROM amazonlinux:2023
RUN dnf install -y shadow-utils python3.11 python3.11-pip make nodejs20-npm nodejs postgresql15 postgresql15-server
USER postgres
RUN initdb -D /var/lib/pgsql/data
USER root
RUN useradd wagtail
EXPOSE 8000
ENV PYTHONUNBUFFERED=1 PORT=8000
COPY requirements.txt /
RUN python3.11 -m pip install -r /requirements.txt
WORKDIR /app
RUN chown wagtail:wagtail /app
COPY --chown=wagtail:wagtail . .
USER wagtail
RUN cd frontend; npm-20 install; npm-20 run build
RUN python3.11 manage.py collectstatic --noinput --clear
CMD set -xe; pg_ctl -D /var/lib/pgsql/data -l /tmp/logfile start; python3.11 manage.py migrate --noinput; gunicorn backend.wsgi:application
endef
define DOCKERCOMPOSE
version: '3'
services:
db:
image: postgres:latest
volumes:
- postgres_data:/var/lib/postgresql/data
environment:
POSTGRES_DB: project
POSTGRES_USER: admin
POSTGRES_PASSWORD: admin
web:
build: .
command: sh -c "python manage.py migrate && gunicorn project.wsgi:application -b 0.0.0.0:8000"
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
environment:
DATABASE_URL: postgres://admin:admin@db:5432/project
volumes:
postgres_data:
endef
define INTERNAL_IPS
INTERNAL_IPS = ["127.0.0.1",]
endef
define ESLINTRC
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"overrides": [
{
"env": {
"node": true
},
"files": [
".eslintrc.{js,cjs}"
],
"parserOptions": {
"sourceType": "script"
}
}
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"no-unused-vars": "off"
},
settings: {
react: {
version: 'detect',
},
},
}
endef
define FAVICON_TEMPLATE
{% load static %}
<link href="{% static 'wagtailadmin/images/favicon.ico' %}" rel="icon">
endef
define HOME_PAGE_MODEL
from django.db import models
from wagtail.models import Page
from wagtail.fields import RichTextField, StreamField
from wagtail import blocks
from wagtail.admin.panels import FieldPanel
from wagtail.images.blocks import ImageChooserBlock
from wagtail_color_panel.fields import ColorField
from wagtail_color_panel.edit_handlers import NativeColorPanel
class MarketingBlock(blocks.StructBlock):
title = blocks.CharBlock(required=False, help_text='Enter the block title')
content = blocks.RichTextBlock(required=False, help_text='Enter the block content')
images = blocks.ListBlock(ImageChooserBlock(required=False), help_text="Select one or two images for column display. Select three or more images for carousel display.")
image = ImageChooserBlock(required=False, help_text="Select one image for background display.")
block_class = blocks.CharBlock(
required=False,
help_text='Enter a CSS class for styling the marketing block',
classname='full title',
default='vh-100 bg-secondary',
)
image_class = blocks.CharBlock(
required=False,
help_text='Enter a CSS class for styling the column display image(s)',
classname='full title',
default='img-thumbnail p-5',
)
layout_class = blocks.CharBlock(
required=False,
help_text='Enter a CSS class for styling the layout.',
classname='full title',
default='d-flex flex-row',
)
class Meta:
icon = 'placeholder'
template = 'blocks/marketing_block.html'
class HomePage(Page):
template = 'home/home_page.html' # Create a template for rendering the home page
marketing_blocks = StreamField([
('marketing_block', MarketingBlock()),
], blank=True, null=True, use_json_field=True)
content_panels = Page.content_panels + [
FieldPanel('marketing_blocks'),
]
class Meta:
verbose_name = 'Home Page'
endef
define HOME_PAGE_TEMPLATE
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% block content %}
<main class="{% block main_class %}{% endblock %}">
{% for block in page.marketing_blocks %}
{% include_block block %}
{% endfor %}
</main>
{% endblock %}
endef
define HTML_INDEX
<h1>Hello world</h1>
endef
define HTML_ERROR
<h1>500</h1>
endef
define JENKINS_FILE
pipeline {
agent any
stages {
stage('') {
steps {
echo ''
}
}
}
}
endef
define SITEPAGE_MODEL
from wagtail.models import Page
class SitePage(Page):
template = "sitepage/site_page.html"
class Meta:
verbose_name = "Site Page"
endef
define SEARCH_TEMPLATE
{% extends "base.html" %}
{% load static wagtailcore_tags %}
{% block body_class %}template-searchresults{% endblock %}
{% block title %}Search{% endblock %}
{% block content %}
<h1>Search</h1>
<form action="{% url 'search' %}" method="get">
<input type="text"
name="query"
{% if search_query %}value="{{ search_query }}"{% endif %}>
<input type="submit" value="Search" class="button">
</form>
{% if search_results %}
<ul>
{% for result in search_results %}
<li>
<h4>
<a href="{% pageurl result %}">{{ result }}</a>
</h4>
{% if result.search_description %}{{ result.search_description }}{% endif %}
</li>
{% endfor %}
</ul>
{% if search_results.has_previous %}
<a href="{% url 'search' %}?query={{ search_query|urlencode }}&page={{ search_results.previous_page_number }}">Previous</a>
{% endif %}
{% if search_results.has_next %}
<a href="{% url 'search' %}?query={{ search_query|urlencode }}&page={{ search_results.next_page_number }}">Next</a>
{% endif %}
{% elif search_query %}
No results found
{% else %}
No results found. Try a <a href="?query=test">test query</a>?
{% endif %}
{% endblock %}
endef
define SEARCH_URLS
from django.urls import path
from .views import search
urlpatterns = [
path("", search, name="search")
]
endef
define SITEUSER_URLS
from django.urls import path
from .views import UserProfileView, UpdateThemePreferenceView, UserEditView
urlpatterns = [
path('profile/', UserProfileView.as_view(), name='user-profile'),
path('update_theme_preference/', UpdateThemePreferenceView.as_view(), name='update_theme_preference'),
path('<int:pk>/edit/', UserEditView.as_view(), name='user-edit'),
]
endef
define REST_FRAMEWORK
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
endef
define FRONTEND_APP_CONFIG
import '../utils/themeToggler.js';
import '../utils/tinymce.js';
endef
define FRONTEND_PORTAL
// Via pwellever
import React from 'react';
import { createPortal } from 'react-dom';
const parseProps = data => Object.entries(data).reduce((result, [key, value]) => {
if (value.toLowerCase() === 'true') {
value = true;
} else if (value.toLowerCase() === 'false') {
value = false;
} else if (value.toLowerCase() === 'null') {
value = null;
} else if (!isNaN(parseFloat(value)) && isFinite(value)) {
// Parse numeric value
value = parseFloat(value);
} else if (
(value[0] === '[' && value.slice(-1) === ']') || (value[0] === '{' && value.slice(-1) === '}')
) {
// Parse JSON strings
value = JSON.parse(value);
}
result[key] = value;
return result;
}, {});
// This method of using portals instead of calling ReactDOM.render on individual components
// ensures that all components are mounted under a single React tree, and are therefore able
// to share context.
export default function getPageComponents (components) {
const getPortalComponent = domEl => {
// The element's "data-component" attribute is used to determine which component to render.
// All other "data-*" attributes are passed as props.
const { component: componentName, ...rest } = domEl.dataset;
const Component = components[componentName];
if (!Component) {
console.error(`Component "$${componentName}" not found.`);
return null;
}
const props = parseProps(rest);
domEl.innerHTML = '';
// eslint-disable-next-line no-unused-vars
const { ErrorBoundary } = components;
return createPortal(
<ErrorBoundary>
<Component {...props} />
</ErrorBoundary>,
domEl,
);
};
return Array.from(document.querySelectorAll('[data-component]')).map(getPortalComponent);
}
endef
define FRONTEND_COMPONENTS
export { default as ErrorBoundary } from './ErrorBoundary';
export { default as UserMenu } from './UserMenu';
endef
define FRONTEND_CONTEXT_INDEX
export { UserContextProvider as default } from './UserContextProvider';
endef
define FRONTEND_CONTEXT_USER_PROVIDER
// UserContextProvider.js
import React, { createContext, useContext, useState } from 'react';
import PropTypes from 'prop-types';
const UserContext = createContext();
export const UserContextProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const login = () => {
try {
// Add logic to handle login, set isAuthenticated to true
setIsAuthenticated(true);
} catch (error) {