### write directive example Source: https://www.jsolly.com/blog/mastering-gpt-directives-and-parameters/ Example prompt using the write directive to tell GPT to write something, with the reply 'Apple'. ```text [write: a noun] ``` ```text Apple ``` -------------------------------- ### Install with constraints flag Source: https://www.jsolly.com/blog/Achieve-consistent-builds-with-Python-constraints/ Command to install packages from requirements.txt while applying version constraints from constraints.txt. ```python python3 -m pip install -r requirements.txt -c constraints.txt ``` -------------------------------- ### GitHub Actions Workflow with Integrated CodeQL Analysis Source: https://www.jsolly.com/blog/code-analysis-and-pip-dependency-check-in-GitHub/ A unified GitHub Actions workflow configuration that runs tests and CodeQL analysis for Python and JavaScript projects. It includes environment variable setup, dependency installation, linting, test coverage, and the CodeQL initialization and analysis steps. ```yaml name: Blogthedata Tests on: push: pull_request: branches: - main schedule: - cron: '0 3 * * 0-6' jobs: build: runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'javascript', 'python' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support env: DJANGO_SETTINGS_MODULE: ${{secrets.DJANGO_SETTINGS_MODULE}} SECRET_KEY: ${{secrets.SECRET_KEY}} EMAIL_HOST_USER: ${{secrets.EMAIL_HOST_USER}} EMAIL_HOST_PASSWORD: ${{secrets.EMAIL_HOST_PASSWORD}} FROM_EMAIL: ${{secrets.FROM_EMAIL}} ALLOWED_HOSTS: ${{secrets.ALLOWED_HOSTS}} POSTGRES_PASS: $${{secrets.POSTGRES_PASS}} GIT_TOKEN: ${{secrets.GIT_TOKEN}} DEBUG: ${{secrets.DEBUG}} MODE: ${{secrets.MODE}} steps: - uses: actions/checkout@v2 - name: Setup Python 3.9.7 uses: actions/setup-python@v2 with: python-version: 3.9.7 - name: Install dependencies run: | pip install --upgrade pip pip install wheel pip install -r django_project/requirements/requirements.txt - name: Lint with Flake8 run: | flake8 django_project - name: Coverage report run: | coverage run -m unittest discover django_project coverage report -m --skip-empty --skip-covered - name: Run unit tests run: | python3 -m unittest discover django_project # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs # queries: security-extended,security-and-quality # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) #- name: Autobuild # uses: github/codeql-action/autobuild@v2 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # If the Autobuild fails above, remove it and uncomment the following three lines. # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # - run: | # echo "Run, Build Application using script" # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 ``` -------------------------------- ### Python Hello World example Source: https://www.jsolly.com/blog/Adding-code-snippets-ckeditor/ A simple Python code snippet that prints 'Hello World'. Used to demonstrate the code snippet formatting feature in CKEditor. ```python print("Hello World") ``` -------------------------------- ### Install TypeScript globally with npm Source: https://www.jsolly.com/blog/TypeScript-revealed-210-issues-JavaScript-codebase/ Run this command to install TypeScript globally using npm. This is the first step in adding TypeScript to a JavaScript project. ```bash sudo npm install -g typescript ``` -------------------------------- ### analyze directive example Source: https://www.jsolly.com/blog/mastering-gpt-directives-and-parameters/ Example prompt using the analyze directive to examine the structure of a text, with the reply 'jump'. ```text [analyze: "The quick brown fox jumped over the lazy dog"][write:verbs] ``` ```text jump ``` -------------------------------- ### Initial Migration File Structure Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ The starting point for the migration file migrations/0018_transfer_categories.py. ```python # migrations/0018_transfer_categories.py from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("blog", "0017_add_temp_category_link_field"), ] operations = [ ] ``` -------------------------------- ### Run Django deployment check Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Execute this command to identify necessary security configurations before deploying to production. ```bash manage.py check --deploy ``` -------------------------------- ### cross-reference directive example Source: https://www.jsolly.com/blog/mastering-gpt-directives-and-parameters/ Example prompt using the cross-reference directive to compare input text to something else, with a detailed reply referencing a biblical passage. ```text [metaphorical analysis:"I dreamt I was being chased by a lion and a lamb saved me"][cross-reference: The Holy Bible] ``` ```text In the context of this dream, the lion represents danger or threat while the lamb represents innocence or purity. The metaphor could potentially be referencing the biblical passage in Isaiah 11:6, which states "The wolf will live with the lamb, the leopard will lie down with the goat, the calf and the lion and the yearling together; and a little child will lead them." This passage speaks of a time of peace and harmony, where even the most ferocious of animals will lay down their aggression. In the dream, the lamb symbolizes this peaceful resolution, rescuing the dreamer from the danger represented by the lion. This could be interpreted as a metaphor for the power of innocence and goodness to overcome even the most formidable challenges. ``` -------------------------------- ### Execute the WebP conversion script Source: https://www.jsolly.com/blog/convert-images-to-webp-25-percent-smaller-payloads/ Run this command in the terminal after placing the conversion script in your target directory. ```bash $ bash webp-convert-directory ``` -------------------------------- ### Test Post Detail View Returns 200 and Uses Correct Template Source: https://www.jsolly.com/blog/how-to-get-100-percent-unit-test-coverage/ Checks that a GET request to the post detail URL returns a 200 OK response and uses the 'blog/post_detail.html' template. ```python def test_post_detail_view(self): response = self.client.get(self.post1_detail_url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'blog/post_detail.html') ``` -------------------------------- ### Initialize Leaflet Map Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Create the map instance with a center point and zoom level. ```javascript // leaflet_map.js var map = L.map('map', { center: [39, -98], zoom: 4, }); ``` -------------------------------- ### Configure Custom Marker Icon Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Create a custom icon configuration for a marker. ```javascript var IPAddressIcon = L.icon({ iconUrl: "static/icons/ip-address.png", iconSize: [40, 40] }); var DallasMarkerOptions = { title: "Blogthedata.com Server", alt: "The city of Dallas, Texas. USA", icon: IPAddressIcon } ``` -------------------------------- ### Update urls.py for slugified URLs Source: https://www.jsolly.com/blog/adding-slugified-urls/ Example of the changes required in the urls.py file to support slug-based routing. ```python path('post//', PostDetailView.as_view(), name='post-detail'), ``` -------------------------------- ### disable directive example Source: https://www.jsolly.com/blog/mastering-gpt-directives-and-parameters/ Example prompt using the disable directive to turn off GPT features, specifically 'Pretext' and 'Context'. ```text [disable: "Pretext" AND "Context"] ``` -------------------------------- ### Define ALLOWED_HOSTS for local development Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Include localhost and ngrok addresses for local testing and mobile development. ```json {"ALLOWED_HOSTS": [ "127.0.0.1", ".ngrok.io", "localhost"]} ``` -------------------------------- ### Example requirements.txt generated by pip freeze Source: https://www.jsolly.com/blog/why-I-stopped-using-pip-freeze/ A sample requirements.txt showing the output of pip freeze, including many transitive dependencies. This illustrates the problem of unclear project requirements. ```python # requirements.txt asgiref==3.5.1 async-generator==1.10 attrs==21.4.0 beautifulsoup4==4.9.3 black==22.3.0 certifi==2020.12.5 cffi==1.15.0 chardet==4.0.0 charset-normalizer==2.0.12 chromedriver-autoinstaller==0.3.1 click==8.1.3 coverage==6.3.2 cryptography==37.0.2 Django==3.2.13 django-admin-honeypot==1.1.0 django-ckeditor==6.4.1 django-coverage-plugin==2.0.2 django-csp==3.7 django-fastdev==1.7.2 django-js-asset==2.0.0 django-ranged-response==0.2.0 django-robots==5.0 django-simple-captcha==0.5.14 django-sri==0.3.0 filetype==1.0.10 flake8==3.9.2 geckodriver-autoinstaller==0.1.0 h11==0.13.0 idna==2.10 mccabe==0.6.1 mypy-extensions==0.4.3 outcome==1.1.0 pathspec==0.9.0 Pillow==8.3.2 platformdirs==2.5.2 psycopg2==2.9.3 pycodestyle==2.7.0 pycparser==2.21 pyflakes==2.3.1 pyOpenSSL==22.0.0 PySocks==1.7.1 python-dotenv==0.20.0 pytz==2022.1 requests==2.25.1 selenium==4.1.3 six==1.16.0 sniffio==1.2.0 sortedcontainers==2.4.0 soupsieve==2.1 sqlparse==0.4.2 tomli==2.0.1 trio==0.20.0 trio-websocket==0.9.2 typing_extensions==4.2.0 urllib3==1.26.3 wsproto==1.1.0 ``` -------------------------------- ### Add Tile Layer Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Add an OpenStreetMap tile layer to the map. ```javascript L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 20, attribution: '© OpenStreetMap contributors' }).addTo(map); ``` -------------------------------- ### Display category post count in template Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ Example of injecting a category post count into a sidebar template. ```html # templates/sidebar.html { category.posts_count }} ``` -------------------------------- ### Example conventional commit with body and footer Source: https://www.jsolly.com/blog/conventional-commits/ A concrete example of a conventional commit message that includes a fix type, a body explaining the change, a BREAKING CHANGE footer, and a reference to a task ID. ```plaintext fix: fix foo to enable bar This fixes the broken behavior of the component by doing xyz. BREAKING CHANGE Before this fix foo wasn't enabled at all, behavior changes from to Closes D2IQ-12345 ``` -------------------------------- ### Pure Tailwind Utility Classes for Hover/Focus Source: https://www.jsolly.com/blog/three-scenarios-i-dont-use-tailwind/ An example of implementing hover and focus states using only Tailwind utility classes, resulting in a long list of classes on a single element. ```html ``` -------------------------------- ### Configure UFW Firewall Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Install and configure the UFW firewall to allow only SSH and HTTP traffic while denying all other incoming connections. ```bash sudo apt-get install ufw -y sudo ufw default allow outgoing sudo ufw default deny incoming sudo ufw allow ssh sudo ufw allow http/tcp sudo ufw enable # put all the previous rules into effect ``` -------------------------------- ### Pseudo-elements using pure Tailwind utility classes Source: https://www.jsolly.com/blog/three-scenarios-i-dont-use-tailwind/ An example of styling a testimonial quote using only Tailwind utility classes, resulting in a high density of classes on a single element. ```html

