Top Stories

Ankaj Gupta
October 10, 2021

How do I get the Yelp Fusion API Key | How to get Yelp API Key

# In this article you will learn, How to create a new yelp account and How do you get the Yelp Fusion API Key.

What is Yelp API?

The Yelp Fusion API allows users to get local content and user reviews from millions of businesses, such as the restaurant, hospitality and service industries in 32 countries. Yelp content may be used for app and website development purposes.

# How to Create a Yelp Account

Step 1: Go-to yelp developers portal

To continue with Yelp API, First you need to visit the Yelp developers portal. Yelp developers portal

Yelp developers portal

Step 2: Create a Yelp Account.

You can continue to work with the Yelp service through a Facebook, Google, or Apple account. Another option is to sign up with your email address.

Note: You have to verify that you are not a robot by filling the recaptcha.

Now your account is successfully created.

Step 3: Verify email id

In this case you will receive a confirmation email - don't forget to follow the link in it to verify your account.

yelp verify email

# How do I get the Yelp API Key

Step 1: Get started with Fusion API

Once you are logged into the Yelp Developers service, first scroll to the bottom of the page and hit the Explore Yelp Fusion button.

Explore Yelp Fusion

Step 2: Create an App

First, log in to the Developers Portal with your existing Yelp account or create a new one.

How do I get the Yelp Fusion API Key | How to get Yelp API Key

Create your first Yelp app to receive your personal Yelp fusion API Key and fill in the required fields in the form, agree to the Yelp API Terms of Use and performance requirements. Then prove you're a human, and press Create New App button.

yelp api form | Create the Yelp App | Yelp Fusion API Key

Step 3: Get your Client ID and API Key.

After submitting the form, you will get your Client ID and API Key. Save them to start working with your app.

Get yelp Client ID and API Key | Yelp Fusion API Key

Note: Remember to keep your personal Yelp API Key with yourself! This is the credential for your calls to Yelp's API and must be used only by you.

API Yelp Fusion
Read
Ankaj Gupta
October 02, 2021

How to fetch single column from database in Django | Django values_list querysets

How to Fetch Single or Column Data from Database in Django ORM

In Django, with the help of the values_list() method, you can fetch single or multiple column data from your database efficiently.

Django values_list querysets

Introduction

The values_list() method is similar to values(), except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call.

Example Model

Your Posts model is like this:

class Posts(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=155)
    
    class Meta:
        verbose_name_plural = "Posts"

    def __str__(self):
        return self.title

Basic Usage

# Fetch single column data
Posts.objects.values_list('id',)

# Fetch more than one column data
Posts.objects.values_list('id', 'title',)

# You can also fetch in order_by
Posts.objects.values_list('id', 'title',).order_by('?')

Note: You can also pass in a flat parameter if you only pass in a single field. It will return true/false values.

Understanding flat=True

If flat=True, the returned results are single values, rather than one-tuples. Let's look at an example to make the difference clear:

# Without flat=True
Posts.objects.values_list('id')
# Output: [(1,), (2,), (3,), ...]

# With flat=True
Posts.objects.values_list('id', flat=True)
# Output: [1, 2, 3, ...]

Important Limitation

values_list raises an error if you try to pass in flat=True when there is more than one field.

# This will raise an error
Posts.objects.values_list('id', 'title', flat=True)
Django values_list error

Important Points

  • All Fields: If you don't pass any values to values_list(), it will return all the fields in the model, in the order they were declared.
  • QuerySet Behavior: values_list method returns a ValuesListQuerySet that behaves like a list. If you require an actual Python list object, you can call list() on it.
  • Getting Specific Values: A common requirement is to get the specific field value of a certain model instance. Use values_list() and then call the get() method.

Example of getting a specific value:

# Code
Posts.objects.values_list('title', flat=True).get(pk=1)

# Output
'First entry'

values_list() vs values()

Feature values_list() values()
Return Type Tuples Dictionaries
Memory Usage Lower (more efficient) Higher
Best For Getting specific field values Getting labeled data

Summary

values_list() is a powerful and efficient method for fetching specific columns from your database. Use it when you need specific field values, especially with flat=True for single fields to get clean, flat lists of values.

Remember: flat=True only works with single fields, and calling values_list() without arguments returns all fields in declaration order.

