Django Portfolio Journal

Create a JSON file to store database content


on branch: dev/ckeditor

As I said before, I had to rebuild the database several times because of changes to the model attributes, so I had to find another way to make this task easier. I found three different ways to store the content in my project: in a CSV file, in a text file or in a JSON file. I decided to use a JSON file because it met my criteria.

I started with the differnt descriptions for myself, the DoriDoro instance to test this method. And I created a JSON file within the management/commands/ folder named: descriptions.json.

{
    "profile_description": "Text for my profile description",
    "dream_job_description": "Text for the dream job",
    "free_time_description": "Free time text"
}

With this new JSON file, I had to change the way I retrieve the content from the JSON file and use the content to create the DoriDoro instance in my management command.

            path = "doridoro/management/commands/descriptions.json"
            try:

                def get_descriptions(key):
                    with open(path, "r") as file:
                        descriptions = json.load(file)
                        return descriptions.get(key)

            except FileNotFoundError:
                print(f"The file {path} was not found.")
            except IOError:
                print(f"An error occurred while trying to read the file {path}.")
            except json.JSONDecodeError:
                print(f"The file {path} does not contain valid JSON.")
            except Exception as e:
                print(f"An unexpected error occurred: {e}")

Here you can see the whole Management Command to create a DoriDoro instance:

# doridoro/management/commands/create_doridoro.py

import json

from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import IntegrityError, transaction

from doridoro.models import DoriDoro

UserModel = get_user_model()


class Command(BaseCommand):
    help = "This command creates one DoriDoro instance."

    def handle(self, *args, **options):
        path = "doridoro/management/commands/descriptions.json"

        if (
            not DoriDoro.objects.exists()
            and not UserModel.objects.filter(username="doridoro").exists()
        ):

        raw_password = input("Please enter the password for DoriDoro: ")

        try:
            def get_descriptions(key):
                with open(path, "r") as file:
                    descriptions = json.load(file)
                    return descriptions.get(key)

        except FileNotFoundError:
            print(f"The file {path} was not found.")
        except IOError:
            print(f"An error occurred while trying to read the file {path}.")
        except json.JSONDecodeError:
            print(f"The file {path} does not contain valid JSON.")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")

            with transaction.atomic():
                user = UserModel.objects.create_user(
                    username="doridoro",
                    password=raw_password,
                    is_staff=True,
                )
                DoriDoro.objects.create(
                    user=user,
                    profession="Python/Django Developer",
                        introduction=get_descriptions("profile_description"),
                        dream_job=get_descriptions("dream_job_description"),
                        free_time=get_descriptions("free_time_description"),
                )

I have removed some personal information in the creation of the user and doridoro instance.

This use of JSON files to create content and instances will evolve over time.


Designed by BootstrapMade and modified by DoriDoro