"""
Django settings for civiwiki project.
Darius Calliet May 12, 2016

Production settings file to select proper environment variables.
"""
import os

# False if not in os.environ
DEBUG = os.getenv("DEBUG", False)

# defaults to second value if not found in os.environ
DJANGO_HOST = os.getenv("DJANGO_HOST", "LOCALHOST")

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "TEST_KEY_FOR_DEVELOPMENT")
ALLOWED_HOSTS = [".herokuapp.com", ".civiwiki.org", "127.0.0.1", "localhost", "0.0.0.0"]

INSTALLED_APPS = (
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django_extensions",
    "storages",
    "core",
    "rest_framework",
    "accounts.apps.AccountsConfig",
    "threads",
    "notifications",
    "corsheaders",
    "taggit",
    "categories",
    "notification",
    "debug_toolbar",
)

MIDDLEWARE = [
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

INTERNAL_IPS = [
    "127.0.0.1",
]

CSRF_USE_SESSIONS = (
    True  # Store the CSRF token in the users session instead of in a cookie
)

CORS_ORIGIN_ALLOW_ALL = True
ROOT_URLCONF = "core.urls"

# SSL Setup
if DJANGO_HOST != "LOCALHOST":
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True

# Internationalization & Localization
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "threads/templates/threads"),
            os.path.join(BASE_DIR, "accounts/templates/accounts"),
        ],  # TODO: Add non-webapp template directory
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "core.wsgi.application"

# Apex Contact for Production Errors
ADMINS = [("Development Team", "dev@civiwiki.org")]

STATIC_URL = "/static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "core/templates/static"),)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"

# TODO: re-organize and simplify staticfiles settings
if "CIVIWIKI_LOCAL_NAME" not in os.environ:
    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

# Use DATABASE_URL in production
DATABASE_URL = os.getenv("DATABASE_URL")

if DATABASE_URL is not None:
    DATABASES = {"default": DATABASE_URL}
else:
    # Default to sqlite for simplicity in development
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": BASE_DIR + "/" + "db.sqlite3",
        }
    }

# Email Backend Setup
if "EMAIL_HOST" not in os.environ:
    EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
    EMAIL_HOST_USER = "test@civiwiki.org"
else:
    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
    EMAIL_HOST = os.getenv("EMAIL_HOST")
    EMAIL_PORT = os.getenv("EMAIL_PORT")
    EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
    EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
    EMAIL_USE_SSL = True
    DEFAULT_FROM_EMAIL = EMAIL_HOST

# Notification API Settings
NOTIFICATIONS_SOFT_DELETE = True
NOTIFICATIONS_USE_JSONFIELD = True

# Django REST API Settings
DEFAULT_RENDERER_CLASSES = ("rest_framework.renderers.JSONRenderer",)

if DEBUG:
    # Browsable HTML - Enabled only in Debug mode (dev)
    DEFAULT_RENDERER_CLASSES = DEFAULT_RENDERER_CLASSES + (
        "rest_framework.renderers.BrowsableAPIRenderer",
    )

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
    "DEFAULT_RENDERER_CLASSES": DEFAULT_RENDERER_CLASSES,
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.BasicAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
}

# CORS Settings
CORS_ORIGIN_ALLOW_ALL = True

# Custom User model
AUTH_USER_MODEL = "accounts.User"

DEFAULT_AUTO_FIELD = "django.db.models.AutoField"

# Login Logout URLS
LOGIN_URL = "login/"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",  # noqa: E501
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
        "OPTIONS": {
            "min_length": 4,
        },
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {"rich": {"datefmt": "[%X]"}},
    "handlers": {
        "console": {
            "class": "rich.logging.RichHandler",
            "formatter": "rich",
            "level": "WARNING",
            # "filters": ["require_debug_true"],
            "rich_tracebacks": True,
            "tracebacks_show_locals": True,
        }
    },
    "loggers": {"django": {"handlers": ["console"]}},
}

project/core/settings.py
"""
Django settings for civiwiki project.
Darius Calliet May 12, 2016

Production settings file to select proper environment variables.
"""
import os