Recommended Posts

django Django QuerySet
Read
Ankaj Gupta
July 18, 2021

Java program to find and print all special characters with their positions in a string

Program to Find Special Characters in a String

In this section, you will learn how to find special characters from a string in Java along with counting the total number of special characters with their positions in a given string.

Java program to find special characters in a string

Overview

This Java program demonstrates how to use regular expressions to find and count special characters in a string. Special characters are any characters that are not letters (a-z, A-Z), numbers (0-9), or spaces.

Complete Program

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;

class FindSpecialCharacters {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        String str;

        System.out.print("\nEnter a string : ");
        str = input.nextLine();

        Pattern string_patterns = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
        Matcher string_matcher = string_patterns.matcher(str);

        System.out.println("\n\n\t______________ OUTPUT ______________");
        System.out.println("\nYour string is : "+str);

        int count = 0;
        while(string_matcher.find()) {
            count = count + 1;
            System.out.println("\tposition "+string_matcher.start() +": "+ str.charAt(string_matcher.start()));
        }
        System.out.println("\nThere are "+count+" special characters");
        System.out.println("\n\t------------------------------------");
    }
}

Code Explanation

1. Pattern Definition

Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE)

This regex pattern [^a-z0-9 ] matches any character that is NOT a letter (a-z), number (0-9), or space.

2. Matcher Usage

Matcher string_matcher = string_patterns.matcher(str)

The matcher is created to find all occurrences of the pattern in the input string.

3. Finding Special Characters

while(string_matcher.find()) {
    count = count + 1;
    System.out.println("\tposition "+string_matcher.start() +": "+ str.charAt(string_matcher.start()));
}

The find() method returns true each time a match is found, and start() returns the position of the match.

Key Concepts

Regex Pattern

[^a-z0-9 ] is a negated character class that matches anything except letters, digits, and spaces.

Matcher.find()

Returns true if the pattern is found in the string and advances the matcher to the next match.

Matcher.start()

Returns the start position of the previous match in the string.

Pattern.CASE_INSENSITIVE

Flag to make pattern matching case-insensitive, covering both uppercase and lowercase letters.

Sample Outputs

Output 1: String with Special Characters

Enter a string : `Welcome to #coderwebsite && "j@v@" is @m@zing programming l@ngu@ge`!

        ______________ OUTPUT ______________

Your string is : `Welcome to #coderwebsite && "j@v@" is @m@zing programming l@ngu@ge`!
	position 0: `
	position 12: #
	position 26: &
	position 27: &
	position 29: "
	position 31: @
	position 33: @
	position 34: "
	position 39: @
	position 41: @
	position 60: @
	position 64: @
	position 67: `
	position 68: !
There are 14 special characters
        ------------------------------------

Output 2: String without Special Characters

Enter a string : Welcome to coderwebsite 

        ______________ OUTPUT ______________

Your string is : Welcome to coderwebsite 
There are 0 special characters
        ------------------------------------

Use Cases

  • Data Validation: Check if user input contains invalid special characters
  • Password Validation: Ensure passwords contain or don't contain certain characters
  • Text Sanitization: Identify and remove special characters from text
  • Security Checks: Detect potentially malicious input or SQL injection attempts

Summary

This program effectively demonstrates how to use Java's regex capabilities to find and count special characters in a string. The key is using a negated character class [^a-z0-9 ] to match anything that isn't a letter, digit, or space.

By combining Pattern and Matcher classes, you can efficiently process strings and extract specific information based on complex patterns.

Recommended Posts

Java program Java programming
Read
Ankaj Gupta
July 18, 2021

How to find special characters in a string in java | Java program to check and get special characters in a String

Program to Find Special Characters in a String (Without Regex)

In this section, you will learn how to find special characters from a string in Java along with counting the total number of special characters in a given string, without using regular expressions. This approach uses ASCII value checking.

Java program to find special characters in a string

Overview

This Java program demonstrates an alternative approach to finding special characters in a string by checking ASCII values of each character. This method is useful when you want to avoid regex or need more control over character classification.

Complete Program

import java.util.Scanner;

class FindSpecialCharacters {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        String str;
        char find_special_charactetr[] = new char[1000];

        System.out.print("\nEnter a string :");
        str = input.nextLine();

