3 KiB
3 KiB
Chapter 3: adding content to templates
Escaping user data
Django escapes user data by default, on output.
- create a ticket with a
<h1>in the body
<!DOCTYPE html>
...
<h1>View tickets</h1>
<div>Submitted: "Test user", Created at: Aug. 16, 2022, 5:05 p.m.</div>
<div>Body: "<h1>Help, I need help with a bug</h1>"</div>
...
- we can prevent escaping by showing fields with
safe,- as in
{{ ticket.body | safe }}.
- as in
```http -pb http://localhost:8000/tickets
<!DOCTYPE html>
...
<h1>View tickets</h1>
<div>Submitted: "Test user", Created at: Aug. 16, 2022, 5:05 p.m.</div>
<div>Body: "<h1>Help, I need help with a bug</h1>"</div>
- we can also disable escaping with a tag:
{%autoescape off%} ... {%endautoescape%}
- within
autoescapewe can still force escaping:{%autoescape off%} {{whatever | escape}} {%endautoescape%}
Static content and URL building
Static content
Static file support is provided by the django.contrib.staticfiles,
so verify it is present in settings.py#INSTALLED_APPS.
That app is configured with the settings.py#STATIC_URL variable,
defaulting to /static.
https://docs.djangoproject.com/en/3.2/howto/static-files/
It assumes assets are in a <app>/static folder.
- In the templates
- add
{% load static %}to make thestaticfunction available - invoke it as
{% static '<asset>' %}
- add
It may be necessary to restart the dev server to have the routing work.
URLs for routes
We use the {% url <route> <args>... %} for that.
The name of the route used here is defined as the name parameter
for the route in urls.py.
SPAs
- Create the SPA:
npx create-react-app ticketing-frontend - Enter that folder:
cd ticketing-frontend - Build the SPA bundle:
npm run build- this will create a
ticketing-frontend/build/directory
- this will create a
- In
urls.py- Disable all existing routes
- Import re_path:
from django.urls import re_path - Import the generic template view:
from django.views.generic import TemplateView - Declare the route:
re_path('', TemplateView(template_name='index'))
- In
settings.py:- Disable all existing templates by settings
TEMPLATES.0.APP_DIRS = False - Point to the React build:
TEMPLATES.DIRS': ['./ticketing-frontend/build'] - Update the base static URL:
STATIC_URL = '/static/'STATICFILES_DIRS = [os.path.join(BASE_DIR, "./ticketing-frontend/build/static")]
- Disable all existing templates by settings
Now we need to enable acces to our tickets.
- in
urls.pypath('api/tickets', views.tickets_raw)
// http -pb http://127.0.0.1:8000/api/tickets
[
{
"body": "Help, I need help with a bug",
"created_at": "2022-08-16T17:05:02.642Z",
"id": 3,
"submitter": "Test user"
},
{
"body": "Help, I need help with a bug",
"created_at": "2022-08-16T17:09:14.185Z",
"id": 4,
"submitter": "nwaasrknojjc"
}
]
At this point, all that remains is to request the data from React, e.g. with Fetch or Axios.