# False if not in os.environ
DEBUG = os.getenv("DEBUG", False)

# defaults to second value if not found in os.environ
DJANGO_HOST = os.getenv("DJANGO_HOST", "LOCALHOST")

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "TEST_KEY_FOR_DEVELOPMENT")
ALLOWED_HOSTS = [".herokuapp.com", ".civiwiki.org", "127.0.0.1", "localhost", "0.0.0.0"]

INSTALLED_APPS = (
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django_extensions",
    "storages",
    "core",
    "rest_framework",
    "accounts.apps.AccountsConfig",
    "threads",
    "notifications",
    "corsheaders",
    "taggit",
    "categories",
    "notification",
    "debug_toolbar",
)

MIDDLEWARE = [
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

INTERNAL_IPS = [
    "127.0.0.1",
]

CSRF_USE_SESSIONS = (
    True  # Store the CSRF token in the users session instead of in a cookie
)

CORS_ORIGIN_ALLOW_ALL = True
ROOT_URLCONF = "core.urls"

# SSL Setup
if DJANGO_HOST != "LOCALHOST":
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True

# Internationalization & Localization
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "threads/templates/threads"),
            os.path.join(BASE_DIR, "accounts/templates/accounts"),
        ],  # TODO: Add non-webapp template directory
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "core.wsgi.application"

# Apex Contact for Production Errors
ADMINS = [("Development Team", "dev@civiwiki.org")]

STATIC_URL = "/static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "core/templates/static"),)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"

STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

# Use DATABASE_URL in production
DATABASE_URL = os.getenv("DATABASE_URL")

if DATABASE_URL is not None:
    DATABASES = {"default": DATABASE_URL}
else:
    # Default to sqlite for simplicity in development
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": BASE_DIR + "/" + "db.sqlite3",
        }
    }

# Email Backend Setup
if "EMAIL_HOST" not in os.environ:
    EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
    EMAIL_HOST_USER = "test@civiwiki.org"
else:
    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
    EMAIL_HOST = os.getenv("EMAIL_HOST")
    EMAIL_PORT = os.getenv("EMAIL_PORT")
    EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
    EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
    EMAIL_USE_SSL = True
    DEFAULT_FROM_EMAIL = EMAIL_HOST

# Notification API Settings
NOTIFICATIONS_SOFT_DELETE = True
NOTIFICATIONS_USE_JSONFIELD = True

# Django REST API Settings
DEFAULT_RENDERER_CLASSES = ("rest_framework.renderers.JSONRenderer",)

if DEBUG:
    # Browsable HTML - Enabled only in Debug mode (dev)
    DEFAULT_RENDERER_CLASSES = DEFAULT_RENDERER_CLASSES + (
        "rest_framework.renderers.BrowsableAPIRenderer",
    )

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
    "DEFAULT_RENDERER_CLASSES": DEFAULT_RENDERER_CLASSES,
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.BasicAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
}

# CORS Settings
CORS_ORIGIN_ALLOW_ALL = True

# Custom User model
AUTH_USER_MODEL = "accounts.User"

DEFAULT_AUTO_FIELD = "django.db.models.AutoField"

# Login Logout URLS
LOGIN_URL = "login/"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",  # noqa: E501
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
        "OPTIONS": {
            "min_length": 4,
        },
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {"rich": {"datefmt": "[%X]"}},
    "handlers": {
        "console": {
            "class": "rich.logging.RichHandler",
            "formatter": "rich",
            "level": "WARNING",
            # "filters": ["require_debug_true"],
            "rich_tracebacks": True,
            "tracebacks_show_locals": True,
        }
    },
    "loggers": {"django": {"handlers": ["console"]}},
}

