Package: django-qr-code
Django QR CodeThis is an application that provides tools for displaying QR codes on yourDjangosite.This application depends on theSegno QR Code generatorlibrary.This app makes no usage of the Django models and therefore do not use any database.Only Python >= 3.8 is supported.InstallationBinary Package from PyPiIn order to use this app in a Django project, the simplest way is to install it fromPyPi:pipinstalldjango-qr-codeFrom the Source CodeIn order to modify or test this app you may want to install it from the source code.Clone theGitHub repositoryand then run:pipinstall-rrequirements.txt-rrequirements-dev.txt
pythonmanage.pycollectstatic--no-inputUsageStart by addingqr_codeto yourINSTALLED_APPSsetting like this:INSTALLED_APPS=(# ...,'qr_code',)You need to load the tags provided by this app in your template with:{% load qr_code %}The source code onGitHubcontains a simple demo app. Please check out thetemplates folderfor an example of template, and thesettingandurlsfiles for an example of configuration and integration.Generating Inline QR Code in your HTML (qr_from_text)The tagqr_from_textgenerates an embeddedsvgorimgtag within the HTML code produced by your template.The following renders a tiny "hello world" QR code with asvgtag:{% qr_from_text "Hello World!" size="T" %}Here is a medium "hello world" QR code with animgtag:{% qr_from_text "Hello World!" size="m" image_format="png" error_correction="L" %}QR Code Rendering OptionsThesizeparameter gives the size of each module of the QR code matrix. It can be either a positive integer or one of the following letters:t or T: tiny (value: 6)s or S: small (value: 12)m or M: medium (value: 18)l or L: large (value: 30)h or H: huge (value: 48)For PNG image format the size unit is in pixels, while the unit is 1 mm for SVG format.Here is a "hello world" QR code using the version 12:{% qr_from_text "Hello World!" size=8 version=12 %}Theversionparameter 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.Here is a "hello world" QR code using a border of 6 modules:{% qr_from_text "Hello World!" size=10 border=6 %}Theborderparameter controls how many modules thick the border should be (the default is 4, which is the minimum according to the specs).There are 4 error correction levels used for QR codes, with each one adding different amounts of "backup" data
depending on how much damage the QR code is expected to suffer in its intended environment, and hence how much
error correction may be required. The correction level can be configured with theerror_correctionparameter as follows:l or L: error correction level L – up to 7% damagem or M: error correction level M – up to 15% damageq or Q: error correction level Q – up to 25% damageh or H: error correction level H – up to 30% damageYou may enforce the creation of a Micro QR Code withmicro=True. Themicrooption defaults toFalse.Theencodingoption controls the text encoding used in mode "byte" (used for any general text content). By defaultencodingisUTF-8. When set toNone, 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 (seeecioption). Theencodingparameter is case-insensitive.Theboost_errorindicates 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.Theecioption 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 toTrueif 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.Alternatively, you may use theoptionskeyword argument with an instance ofQRCodeOptionsas value instead of listing every requested options. Here is an example of view:fromdjango.shortcutsimportrenderfromqr_code.qrcode.utilsimportQRCodeOptionsdefmy_view(request):# Build context for rendering QR codes.context=dict(my_options=QRCodeOptions(size='t',border=6,error_correction='L'),)# Render the view.returnrender(request,'my_app/my_view.html',context=context)and an example of template for the view above:{% qr_from_text "Hello World!" options=my_options %}Generating URLs to QR Code Images (qr_url_from_text)Theqr_url_from_texttag generates an url to an image representing the QR code. It comes with the same options asqr_from_textto customize the image format (SVG or PNG), the size, the border, and the matrix size. It also has an additional optioncache_enabledto disable caching of served image.Here is a medium "hello world" QR code that uses an URL to serve the image in SVG format:<img src="{% qr_url_from_text "Hello World!" %}" alt="Hello World!">Here is a "hello world" QR code in version 10 that uses an URL to serve the image in PNG format:<img src="{% qr_url_from_text "Hello World!" size=8 version=10 image_format='png' %}" alt="Hello World!">The image targeted by the generated URL is served by a view provided inqr_code.urls. Therefore, you need to include the URLs provided byqr_code.urlsin your app in order to make this tag work. This can be achieved with something like this:fromdjango.conf.urlsimportincludefromdjango.urlsimportpathurlpatterns=[path('qr_code/',include('qr_code.urls',namespace="qr_code")),]The QR code images are served via a URL namedqr_code:serve_qr_code_image. You can customize the path under which the images are served (i.e. the path bound to the URL namedqr_code:serve_qr_code_image) with the optional settingSERVE_QR_CODE_IMAGE_PATHwhich defaults toimages/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/:# In urls.pyfromdjango.conf.urlsimportincludefromdjango.urlsimportpathurlpatterns=[path('',include('qr_code.urls',namespace='qr_code')),]# In your settingsSERVE_QR_CODE_IMAGE_PATH='qr-code-image/'Generating Image Object Representing a QR CodeIf you do not want to use Django tags for rendering QR code in a template, you can simply use the API in your code. For instance,qr_code.qrcode.maker.make_qr_code_imagewill return bytes representing an image according to the image_format passed in theqr_code_optionsparameter.Special encoding modes with qr_from_data and qr_url_from_dataThe tagsqr_from_dataandqr_url_from_dataproduce results similar to those ofqr_from_textandqr_url_from_text, but they avoid converting everything to text (UTF-8 encoded by default, or any supported charset depending onencodingoption).The ISO/IEC 18004 standard defines four modes in order to encode the data as efficiently as possible.Numeric modeThe 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).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) toqr_from_dataorqr_url_from_data.Alphanumeric modeThe alphanumeric mode extends the numeric mode by various characters. Namely, about the upper case letters ABCDEFGHIJKLMNOPQRSTUVWXYZ, a space character " " and other letters $%*+-./:.Kanji modeKanji can be encoded compactly and efficiently and requires significantly less space than encoding the characters in UTF-8.Byte modeThe byte mode covers all data which cannot be represented by the other modes. When theencodingoption is set toNone, 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.NOTE: When usingqr_from_textorqr_url_from_text, the byte mode with UTF-8 encoding is forced by default . You may use theencodingoption to change this behavior. It appears to be one of the most portable way of encoding text for proper decoding among the readers.ExamplesThe following renders a tiny numeric QR code containing the value2021with asvgtag:{% qr_from_data 2021 size="T" %}Here is a micro QR code with animgtag containing the value2021:{% qr_from_data 2021 micro=True image_format="png" %}Caching Served ImagesA 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.The image served by theqr_codeapp 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 settingQR_CODE_CACHE_ALIASto indicate in which cache to store the generated QR codes.For instance, you may declare an additional cache for your QR codes like this in your Django settings:CACHES={'default':{'BACKEND':'django.core.cache.backends.locmem.LocMemCache',},'qr-code':{'BACKEND':'django.core.cache.backends.locmem.LocMemCache','LOCATION':'qr-code-cache','TIMEOUT':3600}}QR_CODE_CACHE_ALIAS='qr-code'TheQR_CODE_CACHE_ALIAS = 'qr-code'tells theqr_codeapp to use that cache for storing the generated QR codes. All QR codes will be cached with the specifiedTIMEOUTwhen a non-empty value is set toQR_CODE_CACHE_ALIAS.If you want to activate the cache for QR codes, but skip the caching for some specific codes, you can use the keyword argumentcache_enabled=Falsewhen usingqr_url_from_text.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:<img src="{% qr_url_from_text "Hello World!" size=8 version=20 error_correction="Q" cache_enabled=False %}" alt="Hello World!">Protecting Access to QR Code ImagesThe default settings protect the URLs that serve QR code images against external requests, and thus against possibly easy (D)DoS attacks.Here are the available settings to manage the protection for served images:fromqr_code.qrcodeimportconstantsQR_CODE_URL_PROTECTION={constants.TOKEN_LENGTH:30,# Optional random token length for URL protection. Defaults to 20.constants.SIGNING_KEY:'my-secret-signing-key',# Optional signing key for URL token. Uses SECRET_KEY if not defined.constants.SIGNING_SALT:'my-signing-salt',# Optional signing salt for URL token.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).}Signing Request URLsBy 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 namedtokenwhich is automatically generated byqr_url_from_textorqr_url_from_data. Whenever the signature is invalid, the application returns aHTTP 403 Permission deniedresponse when processing the request for serving a QR code image.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).Thetokenquery argument is not mandatory and, when a request reaches theqr_code:serve_qr_code_imageURL without that token, the protection mechanism falls back to the user authentication mechanism (see chapter below).It is possible to explicitly remove the  signature token that protects a specific URL with the parameterurl_signature_enabled=False. Here is a "hello world" QR code that uses a URL to serve the image in SVG format without thetokenquery argument :<img src="{% qr_url_from_text "Hello World!" url_signature_enabled=False %}" alt="Hello World!">Thetokenparameter 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).Handling User Authentication when Serving QR Code ImagesIf you are interested in providing the QR code images as a service, there is a setting namedALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USERto 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.Setting theALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USERoption toTruetells 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:fromqr_code.qrcodeimportconstantsQR_CODE_URL_PROTECTION={constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER:True}Setting the optionALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USERto a callable that always returnsTrue(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:fromqr_code.qrcodeimportconstantsQR_CODE_URL_PROTECTION={constants.ALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USER:lambdau:True}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.QR Codes for AppsAside 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.  Seethis documentationabout what a QR code can encode.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.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.The following tags targeting apps are available:qr_for_emailandqr_url_for_emailqr_for_telandqr_url_for_telqr_for_smsandqr_url_for_smsqr_for_geolocationandqr_url_for_geolocationqr_for_google_mapsandqr_url_for_google_mapsqr_for_youtubeandqr_url_for_youtubeqr_for_google_playandqr_url_for_google_playqr_for_mecardandqr_url_for_mecardqr_for_vcardandqr_url_for_vcardqr_for_wifiandqr_url_for_wifiqr_for_epcandqr_url_for_epcqr_for_eventandqr_url_for_eventqr_for_contactandqr_url_for_contact(legacy, do not use in new projects)You could write a view like this:importdatetimefromdatetimeimportdatefromdjango.shortcutsimportrenderfromqr_code.qrcode.utilsimportMeCard,VCard,EpcData,VEvent,EventClass,EventTransparency,EventStatus,WifiConfig,Coordinates,QRCodeOptionsdefapplication_qr_code_demo(request):# Use a MeCard instance to encapsulate the detail of the contact.mecard_contact=MeCard(name='Doe, John',phone='+41769998877',email='j.doe@company.com',url='http://www.company.com',birthday=date(year=1985,month=10,day=2),memo='Development Manager',org='Company Ltd')# Use a VCard instance to encapsulate the detail of the contact.vcard_contact=VCard(name='Doe; John',phone='+41769998877',email='j.doe@company.com',url='http://www.company.com',birthday=date(year=1985,month=10,day=2),street='Cras des Fourches 987',city='Delémont',zipcode=2800,region='Jura',country='Switzerland',memo='Development Manager',org='Company Ltd')# Use a WifiConfig instance to encapsulate the configuration of the connexion.wifi_config=WifiConfig(ssid='my-wifi',authentication=WifiConfig.AUTHENTICATION.WPA,password='wifi-password')# Use a EpcData instance to encapsulate the data of the European Payments Council Quick Response Code.epc_data=EpcData(name='Wikimedia Foerdergesellschaft',iban='DE33100205000001194700',amount=50.0,text='To Wikipedia')# Build coordinates instances.google_maps_coordinates=Coordinates(latitude=586000.32,longitude=250954.19)geolocation_coordinates=Coordinates(latitude=586000.32,longitude=250954.19,altitude=500)# Build event data (VEVENT properties)# NB for start and end of event:#   - Naive date and time is rendered as floating time.#   - Aware date and time is rendered as UTC converted time.event=VEvent(uid="some-event-id",summary="Vacations",start=datetime.datetime(2022,8,6,hour=8,minute=30),end=datetime.datetime(2022,8,17,hour=12),location="New-York, Statue de la Liberté",geo=(40.69216097988203,-74.04460073403436),categories=["PERSO","holidays"],status=EventStatus.CONFIRMED,event_class=EventClass.PRIVATE,transparency=EventTransparency.OPAQUE,organizer="foo@bar.com",url="https://bar.com",description="""Fake description. Meeting to provide technical review for "Phoenix" design. Happy Face Conference Room.Phoenix design team MUST attend this meeting.RSVP to team leader.""")# Build context for rendering QR codes.context=dict(mecard_contact=mecard_contact,vcard_contact=vcard_contact,wifi_config=wifi_config,epc_data=epc_data,event=event,video_id='J9go2nj6b3M',google_maps_coordinates=google_maps_coordinates,geolocation_coordinates=geolocation_coordinates,options_example=QRCodeOptions(size='t',border=6,error_correction='L'),)# Render the index page.returnrender(request,'my_app/application_qr_code_demo.html',context=context)Then, in your template, you can render the appropriate QR codes for the given context:<h3>Add contact '{{ mecard_contact.name }}' to phone book</h3>
{% qr_for_mecard mecard=mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact size='S' %}
<p>or:</p>
{% qr_for_contact mecard_contact options=options_example %}

<h3>Add contact '{{ vcard_contact.name }}' to phone book</h3>
{% qr_for_vcard vcard=vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact size='S' %}
<p>or:</p>
{% qr_for_contact vcard_contact options=options_example %}

<h3>Configure Wi-Fi connexion to '{{ wifi_config.ssid }}'</h3>
<img src="{% qr_url_for_wifi wifi_config=wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config size='T' error_correction='Q' %}">
<p>or:</p>
<img src="{% qr_url_for_wifi wifi_config options=options_example %}">

<h3>EPC QR Code'</h3>
<img src="{% qr_url_for_epc epc_data=epc_data %}">
<p>or:</p>
<img src="{% qr_url_for_epc epc_data size='H' %}">

<h3>Event QR Code'</h3>
<img src="{% qr_url_for_event event=event %}">
<p>or:</p>
{% qr_for_event event=event %}

<h3>Watch YouTube video '{{ video_id }}'</h3>
{% qr_for_youtube video_id image_format='png' size='T' %}
<p>or:</p>
{% qr_for_youtube video_id options=options_example %}

<h3>Open map at location: ({{ geolocation_coordinates }})</h3>
<img src="{% qr_url_for_geolocation coordinates=geolocation_coordinates %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude %}">
<p>or:</p>
<img src="{% qr_url_for_geolocation latitude=geolocation_coordinates.latitude longitude=geolocation_coordinates.longitude altitude=geolocation_coordinates.altitude options=options_example %}">

<h3>Open Google Maps App at location: ({{ google_maps_coordinates }})</h3>
{% qr_for_google_maps coordinates=google_maps_coordinates %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude %}
<p>or:</p>
{% qr_for_google_maps latitude=google_maps_coordinates.latitude longitude=google_maps_coordinates.longitude options=options_example %}Please check out thedemo applicationto see more examples.NotesImage FormatsThe 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.SVG hasbroad supportnow, and it will work properly on any modern web browser.qr_from_text vs qr_url_from_textThe tagqr_url_from_texthas several advantages overqr_from_text, despite the fact that it requires a bit more of writing:the generated HTML code does not contain heavy inline image data (lighter and cleaner content)the generated images can be cached (served with a separate HTML request)the HTML tag used to render the QR code is always an<img>tag, which may simplify CSS handlingthe HTML tag embedding the image is not generated for you, which allows for customization of attributes (height,width,alt)the page can be loaded asynchronously, which improves responsivenessyou can provide links to QR codes instead of displaying them, which is not possible withqr_from_textOne disadvantage ofqr_url_from_textis 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.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 settingALLOWS_EXTERNAL_REQUESTS_FOR_REGISTERED_USERinQR_CODE_URL_PROTECTIONdefaults to completely forbid external access to the API. Be careful when opening external access.QR Codes CachingCaching QR codes reduces CPU usage, but the usage ofqr_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).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.
Be sure that your cache options are reasonable and can be supported by your server(s), especially for in-memory caching.Note that even without caching the generated QR codes, the app will return aHTTP 304 Not Modifiedstatus code whenever the same QR code is requested again. The URL namedqr_code:serve_qr_code_imageadds theETagandLast-Modifiedheaders to the response if the headers aren't already set, enablingHTTP 304 Not Modifiedresponse upon following requests.Demo ApplicationIf you want to try this app, you may want to use the demo application shipped alongside the source code.Get the source code fromGitHub, follow theinstallation instructionsabove, and run therunservercommand of Django:pythonmanage.pyrunserverThe demo application should be running athttp://127.0.0.1:8000/qr-code-demo/.If you haveDocker Composeinstalled, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):cdscripts
./run-demo-app.shThe demo application should be running athttp://127.0.0.1:8910/qr-code-demo/.TestingGet the source code fromGitHub, follow theinstallation instructionsabove, and run thetestcommand of Django:pythonmanage.pytestThis will run the test suite with the locally installed version of Python and Django.If you haveDocker Composeinstalled, you can simply run the following from a terminal (this will save you the burden of setting up a proper python environment):cdscripts
./run-tests.shThis will run the test suite with all supported versions of Python and Django. The test results are stored withintests_resultfolder.Projects Using this AppThis app is used in the following projects:MyGym Web: a web platform for managing sports clubs. The QR codes are used for importing members' contact information in a phone book.Gymna-Score: a web platform for entering scores during gymnastics competitions organized by the Association Cantonale Jurassienne de Gymnastique (ACJG). The QR codes are used to provide an easy way for the public to follow an ongoing competition. They are also used to authenticate judges that need to enter scores.AC-Ju: a website that generates digital vouchers that can be redeemed at affiliate merchants.