        int p, special_charactetr = 0;
        char a[] = str.toCharArray();
        int len = a.length;

        for (int i = 0; i < len; i++) {
            p = a[i];
            if (p >= 65 && p <= 90 || p >= 97 && p <= 122 || p == 32 || p >= 48 && p <= 57) {
                continue;
            } else {
                find_special_charactetr[special_charactetr] = a[i];
                special_charactetr++;
            }
        }

        if (special_charactetr > 0) {
            System.out.println("\n\n\t______________ OUTPUT ______________");
            System.out.println("\nSpecial characters is :"+String.valueOf(find_special_charactetr));
            System.out.println("There are "+special_charactetr+" special characters");
            System.out.println("\n\t------------------------------------");
        } else {
            System.out.println("\n\n\t______________ OUTPUT ______________");
            System.out.println("\n Note that : No any special characters in : {"+str+"}");
            System.out.println("\n\t------------------------------------");
        }
    }
}

Code Explanation

1. ASCII Value Check

if (p >= 65 && p <= 90 || p >= 97 && p <= 122 || p == 32 || p >= 48 && p <= 57)

This condition checks if a character is:

  • 65-90: Uppercase letters (A-Z)
  • 97-122: Lowercase letters (a-z)
  • 32: Space character
  • 48-57: Digits (0-9)

If the character doesn't match any of these ranges, it's considered a special character.

2. Character Array Conversion

char a[] = str.toCharArray();

Converts the string into a character array for easy iteration and ASCII value checking.

3. Special Character Collection

else {
    find_special_charactetr[special_charactetr] = a[i];
    special_charactetr++;
}

When a special character is found, it's stored in the special character array and the counter is incremented.

ASCII Value Reference

Character Type ASCII Range Example Characters
Uppercase Letters 65-90 A, B, C, ..., Z
Lowercase Letters 97-122 a, b, c, ..., z
Digits 48-57 0, 1, 2, ..., 9
Space 32 " "

Sample Outputs

Output 1: String with Special Characters

Enter a string : #Welc@me t@ c@derwebsite!

        ______________ OUTPUT ______________

Special characters is : #@@@!
There are 5 special characters
        ------------------------------------

Output 2: String without Special Characters

Enter a string : Welcome to coderwebsite 

        ______________ OUTPUT ______________

Note that : No any special characters in : {Welcome to coderwebsite}
        ------------------------------------

ASCII Method vs Regex Method

Advantages

  • • No regex knowledge required
  • • Simple and straightforward logic
  • • Easy to customize character classification
  • • More control over which characters are considered special

Disadvantages

  • • Longer code compared to regex
  • • Requires memorizing ASCII values
  • • Less flexible than regex patterns
  • • More prone to errors in range definition

Summary

This program demonstrates a manual approach to finding special characters using ASCII value checking. This method is educational and helps understand how characters are represented in computers.

For production code, the regex approach (Pattern.compile("[^a-z0-9 ]")) is generally more concise and maintainable, but this ASCII-based approach provides valuable insights into character encoding.

Recommended Posts

Java program Java programming
Read
Ankaj Gupta
July 09, 2021

How to store emoji expressions in django mysql | Solve the problem of failure to store emoji expressions in django

How to Store Emoji Expressions in Django + MySQL

This guide shows you how to resolve the encoding error when trying to store emoji expressions in Django with MySQL database. The solution involves converting MySQL encoding from utf8 to utf8mb4.

Common Problem

The error when storing emoji expressions in Django + MySQL:

django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x90\\xA6 \\xF0...' for column 'description' at row 1")

Reason

UTF-8 encoding may be two, three, or four bytes. Emoji expressions are 4-byte characters, but MySQL's standard utf8 encoding only supports up to 3 bytes, so the data can't be inserted into the database.

Solution: Convert MySQL encoding from utf8 to utf8mb4, which supports 4-byte UTF-8 characters including emoji.

Settings in MySQL

Follow these steps to configure MySQL for emoji support:

Step 1: Modify Database Character Set

Alter the database to use utf8mb4 encoding:

ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

Step 2: Use the Database

Switch to the database you want to modify:

USE database_name;

Step 3: Modify Table Character Set

Convert the table to utf8mb4:

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Step 4: Modify Column Character Set

Change the specific column to utf8mb4:

