-
Notifications
You must be signed in to change notification settings - Fork 2
/
Makefile
4499 lines (3800 loc) · 134 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 Makefile to automate setup of Django projects and related tasks
#
# https://github.com/aclark4life/project-makefile
#
# ================================================================================
# Set the default goal to be `git commit -a -m $(GIT_COMMIT_MESSAGE)` and `git push`
# ================================================================================
.DEFAULT_GOAL := git-commit-push
# ================================================================================
# Single line variables to be used by phony target rules
# ================================================================================
ADD_DIR := mkdir -pv
ADD_FILE := touch
AWS_OPTS := --no-cli-pager --output table
COPY_DIR := cp -rv
COPY_FILE := cp -v
DEL_DIR := rm -rv
DEL_FILE := rm -v
DJANGO_ADMIN_CUSTOM_APPS_FILE := backend/apps.py
DJANGO_ADMIN_CUSTOM_ADMIN_FILE := backend/admin.py
DJANGO_CLEAN_DIRS = backend contactpage dist frontend home logging_demo model_form_demo \
node_modules payments privacypage search sitepage siteuser unit_test_demo
DJANGO_CLEAN_FILES = .babelrc .browserslistrc .dockerignore .eslintrc .gitignore .nvmrc \
.stylelintrc.json Dockerfile db.sqlite3 docker-compose.yml manage.py \
package-lock.json package.json postcss.config.js requirements-test.txt \
requirements.txt
DJANGO_FRONTEND_FILES = .babelrc .browserslistrc .eslintrc .nvmrc .stylelintrc.json \
frontend package-lock.json \
package.json postcss.config.js
DJANGO_SETTINGS_DIR = backend/settings
DJANGO_SETTINGS_BASE_FILE = $(DJANGO_SETTINGS_DIR)/base.py
DJANGO_SETTINGS_DEV_FILE = $(DJANGO_SETTINGS_DIR)/dev.py
DJANGO_SETTINGS_PROD_FILE = $(DJANGO_SETTINGS_DIR)/production.py
DJANGO_SETTINGS_SECRET_KEY = $(shell openssl rand -base64 48)
DJANGO_URLS_FILE = backend/urls.py
EB_DJANGO_DATABASE_HOST = $(call EB_DJANGO_DATABASE,HOST)
EB_DJANGO_DATABASE_NAME = $(call EB_DJANGO_DATABASE,NAME)
EB_DJANGO_DATABASE_PASS = $(call EB_DJANGO_DATABASE,PASSWORD)
EB_DJANGO_DATABASE_URL = $(shell eb ssh -c "source /opt/elasticbeanstalk/deployment/custom_env_var; \
env | grep DATABASE_URL" | awk -F= '{print $$2}')
EB_DJANGO_DATABASE_USER = $(call EB_DJANGO_DATABASE,USER)
EB_DIR_NAME := .elasticbeanstalk
EB_ENV_NAME ?= $(PROJECT_NAME)-$(GIT_BRANCH)-$(GIT_REV)
EB_PLATFORM ?= "Python 3.11 running on 64bit Amazon Linux 2023"
EC2_INSTANCE_MAX ?= 1
EC2_INSTANCE_MIN ?= 1
EC2_INSTANCE_PROFILE ?= aws-elasticbeanstalk-ec2-role
EC2_INSTANCE_TYPE ?= t4g.small
EC2_LB_TYPE ?= application
EDITOR_REVIEW = subl
GIT_ADD := git add
GIT_BRANCH = $(shell git branch --show-current)
GIT_BRANCHES = $(shell git branch -a)
GIT_CHECKOUT = git checkout
GIT_COMMIT = git commit
GIT_COMMIT_IGNORE_FILE = .gitignore
GIT_PUSH = git push
GIT_PUSH_FORCE = $(GIT_PUSH) --force-with-lease
GIT_REV = $(shell git rev-parse --short HEAD)
GIT_STATUS = git status
MONGODB_MIGRATIONS_DIR := backend/migrations
PACKAGE_NAME = $(shell echo $(PROJECT_NAME) | sed 's/-/_/g')
PAGER ?= less
PIP_DEPS = python -m pipdeptree
PIP_ENSURE = python -m ensurepip
PIP_FREEZE = python -m pip freeze
PIP_INSTALL = python -m pip install
PIP_UNINSTALL = python -m pip uninstall -y
PLONE_VERSION_FILE = https://dist.plone.org/release/6.0.11.1/constraints.txt
PROJECT_CUSTOM_FILE := project.mk
PROJECT_EMAIL := [email protected]
PROJECT_NAME = project-makefile
PYTHON_HTTP_SERVER = python -m http.server
RANDIR := $(shell openssl rand -base64 12 | sed 's/\///g')
TMPDIR := $(shell mktemp -d)
UNAME := $(shell uname)
# ================================================================================
# Include $(PROJECT_CUSTOM_FILE) if it exists
# ================================================================================
ifneq ($(wildcard $(PROJECT_CUSTOM_FILE)),)
include $(PROJECT_CUSTOM_FILE)
endif
# ================================================================================
# Multi-line variables to be used by phony target rules
# ================================================================================
# ----------------------------------------------------------------
# Django Custom Admin Demo
#
# https://docs.djangoproject.com/en/5.1/ref/contrib/admin/#overriding-the-default-admin-site
# ----------------------------------------------------------------
define DJANGO_ADMIN_CUSTOM_ADMIN
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 DJANGO_ADMIN_CUSTOM_APPS
from django.contrib.admin.apps import AdminConfig
class CustomAdminConfig(AdminConfig):
default_site = "backend.admin.CustomAdminSite"
endef
define DJANGO_API_SERIALIZERS
from rest_framework import serializers
from siteuser.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ["url", "username", "email", "is_staff"]
endef
define DJANGO_API_VIEWS
from ninja import NinjaAPI
from rest_framework import viewsets
from siteuser.models import User
from .serializers import UserSerializer
api = NinjaAPI()
@api.get("/hello")
def hello(request):
return "Hello world"
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
endef
define DJANGO_DOCKER_COMPOSE
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 DJANGO_DOCKER_FILE
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 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
# ----------------------------------------------------------------
# Django Frontend
#
# For use with python-webpack-boilerplate
# ----------------------------------------------------------------
define DJANGO_FRONTEND
import React from 'react';
import { createRoot } from 'react-dom/client';
import 'bootstrap';
// import '@fortawesome/fontawesome-free/js/fontawesome';
// import '@fortawesome/fontawesome-free/js/solid';
// import '@fortawesome/fontawesome-free/js/regular';
// import '@fortawesome/fontawesome-free/js/brands';
import getDataComponents from '../dataComponents';
import UserContextProvider from '../context';
import * as components from '../components';
import "../styles/index.scss";
import "../styles/theme-blue.scss";
import "./config";
const { ErrorBoundary } = components;
const dataComponents = getDataComponents(components);
const container = document.getElementById('app');
const root = createRoot(container);
const App = () => (
<ErrorBoundary>
<UserContextProvider>
{dataComponents}
</UserContextProvider>
</ErrorBoundary>
);
root.render(<App />);
endef
define DJANGO_FRONTEND_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 DJANGO_FRONTEND_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 DJANGO_FRONTEND_COMPONENTS
export { default as ErrorBoundary } from './ErrorBoundary';
export { default as UserMenu } from './UserMenu';
endef
define DJANGO_FRONTEND_CONFIG
import '../utils/themeToggler.js';
// import '../utils/tinymce.js';
endef
define DJANGO_FRONTEND_CONTEXT_INDEX
export { UserContextProvider as default } from './UserContextProvider';
endef
define DJANGO_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) {
console.error('Login error:', error);
// Handle error, e.g., show an error message to the user
}
};
const logout = () => {
try {
// Add logic to handle logout, set isAuthenticated to false
setIsAuthenticated(false);
} catch (error) {
console.error('Logout error:', error);
// Handle error, e.g., show an error message to the user
}
};
return (
<UserContext.Provider value={{ isAuthenticated, login, logout }}>
{children}
</UserContext.Provider>
);
};
UserContextProvider.propTypes = {
children: PropTypes.node.isRequired,
};
export const useUserContext = () => {
const context = useContext(UserContext);
if (!context) {
throw new Error('useUserContext must be used within a UserContextProvider');
}
return context;
};
// Add PropTypes for the return value of useUserContext
useUserContext.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
login: PropTypes.func.isRequired,
logout: PropTypes.func.isRequired,
};
endef
define DJANGO_FRONTEND_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 DJANGO_FRONTEND_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 DJANGO_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 DJANGO_FRONTEND_STYLES
// If you comment out code below, bootstrap will use red as primary color
// and btn-primary will become red
// $primary: red;
@import "~bootstrap/scss/bootstrap.scss";
.jumbotron {
// should be relative path of the entry scss file
background-image: url("../../vendors/images/sample.jpg");
background-size: cover;
}
#theme-toggler-authenticated:hover {
cursor: pointer; /* Change cursor to pointer on hover */
color: #007bff; /* Change color on hover */
}
#theme-toggler-anonymous:hover {
cursor: pointer; /* Change cursor to pointer on hover */
color: #007bff; /* Change color on hover */
}
endef
define DJANGO_FRONTEND_THEME_BLUE
@import "~bootstrap/scss/bootstrap.scss";
[data-bs-theme="blue"] {
--bs-body-color: var(--bs-white);
--bs-body-color-rgb: #{to-rgb($$white)};
--bs-body-bg: var(--bs-blue);
--bs-body-bg-rgb: #{to-rgb($$blue)};
--bs-tertiary-bg: #{$$blue-600};
.dropdown-menu {
--bs-dropdown-bg: #{color-mix($$blue-500, $$blue-600)};
--bs-dropdown-link-active-bg: #{$$blue-700};
}
.btn-secondary {
--bs-btn-bg: #{color-mix($gray-600, $blue-400, .5)};
--bs-btn-border-color: #{rgba($$white, .25)};
--bs-btn-hover-bg: #{color-adjust(color-mix($gray-600, $blue-400, .5), 5%)};
--bs-btn-hover-border-color: #{rgba($$white, .25)};
--bs-btn-active-bg: #{color-adjust(color-mix($gray-600, $blue-400, .5), 10%)};
--bs-btn-active-border-color: #{rgba($$white, .5)};
--bs-btn-focus-border-color: #{rgba($$white, .5)};
// --bs-btn-focus-box-shadow: 0 0 0 .25rem rgba(255, 255, 255, 20%);
}
}
endef
define DJANGO_FRONTEND_THEME_TOGGLER
document.addEventListener('DOMContentLoaded', function () {
const rootElement = document.documentElement;
const anonThemeToggle = document.getElementById('theme-toggler-anonymous');
const authThemeToggle = document.getElementById('theme-toggler-authenticated');
if (authThemeToggle) {
localStorage.removeItem('data-bs-theme');
}
const anonSavedTheme = localStorage.getItem('data-bs-theme');
if (anonSavedTheme) {
rootElement.setAttribute('data-bs-theme', anonSavedTheme);
}
if (anonThemeToggle) {
anonThemeToggle.addEventListener('click', function () {
const currentTheme = rootElement.getAttribute('data-bs-theme') || 'light';
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
rootElement.setAttribute('data-bs-theme', newTheme);
localStorage.setItem('data-bs-theme', newTheme);
});
}
if (authThemeToggle) {
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
authThemeToggle.addEventListener('click', function () {
const currentTheme = rootElement.getAttribute('data-bs-theme') || 'light';
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
fetch('/user/update_theme_preference/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken, // Include the CSRF token in the headers
},
body: JSON.stringify({ theme: newTheme }),
})
.then(response => response.json())
.then(data => {
rootElement.setAttribute('data-bs-theme', newTheme);
})
.catch(error => {
console.error('Error updating theme preference:', error);
});
});
}
});
endef
define DJANGO_FRONTEND_TINYMCE_JS
import tinymce from 'tinymce';
import 'tinymce/icons/default';
import 'tinymce/themes/silver';
import 'tinymce/skins/ui/oxide/skin.css';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/code';
import 'tinymce/plugins/emoticons';
import 'tinymce/plugins/emoticons/js/emojis';
import 'tinymce/plugins/link';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/table';
import 'tinymce/models/dom';
tinymce.init({
selector: 'textarea#editor',
plugins: 'advlist code emoticons link lists table',
toolbar: 'bold italic | bullist numlist | link emoticons',
skin: false,
content_css: false,
});
endef
define DJANGO_FRONTEND_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"></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>
<li><a className="dropdown-item" href="/logging-demo/">Logging Demo</a></li>
<li><a className="dropdown-item" href="/payments/">Payments 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="/api" target="_blank">Django API</a></li>
<li><a className="dropdown-item" href="/wagtail" target="_blank">Wagtail admin</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 dropdown-toggle" type="button" aria-expanded="false" href="/accounts/login/"></a>
</li>
)}
</div>
);
};
UserMenu.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
isSuperuser: PropTypes.bool.isRequired,
textColor: PropTypes.string,
};
export default UserMenu;
endef
# ----------------------------------------------------------------
# Django Home Page for Django Minimal
#
# Wagtail projects includes a home page model, Django does not.
# ----------------------------------------------------------------
define DJANGO_HOME_PAGE_ADMIN
from django.contrib import admin # noqa
# Register your models here.
endef
define DJANGO_HOME_PAGE_MODELS
from django.db import models # noqa
# Create your models here.
endef
define DJANGO_HOME_PAGE_URLS
from django.urls import path
from .views import HomeView
urlpatterns = [path("", HomeView.as_view(), name="home")]
endef
define DJANGO_HOME_PAGE_VIEWS
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = "home.html"
endef
# ----------------------------------------------------------------
# Django Logging Demo
# ----------------------------------------------------------------
define DJANGO_LOGGING_DEMO_ADMIN
# Register your models here.
endef
define DJANGO_LOGGING_DEMO_MODELS
from django.db import models # noqa
# Create your models here.
endef
define DJANGO_LOGGING_DEMO_SETTINGS
INSTALLED_APPS.append("logging_demo") # noqa
endef
define DJANGO_LOGGING_DEMO_URLS
from django.urls import path
from .views import logging_demo
urlpatterns = [
path("", logging_demo, name="logging_demo"),
]
endef
define DJANGO_LOGGING_DEMO_VIEWS
from django.http import HttpResponse
import logging
logger = logging.getLogger(__name__)
def logging_demo(request):
logger.debug("Hello, world!")
return HttpResponse("Hello, world!")
endef
define DJANGO_MANAGE_PY
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings.dev")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()
endef
# ----------------------------------------------------------------
# Django Model Form Demo
# ----------------------------------------------------------------
define DJANGO_MODEL_FORM_DEMO_ADMIN
from django.contrib import admin
from .models import ModelFormDemo
@admin.register(ModelFormDemo)
class ModelFormDemoAdmin(admin.ModelAdmin):
pass
endef
define DJANGO_MODEL_FORM_DEMO_FORMS
from django import forms
from .models import ModelFormDemo
class ModelFormDemoForm(forms.ModelForm):
class Meta:
model = ModelFormDemo
fields = ["name", "email", "age", "is_active"]
endef
define DJANGO_MODEL_FORM_DEMO_MODELS
from django.db import models
from django.shortcuts import reverse
class ModelFormDemo(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name or f"test-model-{self.pk}"
def get_absolute_url(self):
return reverse("model_form_demo_detail", kwargs={"pk": self.pk})
endef
define DJANGO_MODEL_FORM_DEMO_TEMPLATE_DETAIL
{% extends 'base.html' %}
{% block content %}
<h1>Test Model Detail: {{ model_form_demo.name }}</h1>
<p>Name: {{ model_form_demo.name }}</p>
<p>Email: {{ model_form_demo.email }}</p>
<p>Age: {{ model_form_demo.age }}</p>
<p>Active: {{ model_form_demo.is_active }}</p>
<p>Created At: {{ model_form_demo.created_at }}</p>
<a href="{% url 'model_form_demo_update' model_form_demo.pk %}">Edit Test Model</a>
{% endblock %}
endef
define DJANGO_MODEL_FORM_DEMO_TEMPLATE_FORM
{% extends 'base.html' %}
{% block content %}
<h1>
{% if form.instance.pk %}
Update Test Model
{% else %}
Create Test Model
{% endif %}
</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% endblock %}
endef
define DJANGO_MODEL_FORM_DEMO_TEMPLATE_LIST
{% extends 'base.html' %}
{% block content %}
<h1>Test Models List</h1>
<ul>
{% for model_form_demo in model_form_demos %}
<li>
<a href="{% url 'model_form_demo_detail' model_form_demo.pk %}">{{ model_form_demo.name }}</a>
</li>
{% endfor %}
</ul>
<a href="{% url 'model_form_demo_create' %}">Create New Test Model</a>
{% endblock %}
endef
define DJANGO_MODEL_FORM_DEMO_URLS
from django.urls import path
from .views import (
ModelFormDemoListView,
ModelFormDemoCreateView,
ModelFormDemoUpdateView,
ModelFormDemoDetailView,
)
urlpatterns = [
path("", ModelFormDemoListView.as_view(), name="model_form_demo_list"),
path("create/", ModelFormDemoCreateView.as_view(), name="model_form_demo_create"),
path(
"<int:pk>/update/",
ModelFormDemoUpdateView.as_view(),
name="model_form_demo_update",
),
path("<int:pk>/", ModelFormDemoDetailView.as_view(), name="model_form_demo_detail"),
]
endef
define DJANGO_MODEL_FORM_DEMO_VIEWS
from django.views.generic import ListView, CreateView, UpdateView, DetailView
from .models import ModelFormDemo
from .forms import ModelFormDemoForm
class ModelFormDemoListView(ListView):
model = ModelFormDemo
template_name = "model_form_demo_list.html"
context_object_name = "model_form_demos"
class ModelFormDemoCreateView(CreateView):
model = ModelFormDemo
form_class = ModelFormDemoForm
template_name = "model_form_demo_form.html"
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
class ModelFormDemoUpdateView(UpdateView):
model = ModelFormDemo
form_class = ModelFormDemoForm
template_name = "model_form_demo_form.html"
class ModelFormDemoDetailView(DetailView):
model = ModelFormDemo
template_name = "model_form_demo_detail.html"
context_object_name = "model_form_demo"
endef
define DJANGO_MONGODB_APPS
from django.contrib.admin.apps import AdminConfig
from django.contrib.auth.apps import AuthConfig
from django.contrib.contenttypes.apps import ContentTypesConfig
from allauth.account.apps import AccountConfig
class MongoAdminConfig(AdminConfig):
default_auto_field = "django_mongodb.fields.ObjectIdAutoField"
class MongoAuthConfig(AuthConfig):
default_auto_field = "django_mongodb.fields.ObjectIdAutoField"
class MongoContentTypesConfig(ContentTypesConfig):
default_auto_field = "django_mongodb.fields.ObjectIdAutoField"
class MongoAccountConfig(AccountConfig):
default_auto_field = "django_mongodb.fields.ObjectIdAutoField"
endef
# ----------------------------------------------------------------
# Django Payments Demo
# ----------------------------------------------------------------
define DJANGO_PAYMENTS_ADMIN
from django.contrib import admin
from .models import Product, Order
admin.site.register(Product)
admin.site.register(Order)
endef
define DJANGO_PAYMENTS_FORM
from django import forms
class PaymentsForm(forms.Form):
stripeToken = forms.CharField(widget=forms.HiddenInput())
amount = forms.DecimalField(
max_digits=10, decimal_places=2, widget=forms.HiddenInput()
)
endef
define DJANGO_PAYMENTS_MIGRATION_0002
from django.db import migrations
import os
import secrets
import logging
logger = logging.getLogger(__name__)
def generate_default_key():
return "sk_test_" + secrets.token_hex(24)
def set_stripe_api_keys(apps, schema_editor):
# Get the Stripe API Key model
APIKey = apps.get_model("djstripe", "APIKey")
# Fetch the keys from environment variables or generate default keys
test_secret_key = os.environ.get("STRIPE_TEST_SECRET_KEY", generate_default_key())
live_secret_key = os.environ.get("STRIPE_LIVE_SECRET_KEY", generate_default_key())
logger.info("STRIPE_TEST_SECRET_KEY: %s", test_secret_key)
logger.info("STRIPE_LIVE_SECRET_KEY: %s", live_secret_key)
# Check if the keys are not already in the database
if not APIKey.objects.filter(secret=test_secret_key).exists():
APIKey.objects.create(secret=test_secret_key, livemode=False)