An example of using reactpy-django to create a simple, Django based, single page application (SPA). The project is a reworking of the introductory Django project: Writing your first Django app. If you are unfamiliar with Django get up to speed by working through this first.
git clone https://github.com/stevej2608/reactpy-django-example
cd reactpy-django-example
poetry install --no-root
python manage.py runserver localhost:8000
Visit http://localhost:8000
Use Django admin to add/remove questions. Visit Admin or simply click the Admin link, top-right in every page.
Credentials:
user:admin, password:superadmin
To change the admin password:
python manage.py changepassword admin
- No templates, all pages are coded in python alone.
- Uses reactpy_django.router to dispatch page views.
- Authorization & protected routes.
- Integrates with Django ORM using use_query and use_mutation hooks.
- Can be used along side other Django apps
- VSCODE debug configs for server & testing
reactpy-django makes no changes to the Django ecosystem. The package provides a bridge that maps standard Django routes, as defined by urls, views and templates, onto reactpy components. One or many such mapping can be defined.
As with any Django app urls.py defines a URL pattern that maps onto a view. The view, in turn, loads a template,
The bridge between Django and reactpy-django is defined in the template, in our case:
{% load reactpy %}
<body>
{% component "polls.spa_router.spa_router" %}
</body>
In this project just one view/template definition is used to map between several url patterns defined in urls.py and the reactpy spa_router. The router then unpacks the requested URL and directs it to the relevant reactpy page.
Three pages (index, detail & results) together with a 404 page define the the application. These are pure reactpy based.
A container page_container.py wraps each page in a common wrapper that contains the navbar etc.
The polls ORM model used is the one created by Writing your first Django app.
reactpy-django provides the hooks use_query and use_mutation to access the ORM model. I found these a little cumbersome to use. A use_query wrapper is defined in common.py. This converts loading and error notifications into exceptions allowing the caller to be wrapped in a try/catch block.
...
try:
questions: List[Question] = use_query(Question.get_ordered_questions)
return html.div(
html.h1({'class_name':"text-center mb-3"},"Poll Questions"),
*[QuestionCard(question) for question in questions]
)
except LoadingException as ex:
return html.h2(str(ex))
except RecordNotFound:
return html.h2("No polls available.")
except Exception:
return Page_404()
The first time:
playwright install
then:
python manage.py test
- reactpy
- reactpy-django * use-mutation
- django-unfold, Modern Django admin theme for seamless interface development
- Writing your first Django app
- django-polls
- Bootstrap Pulse Theme