ALTER TABLE table_name CHANGE field_name field_name VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Note: Replace field_name with your actual column name and adjust the VARCHAR size as needed.

Settings in Django

Configure Django to use utf8mb4 charset:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your-db-name',
        'USER': 'user_name',
        'PASSWORD': 'your-db-password',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'charset': 'utf8mb4',  # Support emoji
        }
    }
}

Key Point: The 'OPTIONS': {'charset': 'utf8mb4'} setting is crucial for emoji support in Django.

Understanding UTF-8 Encodings

Encoding Type Bytes per Character Supports Emoji Usage
utf8 1-3 bytes ❌ No Basic Latin, Asian characters
utf8mb4 1-4 bytes ✅ Yes Full UTF-8 including emoji, symbols

Testing the Fix

After applying the changes, test emoji storage in your Django model:

# Example model
class Post(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    
    def __str__(self):
        return self.title

# Test emoji storage
post = Post.objects.create(
    title='Happy Post ๐Ÿ˜€',
    description='This post contains emojis ๐ŸŽ‰๐ŸŒŸ✨'
)
# Should work without errors!

Important Notes

  • Existing Data: If you have existing data, you may need to back up and migrate your database after changing the charset.
  • Index Size: utf8mb4 can increase index size by up to 33% compared to utf8. Plan your database accordingly.
  • Performance: utf8mb4 is slightly slower than utf8 due to 4-byte storage, but the difference is usually negligible.
  • MySQL Version: utf8mb4 support is available in MySQL 5.5.3 and later versions.

Summary

To store emoji expressions in Django + MySQL, you need to convert from utf8 to utf8mb4 encoding. This involves changing the database, table, and column character sets in MySQL, as well as configuring Django's database OPTIONS to use utf8mb4 charset.

The key insight is that emoji characters require 4 bytes in UTF-8, while MySQL's standard utf8 encoding only supports up to 3 bytes per character. The utf8mb4 encoding solves this limitation.

django django and mysql
Read
Ankaj Gupta
May 02, 2021

How to remove ? m=1 or ?m=0 from blogger post URL

Remove ?m=1 From Blogger Post URL

A common question that every blogger searches for is how to remove ?m=1 or ?m=0 from Blogger post URLs. We all know that "simplicity is beauty" and you want a clean permalink. This guide will help you remove these parameters and create professional, clean URLs for your blog posts.

Why Remove ?m=1?

The ?m=1 parameter appears when users access your blog from mobile devices. Removing it provides several benefits.

  • Professional Permalink: Gives your blog posts cleaner, more professional URLs
  • Better SEO: Helps improve ranking in Search Engine Result Pages
  • Shorter URLs: Makes your blog post URLs shorter and easier to share
  • User Experience: Cleaner URLs look more trustworthy and professional

Step-by-Step Tutorial

Follow these simple steps to remove ?m=1 from your Blogger post URLs:

Step 1: Login to Blogger Dashboard

First, log in to your Blogger dashboard and select your blog.

How to remove m1 from blogger url

Step 2: Navigate to Theme Section

Click on the Theme option in your Blogger dashboard.

Fix Blogger m=1 Duplicate Content Issue

Step 3: Click on Customize

Click on the Customise button to access theme settings.

Remove ?m=1, ?m=0 suffix when visiting from mobile

Step 4: Access Edit HTML

Click on Edit HTML option to modify your theme code.

How to Remove ?m=1 From Website URL On Mobile

Step 5: Find the </head> Tag

Press (CTRL + F) from your keyboard and type /head to find the closing head tag.

New Blogger Easily Remove ?m=1 from Your Website with code

Step 6: Add the Code

Paste the below code just above the </head> tag.

How to remove ? m=1 from URL in blogger
<script type='text/javascript'>
    //<![CDATA[
var uri = window.location.toString();
if (uri.indexOf("%3D","%3D") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("%3D"));
    window.history.replaceState({}, document.title, clean_uri);
}
var uri = window.location.toString();
if (uri.indexOf("%3D%3D","%3D%3D") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("%3D%3D"));
    window.history.replaceState({}, document.title, clean_uri);
}
var uri = window.location.toString();
if (uri.indexOf("&m=1","&m=1") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("&m=1"));
    window.history.replaceState({}, document.title, clean_uri);
}
var uri = window.location.toString();
if (uri.indexOf("?m=1","?m=1") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("?m=1"));
    window.history.replaceState({}, document.title, clean_uri);
}
//]]>
</script>