{item.quote}

``` -------------------------------- ### Define ALLOWED_HOSTS for production Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Restrict the application to specific IP addresses and domains for production environments. ```json "ALLOWED_HOSTS": ["69.164.205.120", "www.blogthedata.com", "blogthedata.com"], ``` -------------------------------- ### Django StaticSitemap implementation Source: https://www.jsolly.com/blog/help-google-spider-with-sitemaps-and-robots-file/ A Django Sitemap class for static pages, defining monthly change frequency and priority. It explicitly defines the location using the reverse function. ```python class StaticSitemap(Sitemap): changefreq = "monthly" priority = 0.5 def items(self): return ['blog-about'] def location(self, item): return reverse(item) ``` -------------------------------- ### Upgrade Django in dev environment Source: https://www.jsolly.com/blog/upgrading-to-the-latest-3x-django/ Command to install a specific Django version (3.2.13) in the development environment. ```bash pip install Django==3.2.13 ``` -------------------------------- ### Get Client IP Address Source: https://www.jsolly.com/blog/Adding-views-likes-to-posts/ A helper function to extract the client's IP address from the request metadata, checking for forwarded headers first. ```python def get_client_ip(request): x_forward_for = request.META.get("HTTP_X_FORWARD_FOR") if x_forward_for: ip = x_forward_for.split(",")[0] else: ip = request.META.get("REMOTE_ADDR") return ip ``` -------------------------------- ### Add Scalebar Control Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Add a scale control to the map instance. ```javascript L.control.scale({ imperial: true, metric: true }).addTo(map); ``` -------------------------------- ### Synchronous REST calls with requests Source: https://www.jsolly.com/blog/I-made-my-code-async-its-388-percent-faster/ Makes three synchronous GET requests using the requests library. Each request blocks until the response is received, so total time is the sum of all request times. ```Python import requests def make_request(url): return requests.request(method="GET, url=url) URLS = [url1, url2, url3] response1, response2, response3 = map(url, make_request) ``` -------------------------------- ### Asynchronous REST calls with aiohttp and asyncio Source: https://www.jsolly.com/blog/I-made-my-code-async-its-388-percent-faster/ Makes three asynchronous GET requests using aiohttp and asyncio. Requests are added to a task list and gathered with asyncio.gather, allowing responses to be collected as they arrive. The magic happens on lines 10-12 where tasks are created and awaited. ```Python import aiohttp import asyncio async def make_request(session, url): async with session.get(url) as resp: return await resp.json() async def main(urls): async with aiohttp.ClientSession() as session: tasks = [] for url in urls: tasks.append(asyncio.ensure_future(make_request(session, url))) return await asyncio.gather(*tasks) urls = [url1, url2, url3] response1, response2, response3 = asyncio.run(main(urls)) ``` -------------------------------- ### Define Marker Coordinates Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Define latitude and longitude objects for map markers. ```javascript var LaLatLng = { lat: 34.1, lon: -118.2 } var DallasLatLng = { lat: 32.8, lon: -96.8 } var NYCLatLng = { lat: 40.7, lon: -73.9 } ``` -------------------------------- ### Bash script for recursive WebP image conversion Source: https://www.jsolly.com/blog/convert-images-to-webp-25-percent-smaller-payloads/ This script traverses the current directory and subdirectories to convert images to .webp format using cwebp. It accepts optional parameters to override default compression settings. ```bash #!/bin/bash PARAMS=('-m 6 -q 70 -mt -af -progress') if [ $# -ne 0 ]; then PARAMS=$@; fi shopt -s nullglob nocaseglob extglob for FILE in $PWD/**/*.@(jpg|jpeg|tif|tiff|png); do cwebp $PARAMS "$FILE" -o "${FILE%.*}".webp; done ``` -------------------------------- ### Check HTTP Headers with cURL Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Use cURL to inspect the HTTP headers returned by a web server. ```bash $ curl -I https://blogthedata.com HTTP/1.1 200 OK Date: Tue, 03 May 2022 23:15:38 GMT Server: Apache/2.4.53 (Ubuntu) Content-Length: 13817 X-Frame-Options: DENY Vary: Cookie,Accept-Encoding Strict-Transport-Security: max-age=300; includeSubDomains; preload X-Content-Type-Options: nosniff Referrer-Policy: same-origin Set-Cookie: csrftoken=BL1ILPOtPNUVAITVL00Wnne6ZVVhzE8sJvhu8cnVW9YWAaIB7jqLgeoo6Y3ELDO6; expires=Tue, 02 May 2023 23:15:38 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### GitHub Actions Workflow Configuration Source: https://www.jsolly.com/blog/implement-continuous-integration-github-actions/ A YAML configuration file for GitHub Actions that triggers on push or pull requests, sets up a Python environment, installs dependencies, and runs linting and tests. ```yaml name: Blogthedata Tests on: push: pull_request: branches: - main jobs: build: runs-on: ubuntu-latest env: SECRET_KEY: ${{secrets.SECRET_KEY}} steps: - uses: actions/checkout@v2 - name: Setup Python 3.9.7 uses: actions/setup-python@v2 with: python-version: 3.9.7 - name: Install dependencies run: | pip install --upgrade pip pip install wheel pip install -r config/requirements.txt - name: Lint with Flake8 run: | flake8 django_project - name: Coverage + run unit tests run: | coverage run -m pytest django_project coverage report -m --skip-empty --skip-covered ``` -------------------------------- ### Generate requirements.txt with pip freeze Source: https://www.jsolly.com/blog/why-I-stopped-using-pip-freeze/ Command to output all installed packages and their versions to requirements.txt. This includes transitive dependencies, which can clutter the file. ```bash $ pip freeze > requirements.txt ``` -------------------------------- ### Style Map Container Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Set the dimensions for the map container in your CSS file. ```css // main.css #map{ height: 40vh; width : 100%; } ``` -------------------------------- ### Calculate Distance Between Points Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Calculate the distance between two points in kilometers. ```javascript var DallasToNYCDistance = (Math.floor(map.distance(DallasLatLng, NYCLatLng) / 1000)).toString() ``` -------------------------------- ### Add Text Label to Polyline Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Add a text label to the polyline and add it to the map. ```javascript DallasToNYC.setText(DallasToNYCDistance.concat(' km'), { center: true, offset: -5, attributes: { 'font-size': '24', 'font-weight': 'bold', fill: 'orange' } }) DallasToNYC.addTo(map) ``` -------------------------------- ### Load SECRET_KEY from JSON configuration Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Read sensitive configuration values from an external JSON file in settings.py to avoid committing secrets to source control. ```python import json with open("/etc/django_config.json", encoding="utf-8") as config_file: config = json.load(config_file) SECRET_KEY = config.get("SECRET_KEY") ``` -------------------------------- ### Add SRI to script tag Source: https://www.jsolly.com/blog/how-to-implement-subresource-integrity-django/ Example of a script tag with an integrity hash and crossorigin attribute. ```html ``` -------------------------------- ### Django PostSitemap implementation Source: https://www.jsolly.com/blog/help-google-spider-with-sitemaps-and-robots-file/ A Django Sitemap class for blog posts, defining weekly change frequency and priority. It uses the default get_absolute_url method for location. ```python class PostSitemap(Sitemap): changefreq = "weekly" priority = 0.9 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.date_posted #def location() Django uses get_absolute_url() by default, so no need to define the location ``` -------------------------------- ### Configure CSP directives in settings.py Source: https://www.jsolly.com/blog/how-to-implement-content-security-policy-django/ Add these CSP directives to your Django settings.py file to define allowed content sources and security policies for your application. ```python # settings.py # Content Security Policy CSP_DEFAULT_SRC = ("'none'",) CSP_STYLE_SRC = ("'self'", "https://cdn.jsdelivr.net", "'unsafe-inline'") CSP_SCRIPT_SRC = ( "'self'", "https://cdn.jsdelivr.net", ) CSP_IMG_SRC = ("'self'", "data:") CSP_FONT_SRC = ("'self'",) CSP_CONNECT_SRC = ("'self'",) CSP_FRAME_SRC = ("*",) CSP_FRAME_ANCESTORS = ("'none'",) CSP_BASE_URI = ("'none'",) CSP_FORM_ACTION = ("'self'", "https://blogthedata.us14.list-manage.com") CSP_OBJECT_SRC = ("'none'",) ``` -------------------------------- ### urls.py: Set handler404 to custom view Source: https://www.jsolly.com/blog/how-to-add-a-404-page-to-your-django-app/ Add the handler404 setting in urls.py to point to the custom handler_404 view in django_project.views. ```python # urls.py handler404 = "django_project.views.handler_404" ``` -------------------------------- ### Inject Map Container in Django Template Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Define the map div and inject the JavaScript file that initializes the map. ```html // site_analytics.html
{% sri_static 'maps/leaflet_server_map.js' %} ``` -------------------------------- ### Configure conditional security settings Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Apply strict security settings by default and conditionally loosen them when DEBUG mode is enabled. ```python # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False CAPTCHA_TEST_MODE = False # HTTPS SETTINGS SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS SETTINGS SECURE_HSTS_SECONDS = 31557600 # One year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True if config['DEBUG'] == 'True': DEBUG = True CAPTCHA_TEST_MODE = True # HTTPS SETTINGS SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False SECURE_SSL_REDIRECT = False # HSTS SETTINGS SECURE_HSTS_PRELOAD = False SECURE_HSTS_INCLUDE_SUBDOMAINS = False ``` -------------------------------- ### Test Comment Model Creation and Methods Source: https://www.jsolly.com/blog/how-to-get-100-percent-unit-test-coverage/ Tests that a Comment object can be created with a post and author, that the __str__ override returns the comment content, and that get_absolute_url returns the post detail URL. ```python def test_comment(self): test_comment = Comment.objects.create(post=self.post1, content="I am a comment", author=self.user1) self.assertEqual(str(test_comment), "I am a comment") self.assertEqual(test_comment.get_absolute_url(), self.post1_detail_url) ``` -------------------------------- ### Draw Great Circle Polyline Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Use the Leaflet.Arc plugin to draw a great circle route between two points. ```javascript var DallasToNYC = L.Polyline.Arc([DallasLatLng.lat, DallasLatLng.lon], [NYCLatLng.lat, NYCLatLng.lon], { color: 'orange' }) ``` -------------------------------- ### Test Home URL Resolves to HomeView Source: https://www.jsolly.com/blog/how-to-get-100-percent-unit-test-coverage/ Verifies that the home route resolves to the correct view class. Uses Django's resolve() function and asserts the view class is HomeView. ```python def test_home_url_is_resolved(self): self.assertEqual(resolve(self.home_url).func.view_class, HomeView) ``` -------------------------------- ### Include Leaflet and Plugins in Django Template Source: https://www.jsolly.com/blog/how-to-add-leaflet-js-maps-inside-a-django-site/ Add the Leaflet CSS and JS files along with custom plugins to your Django template's head block. ```html // site_analytics.html {% block head %} {% sri_static 'leaflet_plugins/leaflet.textpath.js' %} {% sri_static 'leaflet_plugins/leaflet-arc.min.js' %} {% endblock head %} ``` -------------------------------- ### Disable Root Login and Password Authentication Source: https://www.jsolly.com/blog/how-to-get-a-perfect-mozilla-observatory-score/ Modify the SSH daemon configuration to prevent root login and password-based authentication. ```bash sudo nano /etc/ssh/sshd_config # disable logging in as root user and password authentication # Change PermitRootLogin to no # Change PasswordAuthentication to no ``` -------------------------------- ### Define Post Model with IP Relationships Source: https://www.jsolly.com/blog/Adding-views-likes-to-posts/ Updates the Post model to include ManyToMany relationships with an IpPerson table for tracking likes and views. ```python class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True, blank=True, null=True) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=100, default='uncategorized') -> likes = models.ManyToManyField(IpPerson, related_name="post_likes", blank=True) -> views = models.ManyToManyField(IpPerson, related_name="post_views", blank=True) ``` -------------------------------- ### Original unoptimized head tag Source: https://www.jsolly.com/blog/smartly-load-CSS-JS-page-load-time/ This example shows a base template head tag that loads all CSS and JS resources globally, regardless of whether they are needed on the specific page. ```python ``` -------------------------------- ### Inspect IPFS Configuration and Find Providers Source: https://www.jsolly.com/blog/web3-notes-personal-reference/ Commands to view the local IPFS configuration file and locate peers hosting data for a specific CID. ```bash $ cat ~/.ipfs/config $ ipfs dht findprovs // Get peers that have hashed the node that is hosting the data ``` -------------------------------- ### views.py: Define handler_404 view to render custom 404 template Source: https://www.jsolly.com/blog/how-to-add-a-404-page-to-your-django-app/ Add a handler_404 view that renders the custom 404 template (blog/404_page.html) when a 404 exception occurs. ```python # views.py def handler_404(request, exception): return render(request, "blog/404_page.html") ``` -------------------------------- ### Update views.py for slug lookup Source: https://www.jsolly.com/blog/adding-slugified-urls/ Update the database lookup in views.py to use the slug field instead of the post ID. ```python post = Post.objects.get(slug=self.object.slug) ``` -------------------------------- ### Directive general format Source: https://www.jsolly.com/blog/mastering-gpt-directives-and-parameters/ Shows the general syntax for a GPT directive, where directiveName is an action verb and directObject1...directObjectN are the objects or conditions. Conditions can be added after a colon. ```text [directiveName: directObject1...directObjectN] ``` -------------------------------- ### Deprecation warning from django-admin-honeypot during tests Source: https://www.jsolly.com/blog/upgrading-to-the-latest-3x-django/ Example of a RemovedInDjango40Warning raised when running unit tests with Python's -Wa flag. The warning indicates django.utils.translation.ugettext_lazy() is deprecated in favor of gettext_lazy(), but it targets Django 4.0, not 3.x. ```python /code/blogthedata/django_project/venv/lib/python3.9/site-packages/admin_honeypot/admin.py:31: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy(). get_path.short_description = _('URL') ``` -------------------------------- ### HTML Link with noopener and noreferrer Source: https://www.jsolly.com/blog/use-noopener-norferrer-to-improve-user-privacy/ An example of an external link configured with rel="noopener noreferrer" and target="_blank" to open in a new tab while clearing referrer and window.opener information. ```html Linkedin ``` -------------------------------- ### Run Migration Command Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ Executes the migration using the Django management command. ```bash $ Python3 manage.py migrate ``` -------------------------------- ### Django method to get top 3 related posts by cosine similarity Source: https://www.jsolly.com/blog/cosine-similarity-better-than-tags/ Returns a queryset of the top three posts most similar to the current post, ordered by descending similarity score. ```python def get_related_posts(self) -> models.QuerySet: """ Get the top 3 related posts based on the cosine similarities. """ return Post.objects.filter( id__in=self.similarities1.order_by("-score").values_list( "post2", flat=True )[:3] ) ``` -------------------------------- ### views.py: Use get_object_or_404 to raise 404 for missing posts Source: https://www.jsolly.com/blog/how-to-add-a-404-page-to-your-django-app/ In the view's get_queryset method, use get_object_or_404 to fetch a Post by slug. This raises a 404 error instead of a 500 when the post is not found. ```python # views.py from django.shortcuts import get_object_or_404 def get_queryset(self): post = get_object_or_404(Post, slug=self.kwargs["slug"]) ``` -------------------------------- ### Test Post Form Valid Data Source: https://www.jsolly.com/blog/how-to-get-100-percent-unit-test-coverage/ Verifies that the PostForm is valid when provided with user-provided fields. Comments show internally generated fields (metaimg, date_posted, likes, views) are not included in the data. ```python def test_post_form_valid_data(self): form = PostForm(data={ "title": "My Second Post", "slug": "second-post", "category": "productivity", "metadesc": "I can make you more productive!", "draft": False, # "metaimg" : "" # "metaimg"_mimetype : "" "snippet": "Do the things", "content": "Do the things. All the things", # date_posted : "" "author": self.user1 # "likes" # "views" }) self.assertTrue(form.is_valid()) ``` -------------------------------- ### Apply migrations Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ Command to apply the pending migrations to the database. ```bash $ python manage.py migrate ``` -------------------------------- ### tsconfig.json configuration for TypeScript compilation Source: https://www.jsolly.com/blog/TypeScript-revealed-210-issues-JavaScript-codebase/ This configuration file sets the compiler options for TypeScript. It targets ES6, outputs compiled files to ./built, reads source files from ./src, and enables strict type checking. When you run tsc, TypeScript files are compiled into JavaScript and placed in the ./built folder. ```json // tsconfig.json { "compilerOptions": { "target": "ES6", "outDir": "./built", "rootDir": "./src", "strict": true } } ``` -------------------------------- ### TypeScript compiler error summary output Source: https://www.jsolly.com/blog/TypeScript-revealed-210-issues-JavaScript-codebase/ This is the output shown in the console when running tsc. It reports 210 errors across 9 files, listing the number of errors per file. This output indicates that the project compiles but has many type errors to resolve. ```bash Found 210 errors in 9 files. Errors Files 39 src/asteroids.ts:18 27 src/canvas.ts:5 29 src/collisions.ts:34 2 src/keybindings.ts:10 42 src/lasers.ts:22 9 src/scoreLevelLives.ts:39 28 src/ship.ts:134 30 src/soundsMusic.ts:8 4 src/utils.ts:9 ``` -------------------------------- ### requirements.txt content Source: https://www.jsolly.com/blog/Achieve-consistent-builds-with-Python-constraints/ Lists direct dependencies used by the project, with comments and ellipsis indicating more packages. ```bash # requirements.txt black Brotli chromedriver-autoinstaller coverage Django ... ``` -------------------------------- ### Project requirements directory structure Source: https://www.jsolly.com/blog/Achieve-consistent-builds-with-Python-constraints/ Shows the layout of the requirements directory containing constraints.txt and requirements.txt. ```bash requirements ├── constraints.txt └── requirements.txt ``` -------------------------------- ### Create empty migration for data transfer Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ Command to create an empty migration file for implementing custom data transfer logic. ```bash $ python3 manage.py makemigrations --empty --name transfer_categories blog ``` -------------------------------- ### Implement SearchView with Q objects Source: https://www.jsolly.com/blog/adding-global-search/ This view handles POST requests to search for posts by title or content. It uses the Q object to perform an OR query across multiple fields. ```python def SearchView(request): """Controls what is shown to a user when they search for a post.""" cat_list = Category.objects.all() if request.method == 'POST': searched = request.POST['searched'] filtered_posts = Post.objects.filter(Q(content__icontains=searched) | Q(title__icontains=searched)) return render( request, "blog/search_posts.html", {"cat_list": cat_list, "searched": searched, "filtered_posts": filtered_posts}, ) else: return render( request, "blog/search_posts.html", {"cat_list": cat_list}, ) ``` -------------------------------- ### Create Empty Migration Command Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ Generates an empty migration file named remove_category_rename_category_link for the blog app. ```bash $ python3 manage.py migrate --empty --name remove_category_rename_category_link blog ``` -------------------------------- ### Backup dependencies with pip freeze Source: https://www.jsolly.com/blog/upgrading-to-the-latest-3x-django/ Command to snapshot current Python dependencies into a requirements file (requirements_5_4_22.txt) for recreating the virtualenv if needed. ```bash pip freeze > requirements_5_4_22.txt ``` -------------------------------- ### Check DNS Nameservers with dig Source: https://www.jsolly.com/blog/how-to-send-email-with-python-the-hard-way/ Use the dig command to identify the DNS provider for a domain by querying the NS records. ```bash 🍁johnsolly:22-05-08:~ $ dig ns blogthedata.com ; <<>> DiG 9.10.6 <<>> ns blogthedata.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2368 ;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;blogthedata.com. IN NS ;; ANSWER SECTION: blogthedata.com. 86400 IN NS ns1.linode.com. blogthedata.com. 86400 IN NS ns2.linode.com. blogthedata.com. 86400 IN NS ns3.linode.com. blogthedata.com. 86400 IN NS ns4.linode.com. blogthedata.com. 86400 IN NS ns5.linode.com. ;; Query time: 130 msec ;; SERVER: 208.67.222.222#53(208.67.222.222) ;; WHEN: Sun May 08 17:52:49 PDT 2022 ;; MSG SIZE rcvd: 141 ``` -------------------------------- ### Initial Post model definition Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ The original Post model using a CharField for category without a formal database relationship. ```python # models.py class Post(models.Model): title = models.CharField(max_length=60) category = models.CharField(max_length=100, default="uncategorized") content = CKEditor5Field(blank=True, null=True, config_name='extends') ``` -------------------------------- ### Run collectstatic manually Source: https://www.jsolly.com/blog/git-hooks-to-perform-collectstatic/ The standard command used to sync static files in Django environments. ```bash Python3 manage.py collectstatic ``` -------------------------------- ### Squash migrations with manage.py Source: https://www.jsolly.com/blog/migrating-to-django-4x/ Use the squashmigrations command to combine multiple migration files into one, which helps resolve conflicts with deprecated packages. ```bash $ python3 manage.py squashmigrations blog 0006 Will squash the following migrations: - 0001_initial - 0002_add_likes - 0003_add_views_to_Post - 0004_add_slug_field - 0005_add_images_to_post - 0006_change_content_field_to_richtextuploading Do you wish to proceed? [yN] ``` ```text Created new squashed migration /Users/johnsolly/Documents/code/blogthedata/django_project/blog/migrations/0001_squashed_0006_change_content_field_to_richtextuploading.py You should commit this migration but leave the old ones in place; the new migration will be used for new installs. Once you are sure all instances of the codebase have applied the migrations you squashed, you can delete them. ``` -------------------------------- ### Flake8 Configuration File Source: https://www.jsolly.com/blog/implement-continuous-integration-github-actions/ Configuration for Flake8 to exclude specific directories and ignore line length warnings. ```ini [flake8] exclude = venv migrations ignore = E501 ``` -------------------------------- ### Define linting scripts in package.json Source: https://www.jsolly.com/blog/I-resolved-150-linting-issues-with-eslint/ Configuration for linting and auto-fixing scripts within the package.json file. ```json // package.json "scripts": { ... "lint": "eslint . --ext .js,.ts", "lint-fix": "eslint . --fix --ext .js,.ts", }, ``` -------------------------------- ### Sidebar Template with Category Counts Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ Displays the category list and post count badges in templates/sidebar.html. ```html # templates/sidebar.html

Navigate to a Category

{% for cat_item in cat_list %} {{cat_item|title}} {{ cat_item.posts_count }} {% endfor %} ``` -------------------------------- ### Coverage Configuration File Source: https://www.jsolly.com/blog/implement-continuous-integration-github-actions/ Configuration for the coverage module, including the django-coverage plugin and exclusion of test files. ```ini [run] plugins = django_coverage_plugin omit = */tests/* ``` -------------------------------- ### Run lint-fix command Source: https://www.jsolly.com/blog/I-resolved-150-linting-issues-with-eslint/ The command executed by the pre-commit hook to automatically fix linting issues. ```bash npm run lint-fix ``` -------------------------------- ### Generate migration for temporary field Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ Command to create a migration for adding the temporary category_link field. ```bash $ python3 manage.py makemigrations --name add_temp_category_link_field blog ``` -------------------------------- ### Tailwind with Scoped Vanilla CSS for Transforms Source: https://www.jsolly.com/blog/three-scenarios-i-dont-use-tailwind/ Combines Tailwind for general layout with scoped CSS for handling transform animations on the accordion icon. ```html ``` -------------------------------- ### Migration file for adding category_link Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ The generated migration file that adds the ForeignKey field to the Post table. ```python # migrations/0017_add_temp_category_link_field.py from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0016_add_alt_txt_to_meta_img'), ] operations = [ migrations.AddField( model_name='post', name='category_link', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='blog.category'), ), ] ``` -------------------------------- ### SQL query for category filtering Source: https://www.jsolly.com/blog/UI-enhancement-leads-to-major-architecture-changes/ The underlying SQL query generated by the string-based filtering logic. ```sql SELECT * FROM Post WHERE category = "site updates" ``` -------------------------------- ### constraints.txt content Source: https://www.jsolly.com/blog/Achieve-consistent-builds-with-Python-constraints/ Pins versions for all dependencies including sub-dependencies, with ellipsis indicating more entries. ```python # constraints.txt black==22.3.0 Brotli==1.0.9 cachetools==5.2.0 certifi==2022.6.15 cffi==1.15.1 ... ``` -------------------------------- ### Generate hash with OpenSSL Source: https://www.jsolly.com/blog/how-to-implement-subresource-integrity-django/ Command to generate a SHA-384 hash for a file using OpenSSL. ```bash $ openssl dgst -sha384 -binary prism_patched.min.js | openssl base64 -A ```