Database Setup - potatoscript/django GitHub Wiki

🔌 Connecting Django to SQLite / PostgreSQL

🗂️ Connecting Django to SQLite

By default, Django uses SQLite as the database engine. If you're starting a project and don't need a complex database setup, SQLite is a great choice because it’s simple and doesn’t require a separate server.

📂 Step 1: Using SQLite (Default in Django)

When you create a new Django project, it automatically uses SQLite for your database. You don’t need to change anything in your settings for SQLite to work.

In your settings.py, you will find a section like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',  # SQLite engine
        'NAME': BASE_DIR / 'db.sqlite3',         # Path to the database file
    }
}

📊 What's Happening Here:

  • ENGINE: Tells Django to use SQLite (django.db.backends.sqlite3).
  • NAME: Defines the path to the SQLite database file. The default db.sqlite3 is stored in your project directory (BASE_DIR).

⚙️ Step 2: Running the Migrations (For SQLite)

Once the settings are configured (which is done by default), you’ll want to run migrations. Migrations are what Django uses to set up your database with the proper tables based on your models.

Run the following commands in your terminal:

  1. Create the database and tables:

    python manage.py migrate
    
  2. Create a superuser to access Django’s admin:

    python manage.py createsuperuser
    
  3. Run the server to check if everything is working:

    python manage.py runserver
    

Now, you can open http://127.0.0.1:8000/admin/ and log in with the superuser credentials you created!


🔌 Connecting Django to PostgreSQL

While SQLite is great for simple projects, PostgreSQL is more robust and ideal for larger applications. Let’s go over how to connect Django to PostgreSQL.

📂 Step 1: Install PostgreSQL and the Required Python Package

  1. Install PostgreSQL on your system:

    • For Windows: Download from PostgreSQL website.
    • For macOS: You can install via Homebrew:
      brew install postgresql
      
    • For Linux: Install via your package manager, for example, in Ubuntu:
      sudo apt-get install postgresql postgresql-contrib
      
  2. Install psycopg2: This is the database adapter for PostgreSQL that allows Django to communicate with the database. Run:

    pip install psycopg2
    

    Alternatively, you can install the binary version:

    pip install psycopg2-binary
    

📂 Step 2: Configure PostgreSQL in Django Settings

Once PostgreSQL is installed and psycopg2 is added to your project, you need to change your DATABASES setting in settings.py to point to PostgreSQL.

Here’s what your settings might look like:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',  # PostgreSQL engine
        'NAME': 'your_database_name',               # Database name
        'USER': 'your_username',                    # PostgreSQL username
        'PASSWORD': 'your_password',                # PostgreSQL password
        'HOST': 'localhost',                        # Localhost (for local development)
        'PORT': '5432',                             # Default PostgreSQL port
    }
}

🧩 Key Points to Note:

  • ENGINE: Tells Django to use PostgreSQL (django.db.backends.postgresql).
  • NAME: The name of your PostgreSQL database.
  • USER: The PostgreSQL username (usually postgres by default).
  • PASSWORD: The password for your PostgreSQL user.
  • HOST: Set to localhost when developing locally, or the IP address of your PostgreSQL server.
  • PORT: Default is 5432 unless you have configured PostgreSQL to use a different port.

📂 Step 3: Create a PostgreSQL Database

Before Django can connect to PostgreSQL, you need to create the database. You can do this via the PostgreSQL command line interface or a GUI tool like pgAdmin.

  1. Log into PostgreSQL:

    sudo -u postgres psql
    
  2. Create a new database:

    CREATE DATABASE your_database_name;
    
  3. Create a new user (if needed):

    CREATE USER your_username WITH PASSWORD 'your_password';
    
  4. Grant privileges to your user on the new database:

    GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_username;
    
  5. Exit PostgreSQL:

    \q
    

Now your PostgreSQL database and user are set up and ready to connect to Django!


📂 Step 4: Run Migrations for PostgreSQL

Just like with SQLite, once you have configured the database, you need to run the migrations to create the tables for your models in PostgreSQL.

Run the following command in your terminal:

python manage.py migrate

This command will apply all migrations and set up your database schema in PostgreSQL.


📂 Step 5: Create a Superuser for Admin Access

To access Django’s admin panel, create a superuser for your PostgreSQL database:

python manage.py createsuperuser

📂 Step 6: Run the Server

Finally, run your Django development server to check if everything is connected correctly:

python manage.py runserver

You can now visit http://127.0.0.1:8000/admin/ and log in with the superuser credentials to access the admin panel.


🌐 Additional Notes

  • Production Setup: When deploying your application to production, remember to use more secure settings, like storing sensitive database credentials in environment variables instead of hardcoding them in settings.py.
  • PostgreSQL Configuration: Make sure that your PostgreSQL server is properly configured to allow remote connections if deploying to a production server. This might involve modifying the pg_hba.conf and postgresql.conf files.

🧩 Summary

Database Steps Django Configuration
SQLite 1. No installation needed DATABASES['default']['ENGINE'] = 'sqlite3'
PostgreSQL 1. Install PostgreSQL and psycopg22. Create DB/User DATABASES['default']['ENGINE'] = 'postgresql'