Step 7: Save Settings

Finally, click on the Save icon to save your settings and code.

Removing ?m=1 From Blogger

How the Code Works

The JavaScript code works by:

  • Getting the current URL using window.location.toString()
  • Checking if the URL contains various encoded or unencoded versions of m=1
  • Extracting the clean URL by removing the unwanted parameters
  • Using window.history.replaceState() to update the URL without reloading the page

Code Breakdown

URL Encoding Handling

The code handles both encoded %3D and unencoded = versions.

Multiple Parameter Checks

Checks for ?m=1, &m=1, and their encoded forms.

No Page Reload

Uses replaceState() instead of pushState() to avoid adding to browser history.

Just save and go to mobile and check the permalink/URL of your Blogger post. You will see that ?m=1 or ?m=0 has been removed. Now enjoy clean, professional URLs! Happy Blogging! :)

Summary

Removing the ?m=1 parameter from Blogger URLs is a simple but effective way to improve your blog's professionalism and SEO. The JavaScript solution provided here works seamlessly across all devices and automatically cleans URLs without requiring any additional configuration.

The code is safe, lightweight, and doesn't affect your blog's performance or functionality. It simply removes the unwanted parameters from the URL when users visit your blog from mobile devices.

Recommended Posts

Blogger blogging
Read
Ankaj Gupta
April 13, 2021

How to connecting PostgreSQL with a Django application

Connect Django App to PostgreSQL Database

In this article, you will learn how to connect a PostgreSQL database to a Django Python web application. You will also learn how to edit your Django Project settings file and connect your web application to a PostgreSQL database.

django connect with PostgreSQL

Introduction

Django is a flexible framework for quickly creating Python applications. By default, Django applications are configured to store data into a lightweight SQLite database file. While this works well under some loads, a more traditional DBMS like PostgreSQL can significantly improve performance in production.

Why PostgreSQL? PostgreSQL offers better performance, advanced features, and robust data integrity for production applications.

Video Tutorial

Step-by-Step Guide

Step 1: Create PostgreSQL Database

When you open the pgAdmin panel, you will view a server icon in the navigation at the left side of the window. Click on it to open the databases icon. Right-click on the databases icon to create a new database and fill the prerequisites for creating the database.

Step 2: Install psycopg2 Adapter

Install an adapter to connect the database with the Django app. We will be using psycopg2 for this purpose.

pip install psycopg2

Note: To install psycopg2 adapter, we also need to install Pillow if we wish to save any pictures in our database.

pip install pillow

Step 3: Configure Django Settings

Go to the settings.py file of your Django app. Under the settings file for databases, change the settings from SQLite or your current database to PostgreSQL.

Default SQLite Configuration:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

PostgreSQL Configuration:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'your-db-name',
        'USER': 'user_name',
        'PASSWORD': 'your-db-password',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Important: Replace 'your-db-name', 'user_name', and 'your-db-password' with your actual PostgreSQL credentials.

Step 4: Run Makemigrations

Run the makemigrations command to convert all your models into database queries.

python manage.py makemigrations

Note: The correct command is python manage.py, not pip manage.py.

Step 5: Run Migrate

Finally, run the migrate command to migrate these changes into your PostgreSQL database.

python manage.py migrate

Verify Your Setup

You can verify the connection by checking your PostgreSQL database in pgAdmin:

Navigate to: Servers → PostgreSQL → Databases → DB_Name → Schema → Public → Tables

You should see Django's built-in tables created in your PostgreSQL database, confirming that the connection is successful!

Configuration Details

Setting Value Description
ENGINE django.db.backends.postgresql_psycopg2 Database backend adapter
NAME your-db-name Database name
USER user_name PostgreSQL username
PASSWORD your-db-password Database password
HOST localhost Database server hostname
PORT 5432 PostgreSQL default port

Benefits of Using PostgreSQL

Performance

Better performance for large-scale applications with concurrent users

Advanced Features

Support for complex queries, JSON data, and full-text search

Data Integrity

ACID compliance and robust data validation

Scalability

Handles large datasets and high traffic efficiently

Summary