project/core/settings.py
diff --git a/.env b/.env
new file mode 100644
index 000000000..0af7c0bbc
--- /dev/null
+++ b/.env
@@ -0,0 +1,5 @@
+# Note: these environment variables are only for local development.
+# Do not use them in production.
+DJANGO_SECRET_KEY=123-secret-for-development
+
+DEBUG=True
diff --git a/.env_sample b/.env_sample
deleted file mode 100644
index b59b35a77..000000000
--- a/.env_sample
+++ /dev/null
@@ -1,15 +0,0 @@
-DJANGO_SECRET_KEY=<django_secret_key>
-
-POSTGRES_HOST=db
-POSTGRES_PORT=5432
-POSTGRES_DB=civiwiki_db
-POSTGRES_USER=civiwiki
-POSTGRES_PASSWORD=civiwiki
-
-
-CIVIWIKI_LOCAL_DB_HOST=db
-CIVIWIKI_LOCAL_NAME=civiwiki_db
-CIVIWIKI_LOCAL_USERNAME=civiwiki
-CIVIWIKI_LOCAL_PASSWORD=civiwiki
-
-DEBUG=True
diff --git a/.gitignore b/.gitignore
index 0f691f14a..c4e862ae8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,7 +6,8 @@ VirtualEnv
 /project/media/* 
 /project/staticfiles/*
 .idea
-.env
+# Note: we use .env for local development
+#.env
 data/
 ### JetBrains template
 # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5a4740cf0..8c2e8bc4f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,11 +2,11 @@
 
 Thank you for your interest in contributing to CiviWiki. There are many ways to contribute, such as by sharing ideas, design, testing, community building, and development.
 
-The following sections outline some common ways to contribue ideas, feature requests, and code.
+The following sections outline common ways to contribute ideas, feature requests, and code.
 
 ## Creating issues
 
-Make sure to search beforehand to see if the issue has been previously reported.
+Make sure to search beforehand to see if the issue has been reported.
 
 The issue tracker should not be used for personal support requests. Please direct those to our [live chat](https://riot.im/app/#/room/#CiviWiki:matrix.org)
 
@@ -26,27 +26,54 @@ A good example should contain:
 
 5. (Optional)Potential solutions to the problem.
 
-A good bug report will help direct developers to solve the problem at hand without wasting time trying to figure out the problem in the first place.
+A good bug report will help developers solve the problem without wasting time trying to figure out the situation in the first place.
 
 ### Feature requests/enhancements
 
-If you have a budding idea or a feature that requires a more community-involved discussion, consider having the development discussion on the [live chat](https://riot.im/app/#/room/#CiviWiki:matrix.org) or create a thread on [loomio](https://www.loomio.org/g/ET40tXUC/openciviwiki). This will allow for a well-thought-out issue that will more likely be in line with the goal of the project.
+If you have a budding idea or a feature that requires a more community-involved discussion, consider having the development discussion on the [live chat](https://riot.im/app/#/room/#CiviWiki:matrix.org) or create a thread on [loomio](https://www.loomio.org/g/ET40tXUC/openciviwiki). This will allow for a well-thought-out issue that will more likely align with the project's goal.
 
 ## Development
 
-The following sections describe how to set up a development environment. Note, we have tried to simplify our development set-up in order to reduce barriers to entry.
+The following sections describe how to set up a development environment. Note we have tried to simplify our development setup to reduce barriers to entry.
 
-### Install requirements
+### First, claim an issue
+
+:warning: When contributing code, please make sure you claim any related issue before opening a pull request. You can claim an issue by adding a comment like "I'd like to work on this issue." Then, we will be able to assign you to the issue so other developers know which tasks have been claimed.
+
+### Install Poetry with .env support
 
 We now use Poetry for Python package management. Please follow the [Poetry installation instructions](https://python-poetry.org/docs/#installation) before trying the following steps.
 
-To install all required modules, complete the following steps.
+Once Poetry is installed, enable Poetry `.env` support by running the following command. This will set all variables defined in the `.env` file when activating the virtual environment.
+
+```sh
+poetry self add poetry-dotenv-plugin
+```
+
+### Install requirements
+
+Once Poetry is installed, complete the following steps to install all required modules.
 
 1. Make sure you are in the repository root directory
 2. Initialize the virtual environment with Poetry: `poetry install`
-3. Change into project directory
 
-Now that you are in the project directory, you can continue the following sections of this guide.
+### Activate virtual environment
+
+To develop the project, activate the virtual environment with the following command.
+
+```sh
+poetry shell
+```
+
+### Change into the project directory
+
+Once you have installed the project dependencies and activated the virtual environment, change into the project directory.
+
+```sh
+cd project/
+```
+
+Once you are in the project directory, you can continue the following sections of this guide.
 
 ### Install pre-commit
 
@@ -66,15 +93,15 @@ python manage.py migrate
 
 ### Collect static files
 
-Certain resources, such as CSS and JavaScript files, need to be served from a static directory. Run the following command to collect static files for Django to serve:
+Resources, such as CSS and JavaScript files, need to be served from a static directory. Run the following command to collect static files for Django to serve:
 
 ```py
 python manage.py collectstatic
 ```
 
-### Create super user
+### Create a super user
 
-You will need a super user in order to log in and manage CiviWiki:
+You will need a super user to log in and manage CiviWiki:
 
 ```py
 python manage.py createsuperuser
@@ -82,7 +109,7 @@ python manage.py createsuperuser
 
 ### Populate initial data
 
-During the first setup, it's useful to import hardcoded initial entries. In this case, there are two fixtures:
+During the first setup, it's helpful to import hardcoded initial entries. In this case, there are two fixtures:
 
 * Sample threads, located in `project/data/sample_threads.json`
 * Sample categories, located in `project/data/categories.json`
@@ -110,7 +137,7 @@ python manage.py runserver
 
 ### Run unit tests
 
-Execute unit tests by running the following command from within the `project` directory.
+Execute unit tests by running the following command within the `project` directory.
 
 ```sh
 python manage.py test
@@ -118,7 +145,7 @@ python manage.py test
 
 ### Register initial user (optional)
 
-Once CiviWiki is running, visit the front page (probably something like http://localhost:8000). Once there, click 'log in/register', and then 'register new user'.
+Once CiviWiki runs, visit the front page (probably something like http://localhost:8000). Once there, click "login/register" and then "register new user."
 
 ## Deployment
 
@@ -126,21 +153,21 @@ The [deployment instructions for Heroku](https://github.com/CiviWiki/OpenCiviWik
 
 ## Coding Conventions
 
-We strive to follow Django Coding Conventions. See https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/
+We strive to follow [Django Coding Conventions](https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/).
 
 ## Compatible Versioning
 
-We use Compatibile Versioning in this project.
+We use Compatible Versioning in this project.
 
 Given a version number MAJOR.MINOR, increment the:
 
-MAJOR version when you make backwards-incompatible updates of any kind
-MINOR version when you make 100% backwards-compatible updates
-Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR format.
+MAJOR version when you make backward-incompatible updates of any kind
+MINOR version when you make 100% backward-compatible updates
+Additional pre-release and build metadata labels are available as MAJOR extensions.MINOR format.
 
-### How is this different to SemVer?
+### How is this different from SemVer?
 
-Compatible Versioning ("ComVer") is SemVer where every PATCH number is 0 (zero). This way, ComVer is backwards compatible with SemVer.
+Compatible Versioning ("ComVer") is SemVer, where every PATCH number is 0 (zero). This way, ComVer is backward compatible with SemVer.
 
 A ComVer release from 3.6 to 3.7 is just a SemVer release from 3.6.0 to 3.7.0. In other words, ComVer is safe to adopt since it is basically SemVer without ever issuing PATCH releases.
 
diff --git a/project/core/settings.py b/project/core/settings.py
index a9af92eef..41147f7fd 100644
--- a/project/core/settings.py
+++ b/project/core/settings.py
@@ -107,9 +107,7 @@
 MEDIA_ROOT = os.path.join(BASE_DIR, "media")
 MEDIA_URL = "/media/"
 
-# TODO: re-organize and simplify staticfiles settings
-if "CIVIWIKI_LOCAL_NAME" not in os.environ:
-    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
+STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
 
 # Use DATABASE_URL in production
 DATABASE_URL = os.getenv("DATABASE_URL")

Update grammar in contributing guide
### Idea summary

Improve the grammar in our contributing guide with an automated grammar checker.

### Further details

_No response_
