Debian Codegraph @

docs/pages/template-tags.md

raw
1 # Template Tags
2
3 ## Generating inline QR code in your HTML (qr_from_text)
4 The tag **`qr_from_text`** generates an embedded `<svg>` or `<img>` tag within the HTML code produced by your template.
5
6 The following renders a tiny "hello world" QR code in SVG format with an inline `<svg>` tag:
7 ```htmldjango
8 {% qr_from_text "Hello World!" size="T" %}
9 ```
10
11 Here is a medium "hello world" QR code in PNG format:
12 ```htmldjango
13 {% qr_from_text "Hello World!" size="m" image_format="png" error_correction="L" %}
14 ```
15 This will output an `<img>` tag with data URI: `<img src="data:image/png;base64,[...]">`
16
17 ### Customizing the HTML output for inline QR codes
18
19 You can customize `alt` and `class` attributes can be customized through `alt_text` and `class_names` arguments of `qr_from_text`:
20 ```htmldjango
21 {% qr_from_text "Hello World!" alt_text="My Hello World image" class_names="ui centered image" %}
22 ```
23 The `alt_text` argument indicates the value of the alternative text embedded in the `alt` attribute of the returned
24 image tag. When set to `None`, the alternative text is set to the string representation of data. The alternative
25 text is automatically escaped. You may use an empty string to explicitly set an empty alternative text.
26
27 The `class_names` argument indicates the value of the `class` attribute of the returned
28 image tag. When set to `None` or empty, the class attribute is not set.
29
30 By default, when SVG format is specified, the generated tag is an inline SVG path: `<svg>`. To change that, you can p
31 ass `use_data_uri_for_svg=True` to the `qr_from_text` tag:
32 ```htmldjango
33 {% qr_from_text "Hello World!" use_data_uri_for_svg=True %}
34 ```
35 This will output an `<img>` tag with a data URI similar to what you get by default for the PNG format:
36 `<img src="data:image/svg+xml;base64,[...]">`. This also allows you to define the `class` and `alt` HTML attributes
37 of the `<img>` tag as shown above. When `use_data_uri_for_svg` is not set or is set to `False`, the `alt_text`
38 and `class_names` arguments are ignored.
39
40 ## Generating URLs to QR code images (qr_url_from_text)
41
42 The **`qr_url_from_text`** tag generates an url to an image representing the QR code. It comes with the same options as `qr_from_text` to customize the image format (SVG or PNG), the size, the border, and the matrix size. It also has an additional option **`cache_enabled`** to disable caching of served image.
43
44 Here is a medium "hello world" QR code that uses a URL to serve the image in SVG format:
45
46 ```htmldjango
47 <img src="{% qr_url_from_text "Hello World!" %}" alt="Hello World!">
48 ```
49
50 Here is a "hello world" QR code in version 10 that uses a URL to serve the image in PNG format:
51
52 ```htmldjango
53 <img src="{% qr_url_from_text "Hello World!" size=8 version=10 image_format='png' %}" alt="Hello World!">
54 ```
55
56 The image targeted by the generated URL is served by a view provided in `qr_code.urls`. Therefore, you need to include the URLs provided by `qr_code.urls` in your app in order to make this tag work. This can be achieved with something like this:
57
58 ```python
59 from django.conf.urls import include
60 from django.urls import path
61
62 urlpatterns = [
63 path('qr_code/', include('qr_code.urls', namespace="qr_code")),
64 ]
65 ```
66
67 The QR code images are served via a URL named **`qr_code:serve_qr_code_image`**. You can customize the path under which the images are served (i.e. the path bound to the URL named `qr_code:serve_qr_code_image`) with the optional setting **`SERVE_QR_CODE_IMAGE_PATH`** which defaults to `images/serve-qr-code-image/`. Note that the trailing slash is mandatory and that defining this setting to an empty string leads to using the default value. The example below will serve any QR code image from `<base URL or your application>/qr-code-image/`:
68
69 ```python
70 # In urls.py
71 from django.conf.urls import include
72 from django.urls import path
73
74 urlpatterns = [
75 path('', include('qr_code.urls', namespace='qr_code')),
76 ]
77
78 # In your settings
79 SERVE_QR_CODE_IMAGE_PATH = 'qr-code-image/'
80 ```
81
82 ### Caching served images
83
84 A large QR code (version 40) requires 0.2 second to be generated on a powerful machine (in 2018), and probably more than half a second on a really cheap hosting.
85
86 The image served by the *qr_code* app can be cached to improve performances and reduce CPU usage required to generate the QR codes. In order to activate caching, you simply need to declare a cache alias with the setting **`QR_CODE_CACHE_ALIAS`** to indicate in which cache to store the generated QR codes.
87
88 For instance, you may declare an additional cache for your QR codes like this in your Django settings:
89
90 ```python
91 CACHES = {
92 'default': {
93 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
94 },
95 'qr-code': {
96 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
97 'LOCATION': 'qr-code-cache',
98 'TIMEOUT': 3600
99 }
100 }
101
102 QR_CODE_CACHE_ALIAS = 'qr-code'
103 ```
104
105 The `QR_CODE_CACHE_ALIAS = 'qr-code'` tells the *qr_code* app to use that cache for storing the generated QR codes. All QR codes will be cached with the specified *TIMEOUT* when a non-empty value is set to `QR_CODE_CACHE_ALIAS`.
106
107 If you want to activate the cache for QR codes, but skip the caching for some specific codes, you can use the keyword argument `cache_enabled=False` when using `qr_url_from_text`.
108
109 Here is a "hello world" QR code in version 20 with an error correction level Q (25% of redundant data) that uses a URL to serve the image in SVG format, and disable caching for served image:
110
111 ```htmldjango
112 <img src="{% qr_url_from_text "Hello World!" size=8 version=20 error_correction="Q" cache_enabled=False %}" alt="Hello World!">
113 ```
114
115 ### Protecting access to QR code images
116
117 The default settings protect the URLs that serve QR code images against external requests, and thus against possibly easy (D)DoS attacks.
118
119 Here are the available settings to manage the protection for served images:
120
121 ```python
122 from qr_code.qrcode import constants
123
124 QR_CODE_URL_PROTECTION = {
125 constants.TOKEN_LENGTH: 30, # Optional random token length for URL protection. Defaults to 20.
126 constants.SIGNING_KEY: 'my-secret-signing-key', # Optional signing key for URL token. Uses SECRET_KEY if not defined.
127 constants.SIGNING_SALT: 'my-signing-salt', # Optional signing salt for URL token.
128 constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True # Tells whether a registered user can request the QR code URLs from outside a site that uses this app. It can be a boolean value used for any user or a callable that takes a user as parameter. Defaults to False (nobody can access the URL without the signature token).
129 }
130 ```
131
132 #### Signing request URLs
133
134 By default, the application only serves QR code images for authenticated URLs (requests generated from your application and addressed to your application). The authentication uses a HMAC to sign the request query arguments. The authentication code is passed as a query argument named **`token`** which is automatically generated by `qr_url_from_text` or `qr_url_from_data`. Whenever the signature is invalid, the application returns a *HTTP 403 Permission denied* response when processing the request for serving a QR code image.
135
136 This mechanism ensures that, by default, nobody can send external requests to your application to obtain custom QR codes for free. This is especially useful if you display QR code URLs on public pages (no user authentication).
137
138 The `token` query argument is not mandatory and, when a request reaches the `qr_code:serve_qr_code_image` URL without that token, the protection mechanism falls back to the user authentication mechanism (see chapter below).
139
140 It is possible to explicitly remove the signature token that protects a specific URL with the parameter **`url_signature_enabled=False`**. Here is a "hello world" QR code that uses a URL to serve the image in SVG format without the `token` query argument :
141
142 ```htmldjango
143 <img src="{% qr_url_from_text "Hello World!" url_signature_enabled=False %}" alt="Hello World!">
144 ```
145
146 The `token` parameter will not be part of the query string of the generated URL, making possible to build a simpler, predictable URL. However, this will trigger the user authentication mechanism (see chapter below).
147
148 #### Handling user authentication when serving QR code images
149
150 If you are interested in providing the QR code images as a service, there is a setting named **`ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER`** to grant access to some controlled users. This setting tells who can bypass the url signature token (see chapter above). It can be a boolean value used for any authenticated user, or a callable that takes a user as only parameter.
151
152 Setting the `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` option to `True` tells the application to serve QR code images to authenticated users only. Hence, to grant access to any authenticated user to generated images, you can use this in your settings:
153
154 ```python
155 from qr_code.qrcode import constants
156
157 QR_CODE_URL_PROTECTION = {
158 constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: True
159 }
160 ```
161
162 Setting the option `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` to a callable that always returns `True` (even for anonymous users) will allow anyone to access QR code image generation from outside your Django app. The following settings will grant access to anonymous users to generated images:
163
164 ```python
165 from qr_code.qrcode import constants
166
167 QR_CODE_URL_PROTECTION = {
168 constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER: lambda u: True
169 }
170 ```
171
172 Please note that, if your service is available on the Internet, allowing anyone to generate any kind of QR code via your Django application - as shown above - might generate a very heavy load on your server.
173
174 ## Special encoding modes with qr_from_data and qr_url_from_data
175
176 The tags **`qr_from_data`** and **`qr_url_from_data`** produce results similar to those of `qr_from_text` and `qr_url_from_text`, but they avoid converting everything to text (UTF-8 encoded by default, or any supported charset depending on `encoding` option).
177
178 The ISO/IEC 18004 standard defines four modes in order to encode the data as efficiently as possible.
179
180 ### Numeric mode
181 The numeric mode is the most efficient way to encode digits. This mode does not cover negative numbers because it does not support the minus sign (or plus sign).
182
183 The numeric mode is supported by QR Codes and Micro QR Codes. The encoding engine detects (Segno) the numeric mode if the data is provided as string (e.g. '54') or integer (e.g. 54) to `qr_from_data` or `qr_url_from_data`.
184
185 ### Alphanumeric mode
186 The alphanumeric mode extends the numeric mode by various characters. Namely, about the upper case letters ABCDEFGHIJKLMNOPQRSTUVWXYZ, a space character " " and other letters $%*+-./:.
187
188 ### Kanji mode
189 Kanji can be encoded compactly and efficiently and requires significantly less space than encoding the characters in UTF-8.
190
191 ### Byte mode
192 The byte mode covers all data which cannot be represented by the other modes. When the `encoding` option is set to `None`, the encoding engine (Segno) detects, according to ISO/IEC 18004, to encode the data with ISO 8859-1. In case the data cannot be represented by ISO 8859-1, UTF-8 is used as fallback.
193
194 NOTE: When using `qr_from_text` or `qr_url_from_text`, the byte mode with UTF-8 encoding is forced by default . You may use the `encoding` option to change this behavior. It appears to be one of the most portable way of encoding text for proper decoding among the readers.
195
196 ### Examples
197 The following renders a tiny numeric QR code containing the value `2021` with a `svg` tag:
198 ```htmldjango
199 {% qr_from_data 2021 size="T" %}
200 ```
201
202 Here is a micro QR code with an `img` tag containing the value `2021`:
203 ```htmldjango
204 {% qr_from_data 2021 micro=True image_format="png" %}
205 ```
206
207 ## QR codes for apps
208
209 Aside from generating a QR code from a given text, you can also generate codes for specific application purposes, that a reader can interpret as an action to take: open a mail client to send an e-mail to a given address, add a contact to your phone book, connect to a Wi-Fi, start a SMS, etc. See [this documentation](https://github.com/zxing/zxing/wiki/Barcode-Contents) about what a QR code can encode.
210
211 Django QR Code proposes several utility tags to ease the generation of such codes, without having to build the appropriate text representation for each action you need. This remove the hassle of reading the specifications and handling all the required escaping for reserved chars.
212
213 Please note that some commands are common patterns, rather than formal specifications. Therefore, there is no guarantee that all QR code readers will handle them properly.
214
215 The following tags targeting apps are available:
216 * `qr_for_email` and `qr_url_for_email`
217 * `qr_for_tel` and `qr_url_for_tel`
218 * `qr_for_sms` and `qr_url_for_sms`
219 * `qr_for_geolocation` and `qr_url_for_geolocation`
220 * `qr_for_google_maps` and `qr_url_for_google_maps`
221 * `qr_for_youtube` and `qr_url_for_youtube`
222 * `qr_for_google_play` and `qr_url_for_google_play`
223 * `qr_for_mecard` and `qr_url_for_mecard`
224 * `qr_for_vcard` and `qr_url_for_vcard`
225 * `qr_for_wifi` and `qr_url_for_wifi`
226 * `qr_for_epc` and `qr_url_for_epc`
227 * `qr_for_event` and `qr_url_for_event`
228 * `qr_for_contact` and `qr_url_for_contact` (legacy, do not use in new projects)
229
230 **Note**: All options and settings presented for `qr_from_text`, `qr_url_from_text`, `qr_from_data`, and `qr_url_from_data` also apply to any of the above "QR codes for apps".
231
232 You could write a view like this:
233
234 ```python
235 import datetime
236 from datetime import date
237 from django.shortcuts import render
238 from qr_code.qrcode.utils import MeCard, VCard, EpcData, VEvent, EventClass, EventTransparency, EventStatus, WifiConfig, Coordinates, QRCodeOptions
239
240
241 def application_qr_code_demo(request):
242 # Use a MeCard instance to encapsulate the detail of the contact.
243 mecard_contact = MeCard(
244 name='Doe, John',
245 phone='+41769998877',
246 email='[email protected]',
247 url='http://www.company.com',
248 birthday=date(year=1985, month=10, day=2),
249 memo='Development Manager',
250 org='Company Ltd'
251 )
252
253 # Use a VCard instance to encapsulate the detail of the contact.
254 vcard_contact = VCard(
255 name='Doe; John',
256 phone='+41769998877',
257 email='[email protected]',
258 url='http://www.company.com',
259 birthday=date(year=1985, month=10, day=2),
260 street='Cras des Fourches 987',
261 city='Delémont',
262 zipcode=2800,
263 region='Jura',
264 country='Switzerland',
265 memo='Development Manager',
266 org='Company Ltd'
267 )
268
269 # Use a WifiConfig instance to encapsulate the configuration of the connexion.
270 wifi_config = WifiConfig(
271 ssid='my-wifi',
272 authentication=WifiConfig.AUTHENTICATION.WPA,
273 password='wifi-password'
274 )
275
276 # Use a EpcData instance to encapsulate the data of the European Payments Council Quick Response Code.
277 epc_data = EpcData(
278 name='Wikimedia Foerdergesellschaft',
279 iban='DE33100205000001194700',
280 amount=50.0,
281 text='To Wikipedia'
282 )
283
284 # Build coordinates instances.
285 google_maps_coordinates = Coordinates(latitude=586000.32, longitude=250954.19)
286 geolocation_coordinates = Coordinates(latitude=586000.32, longitude=250954.19, altitude=500)
287
288 # Build event data (VEVENT properties)
289 # NB for start and end of event:
290 # - Naive date and time is rendered as floating time.
291 # - Aware date and time is rendered as UTC converted time.
292 event = VEvent(
293 uid="some-event-id",
294 summary="Vacations",
295 start=datetime.datetime(2022, 8, 6, hour=8, minute=30),
296 end=datetime.datetime(2022, 8, 17, hour=12),
297 location="New-York, Statue de la Liberté",
298 geo=(40.69216097988203, -74.04460073403436),
299 categories=["PERSO", "holidays"],
300 status=EventStatus.CONFIRMED,
301 event_class=EventClass.PRIVATE,
302 transparency=EventTransparency.OPAQUE,
303 organizer="[email protected]",
304 url="https://bar.com",
305 description="""Fake description. Meeting to provide technical review for "Phoenix" design. Happy Face Conference Room.
306
307 Phoenix design team MUST attend this meeting.
308
309 RSVP to team leader."""
310 )
311
312 # Build context for rendering QR codes.
313 context = dict(
314 mecard_contact=mecard_contact,
315 vcard_contact=vcard_contact,
316 wifi_config=wifi_config,
317 epc_data=epc_data,
318 event=event,
319 video_id='J9go2nj6b3M',
320 google_maps_coordinates=google_maps_coordinates,
321 geolocation_coordinates=geolocation_coordinates,
322 options_example=QRCodeOptions(size='t', border=6, error_correction='L'),
323 )
324
325 # Render the index page.
326 return render(request, 'my_app/application_qr_code_demo.html', context=context)
327 ```
328
329 Then, in your template, you can render the appropriate QR codes for the given context:
330 ```htmldjango
331 <h3>Add contact '{{ mecard_contact.name }}' to phone book</h3>
332 {% qr_for_mecard mecard=mecard_contact size='S' %}
333 <p>or:</p>
334 {% qr_for_contact mecard_contact size='S' %}
335 <p>or:</p>
336 {% qr_for_contact mecard_contact options=options_example %}
337
338 <h3>Add contact '{{ vcard_contact.name }}' to phone book</h3>
339 {% qr_for_vcard vcard=vcard_contact size='S' %}
340 <p>or:</p>
341 {% qr_for_contact vcard_contact size='S' %}
342 <p>or:</p>
343 {% qr_for_contact vcard_contact options=options_example %}
344
345 <h3>Configure Wi-Fi connexion to '{{ wifi_config.ssid }}'</h3>
346 <img src="{% qr_url_for_wifi wifi_config=wifi_config size='T' error_correction='Q' %}">
347 <p>or:</p>
348 <img src="{% qr_url_for_wifi wifi_config size='T' error_correction='Q' %}">
349 <p>or:</p>
350 <img src="{% qr_url_for_wifi wifi_config options=options_example %}">
351
352 <h3>EPC QR Code'</h3>
353 <img src="{% qr_url_for_epc epc_data=epc_data %}">
354 <p>or:</p>
355 <img src="{% qr_url_for_epc epc_data size='H' %}">
356
357 <h3>Event QR Code'</h3>
358 <img src="{% qr_url_for_event event=event %}">
359 <p>or:</p>
360 {% qr_for_event event=event %}
361
362 <h3>Watch YouTube video '{{ video_id }}'</h3>
363 {% qr_for_youtube video_id image_format='png' size='T' %}
364 <p>or:</p>
365 {% qr_for_youtube video_id options=options_example %}
366
367 <h3>Open map at location: ({{ geolocation_coordinates }})</h3>
368 <img src="{% qr_url_for_geolocation coordinates=geolocation_coordinates %}">
369 <p>or:</p>
370 <img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude %}">
371 <p>or:</p>
372 <img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude options=options_example %}">
373
374 <h3>Open Google Maps App at location: ({{ google_maps_coordinates }})</h3>
375 {% qr_for_google_maps coordinates=google_maps_coordinates %}
376 <p>or:</p>
377 {% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude %}
378 <p>or:</p>
379 {% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude options=options_example %}
380 ```
381
382 Please check out the [demo application](README.md#demo-application) to see more examples.
383
384 ## QR code rendering options
385
386 ### Overview of customization options
387
388 * `size`: Size of each module (e.g., T, S, M, L, H or specific integer). Default is 'M'
389 * `image_format`: Format of the image (e.g., 'svg', 'png'). Default is 'svg'.
390 * `border`: Border size in modules. Default is 4.
391 * `error_correction`: Error correction level ('L', 'M', 'Q', 'H'). Default is 'M'.
392 * `use_data_uri_for_svg`: Generate a data URI for SVG images. Default is `False`.
393 * `encoding`: Text encoding . Default is 'UTF-8'.
394 * `micro`: enforce the creation of a Micro QR Code. Default is `False`.
395 * `boost_error` indicates whether the QR code encoding engine (Segno) tries to increase the error correction level if it does not affect the version. Default is `False`.
396 * `eci` indicates if binary data which does not use the default encoding (ISO/IEC 8859-1). Default is `False`.
397 * `options`: Use an instance of QRCodeOptions to encapsulate multiple settings.
398
399 ### Examples of rendering options
400
401 The `size` parameter gives the size of each module of the QR code matrix. It can be either a positive integer or one of the following letters:
402
403 * t or T: tiny (value: 6)
404 * s or S: small (value: 12)
405 * m or M: medium (value: 18)
406 * l or L: large (value: 30)
407 * h or H: huge (value: 48)
408
409 For PNG image format the size unit is in pixels, while the unit is 1 mm for SVG format.
410
411 Here is a "hello world" QR code using the version 12:
412
413 ```htmldjango
414 {% qr_from_text "Hello World!" size=8 version=12 %}
415 ```
416
417 The `version` parameter is an integer from 1 to 40 that controls the size of the QR code matrix. Set to None to determine this automatically. The smallest, version 1, is a 21 x 21 matrix. The biggest, version 40, is 177 x 177 matrix. The size grows by 4 modules/side.
418
419 Here is a "hello world" QR code using a border of 6 modules:
420
421 ```htmldjango
422 {% qr_from_text "Hello World!" size=10 border=6 %}
423 ```
424
425 The `border` parameter controls how many modules thick the border should be (the default is 4, which is the minimum according to the specs).
426
427 There are 4 error correction levels used for QR codes, with each one adding different amounts of "backup" data
428 depending on how much damage the QR code is expected to suffer in its intended environment, and hence how much
429 error correction may be required. The correction level can be configured with the `error_correction` parameter as follows:
430
431 * l or L: error correction level L – up to 7% damage
432 * m or M: error correction level M – up to 15% damage
433 * q or Q: error correction level Q – up to 25% damage
434 * h or H: error correction level H – up to 30% damage
435
436 You may enforce the creation of a Micro QR Code with `micro=True`. The `micro` option defaults to `False`.
437
438 The `encoding` option controls the text encoding used in mode "byte" (used for any general text content). By default `encoding` is ``UTF-8``. When set to ``None``, the implementation (based on Segno) tries to use the standard conform ISO/IEC 8859-1 encoding and if it does not fit, it will use UTF-8. Note that no ECI mode indicator is inserted by default (see `eci` option). The `encoding` parameter is case-insensitive.
439
440 The `boost_error` indicates whether the QR code encoding engine (Segno) tries to increase the error correction level if it does not affect the version. Error correction level is not increased when it impacts the version of the code.
441
442 The `eci` option indicates if binary data which does not use the default encoding (ISO/IEC 8859-1) should enforce the ECI mode. Since a lot of QR code readers do not support the ECI mode, this feature is disabled by default and the data is encoded in the provided encoding using the usual “byte” mode. Set eci to `True` if an ECI header should be inserted into the QR Code. Note that the implementation may not know the ECI designator for the provided encoding and may raise an exception if the ECI designator cannot be found. The ECI mode is not supported by Micro QR Codes.
443
444 Alternatively, you may use the `options` keyword argument with an instance of `QRCodeOptions` as value instead of listing every requested options. Here is an example of view:
445
446 ```python
447 from django.shortcuts import render
448 from qr_code.qrcode.utils import QRCodeOptions
449
450 def my_view(request):
451 # Build context for rendering QR codes.
452 context = dict(
453 my_options=QRCodeOptions(size='t', border=6, error_correction='L'),
454 )
455
456 # Render the view.
457 return render(request, 'my_app/my_view.html', context=context)
458 ```
459
460 and an example of template for the view above:
461
462 ```htmldjango
463 {% qr_from_text "Hello World!" options=my_options %}
464 ```
465
466 ## Notes
467
468 ### Image formats
469 The SVG is the default image format. It is a vector image format, so it can be scaled up and down without quality loss. However, it has two drawbacks. The size is not given in pixel, which can be problematic if the design of your website relies on a fixed width (in pixels). The format is less compact than PNG and results in a larger HTML content. Note that a base64 PNG is less compressible than a SVG tag, so it might not matter that much of you use HTML compression on your web server.
470
471 SVG has [broad support](http://caniuse.com/#feat=svg) now, and it will work properly on any modern web browser.
472
473 ### Embedded image tag VS URL for images
474 The tag `qr_url_from_text` has several advantages over `qr_from_text`, despite the fact that it requires a bit more of writing:
475 * the generated HTML code does not contain heavy inline image data (lighter and cleaner content)
476 * the generated images can be cached (served with a separate HTML request)
477 * the HTML tag used to render the QR code is always an `<img>` tag, which may simplify CSS handling.
478 * the HTML tag embedding the image is not generated for you, which allows for customization of attributes (*height*, *width*)
479 * the page can be loaded asynchronously, which improves responsiveness
480 * you can provide links to QR codes instead of displaying them, which is not possible with `qr_from_text`
481
482 One disadvantage of `qr_url_from_text` is that it increases the number of requests to the server: one request to serve the page containing the URL and another to request the image.
483
484 Be aware that serving image files (which are generated on the fly) from a URL can be abused and lead to (D)DoS attack pretty easily, for instance by requesting very large QR codes from outside your application. This is the reason why the associated setting `ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER` in `QR_CODE_URL_PROTECTION` defaults to completely forbid external access to the API. Be careful when opening external access.
485
486 ### QR codes caching
487 Caching QR codes reduces CPU usage, but the usage of `qr_url_from_text` (which caching depends on) increases the number of requests to the server (one request to serve the page containing the URL and another to request the image).
488
489 Moreover, be aware that the largest QR codes, in version 40 with a border of 4 modules and rendered in SVG format, have a size of ~800 KB.
490 Be sure that your cache options are reasonable and can be supported by your server(s), especially for in-memory caching.
491
492 Note that even without caching the generated QR codes, the app will return an *HTTP 304 Not Modified* status code whenever the same QR code is requested again. The URL named **`qr_code:serve_qr_code_image`** adds the `ETag` and `Last-Modified` headers to the response if the headers aren't already set, enabling *HTTP 304 Not Modified* response upon following requests.