Connecting Django to PostgreSQL is a straightforward process that involves installing the psycopg2 adapter, configuring your database settings in settings.py, and running migrations to create the necessary tables.

This setup provides a robust foundation for production Django applications, offering better performance, scalability, and advanced database features compared to the default SQLite database.

django PostgreSQL
Read
Ankaj Gupta
March 29, 2021

Django not able to find static files[Solved]

Django Static Files Not Working - Fix Guide

In this article, you will learn how to fix the problem of Django not loading static files. This is the easiest and safest solution for Django 3.1 and above.

Introduction

In Django 3.1 and above, the settings.py file uses pathlib.Path instead of os.path to handle directory structures. This means static file configurations using os.path.join won't work unless you import os at the top of your settings file.

Note: This article is for DEBUG = True. For DEBUG = False, follow: Static files not working when DEBUG = False

Step-by-Step Solution

Step 1: Define BASE_DIR

Ensure BASE_DIR is defined in settings.py. If not, add it:

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Step 2: Check Debug Mode

Ensure debug mode is enabled in settings.py:

DEBUG = True

ALLOWED_HOSTS = []

Step 3: Configure Static Files

Define STATIC_URL and STATICFILES_DIRS in settings:

Note: For Django 3.1+, you need to import os and use it for static paths.

STATIC_URL = '/static/'  # the path in url

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

Step 4: Use Static Template Tag

In templates, use the static template tag to build URLs for static files. Store files in my_app/static/image/example.jpg:

{% load static %}



    Welcome! to coderwebsite
    
    



    

My Django project

logo
  • • Create a static folder at your project root directory
  • • Use {% load static %} at the top of your templates
  • • Reference static files using {% static 'path/to/file' %}

Step 5: Run Django Server

Start the development server:

python manage.py runserver

Success! Static files will now load correctly in your Django project!

Recommended Directory Structure

my_django_project/
├── manage.py
├── my_app/
│   └── static/
│       ├── css/
│       │   └── styles.css
│       ├── js/
│       │   └── script.js
│       └── images/
│           └── logo.png
├── static/  (project-level static files)
│   └── ...
└── settings.py

Key Points

Import os

Always import os when using os.path.join in Django 3.1+

Load Static

Use {% load static %} in every template that uses static files

DEBUG True

Static files are auto-served in development when DEBUG = True

Collectstatic

In production, run python manage.py collectstatic

Common Mistakes to Avoid

  • Missing os import: Forgetting to import os in Django 3.1+
  • Incorrect path: Using wrong BASE_DIR or static directory path
  • Wrong template syntax: Using {static} instead of {% static %}
  • Hardcoded paths: Using hardcoded /static/ instead of template tag

Summary

Fixing Django static files requires proper configuration in settings.py and correct template syntax. The key is ensuring os is imported and STATICFILES_DIRS is properly set up.

Remember to use the {% load static %} template tag and reference static files using the {% static %} tag for proper URL generation.

django django static files
Read
Ankaj Gupta
March 25, 2021

Django static files not working when debug false || debug true

Django static not working when debug is false

# Django static and media files not working when debug is false

In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution.

# Problem:

Django static and media files not working when debug is false

➤ Code: settings.py

  • DEBUG = False #True
  • ALLOWED_HOSTS = ['*'] #Host name

# Problem Fix:

Let's see, How you can fix the problem of Django static and media files not working when DEBUG = False :

1.) First way: devserver in insecure mode

If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:

  • python manage.py runserver --insecure

--insecure: it means you can run server without security mode.

Note: This is exactly what you must type on terminal to run your project without "DEBUG = TRUE" and then you see all assets (static) file is loading correctly on local server.

2.) Second way: devserver in secure mode

Step 1: Define a STATIC_ROOT and MEDIA_ROOT path in settings.py.

➤ Code: settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

if DEBUG:
    STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Step 2: Now define your URLConf that if static is in the beginning of url, access files from the static folder staticfiles.

➤ Code: urls.py

from django.conf.urls import url
from django.conf import settings
from django.views.static import serve

urlpatterns = [
    url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
    url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}),
]

Note: This is your project's urls.py file.

Step 3: Now you can run your django project.

  • python manage.py runserver

Note: Congratulations, now static and media files will be loaded in your Django project when DEBUG = False. Have fun!

django django static files
Read