# Welcome to ShipWithDjango Documentation

{% hint style="info" %}
**Please note:** We are currently updating and extending our documentation. If you have any questions, and your package includes support,[ you can contact us here](https://shipwithdjango.com/contact/).
{% endhint %}

Welcome to the ShipWithDjango Documentation, your comprehensive guide to getting started with our powerful Django boilerplate.

ShipWithDjango is designed to revolutionize the way you build and deploy web applications. Tired of repeating the same tedious tasks? Frustrated with managing boilerplate code and debugging errors? With ShipWithDjango, you can focus on what really matters: turning your ideas into reality.

**Why ShipWithDjango?**\
Our boilerplate takes care of the heavy lifting, offering a robust foundation built on Django’s best practices. Whether you’re launching a simple website or developing a complex platform, ShipWithDjango streamlines your development process, helping you ship faster, with less code, and more confidence. It’s equipped with everything you need—from user authentication and payment integration to real-time features and background tasks—all ready out of the box.

**What Can You Build with ShipWithDjango?**\
ShipWithDjango is perfect for a wide range of projects. Whether you're working on an e-commerce site, a SaaS platform, or a custom web application, our boilerplate provides the tools and structure needed to bring your project to life. With features like two-factor authentication, dynamic document creation, async support, and much more, you can build secure, scalable, and high-performance applications effortlessly.

**Get Started Quickly**\
ShipWithDjango is all about ease and efficiency. Our boilerplate includes easy configuration options, containerized development with Docker, and an intuitive admin panel, so you can hit the ground running. Plus, with integrated logging, background tasks, and AI-powered creativity tools, you’ll have everything you need to develop, deploy, and manage your web applications seamlessly.

**Cut the code, ship the product.** Let ShipWithDjango handle the rest.

Dive into the documentation to learn more about how ShipWithDjango can accelerate your development process and help you deliver exceptional web applications with confidence.


# When and How to use ShipWithDjango?

### When to Use ShipWithDjango

ShipWithDjango is ideal for developers looking to accelerate their development process without sacrificing flexibility or control. Whether you're building a simple web application or a complex platform, ShipWithDjango provides a strong foundation that can be tailored to suit your specific needs.

#### Scenarios Where ShipWithDjango Shines:

1. **Starting a New Project**: If you're starting a new Django project and want to avoid spending time on repetitive setup tasks, ShipWithDjango offers a pre-configured environment that handles authentication, API management, and front-end styling out of the box.
2. **Scaling an Existing Project**: For projects that need to scale quickly, ShipWithDjango's integration with tools like Django REST Framework, Stripe, and Tailwind CSS ensures that your application can grow without becoming unmanageable.
3. **Building Secure Applications**: ShipWithDjango comes with built-in security features like token-based authentication, two-factor authentication, and secure secret management, making it a great choice for applications where security is a priority.
4. **Prototyping and MVPs**: If you're working on a prototype or minimum viable product (MVP), ShipWithDjango allows you to get up and running quickly, giving you more time to focus on refining your core features.

### How to Use ShipWithDjango

#### A Solid Foundation for Your Project

ShipWithDjango is designed to be a robust starting point for your project, providing a solid base that is still fully customizable. Here’s how you can leverage it:

1. **Start with a Strong Base**: Out of the box, ShipWithDjango provides everything you need to get started—user authentication, API setup, responsive front-end design, and more. This strong foundation allows you to focus on building the unique features of your application rather than getting bogged down by setup and configuration.
2. **Customize to Your Needs**: Although ShipWithDjango provides a lot of functionality out of the box, it is designed to be fully customizable. You can easily modify the configuration files to change the look and feel of your application, adjust the API behavior, or integrate additional tools and services.
3. **Extend and Build**: Think of ShipWithDjango as the foundation upon which you build your own house. You can add new features, integrate third-party services, and scale your application as needed. The boilerplate is designed to grow with your project, ensuring that it remains maintainable as it becomes more complex.
4. **Leverage Built-in Utilities**: Make use of the pre-built utilities for user management, payment processing, and logging to streamline your development process. These tools are designed to save you time and reduce the amount of repetitive code you need to write.

#### Summary

ShipWithDjango is a powerful tool that helps you start strong, build fast, and scale with confidence. By providing a solid foundation that is still entirely customizable, it allows you to focus on what makes your application unique while taking care of the essential elements of web development. Whether you're building a small app or a large-scale platform, ShipWithDjango is the ideal starting point for your Django projects.


# Obtaining a license

To obtain a license for ShipWithDjango, please visit our pricing page at <https://shipwithdjango.com/pricing/>.

Here, you can explore the different licensing options available and choose the one that best suits your needs.


# Downloading ShipWithDjango

In this section, we'll walk you through the simple steps to access and download your version of ShipWithDjango. Let’s get started!

#### 1. Check Your Email for Your Login Credentials

After purchasing ShipWithDjango, you should receive an email containing your login credentials. This email will include your username and a temporary password. If you don't see the email in your inbox, be sure to check your spam or junk folder. Once you have your credentials, you're ready to access your dashboard.

#### 2. Access Your Dashboard

With your login credentials in hand, navigate to the ShipWithDjango dashboard at <https://shipwithdjango.com/swd/authentication/login/>.&#x20;

Enter your username and password to log in. The dashboard is your central hub for managing your downloads and accessing support (if your plan includes this).

<figure><img src="/files/wUDie0M6Kk1FIOYQq7YB" alt=""><figcaption></figcaption></figure>

#### 3. Download Your Chosen Version

Once you’re logged in to your dashboard, you’ll see a section for downloading ShipWithDjango. Select the version of the boilerplate that suits your project needs. Click the download button, and your file will be ready shortly. After downloading, you can start setting up your project and begin development immediately.

And that's it! You're now ready to start using ShipWithDjango to build and deploy your web applications efficiently.


# Running locally

## First-time setup

Follow these simple instructions to get your development environment up and running smoothly.

#### 1. Unpack the Zip File to Your Desired Directory

After downloading ShipWithDjango, locate the zip file in your downloads folder. Unzip the file and move the contents to the directory where you want to set up your project. This will be your project’s root directory.

#### 2. Open Up a Terminal Inside the Directory

Once the files are unpacked, open your terminal (or command prompt) and navigate to the directory where you placed the ShipWithDjango files. This will be your working directory for the following commands.

#### 3. Make Sure Your Docker Is Running

Before proceeding, ensure that Docker is installed and running on your machine. Docker is essential for containerizing and managing the services required by ShipWithDjango. If Docker isn't running, start it now.

#### 4. Execute "docker compose build"

In your terminal, run the command:

```
docker compose build
```

This command will build the Docker containers needed for your project. It may take a few minutes as it pulls and compiles the necessary images and dependencies. Once completed, your environment will be ready to go.

#### 5. Execute "docker compose up"

After the build process is finished, start the containers by running:

```
docker compose up
```

This will start all the services required by ShipWithDjango, including the web server, database, and any background processes. Wait for all services to boot up properly; you’ll see logs in the terminal indicating that everything is running smoothly.

#### 6. Open Up a New Terminal in the Same Directory

While keeping the services running, open a new terminal in the same directory. In this terminal, you’ll need to set up the database by running the following commands:

```
docker compose exec django python manage.py makemigrations
docker compose exec django python manage.py migrate
```

This step will create and migrate the database schema required for your application. **You only need to do this the first time you set up your project.**

#### 7. Navigate to <http://127.0.0.1:8000/>

Once all services are up and running, open your web browser and navigate to <http://127.0.0.1:8000/>. You should see the default ShipWithDjango homepage, confirming that your local environment is set up correctly.

## Running the next times

Once you have completed the initial setup, running your project in the future is straightforward. Anytime you want to start your local development environment, simply navigate to the project directory in your terminal and execute the following command:

```
docker compose up
```

This will start all the necessary services and bring your application online. There’s no need to repeat the setup steps—you’re good to go with just this single command!

Congratulations! You’re now running ShipWithDjango locally and ready to start building your project.


# Next steps

Now that you've got ShipWithDjango up and running, it is time to customize it and fit it to your needs.

ShipWithDjango is designed with flexibility in mind, allowing you to tailor your project to your specific needs through a series of well-organized configuration files. These files are easy to maintain and focus on different aspects of your application, ensuring that customization is both straightforward and efficient.

All configuration files are located in the `CONFIG` directory within the root of your project.

A lot of these configuration files will also take in environment variables which you can define in the provided `.env`.  ShipWithDjango also comes with secure secret management so you don't need to keep sensitive information in a file located on your server or local device. [Find more about which providers you can integrate with here.](/secret-management/third-party-providers)

The next sections will walk you through all the configuration options and how to leverage them to create your product in no-time.


# Default Configuration

The platform defaults configuration in ShipWithDjango allows you to define key details about your application, such as its name, tagline, version, and URL. These settings are managed in the `CONFIG/platform.py` file and help establish the foundational identity of your project.

### Configuration Options

#### Platform Name

The `PLATFORM_NAME` setting defines the name of your application. This name will be used across the application, such as in the header, email templates, and other areas where the application name is displayed.

```python
PLATFORM_NAME = _('Ship With Django')
```

You can change this to any name that best represents your project.

#### Platform Tagline

The `PLATFORM_TAGLINE` is a short, descriptive phrase that accompanies your platform name. It provides a quick insight into what your application does or represents.

```python
PLATFORM_TAGLINE = _('A Django Boilerplate')
```

Feel free to update this tagline to reflect the unique value proposition of your application.

#### Platform Version

The `PLATFORM_VERSION` setting specifies the current version of your application. This is useful for tracking releases and ensuring that users and developers are aware of the version they are working with.

```python
PLATFORM_VERSION = "1.0.0"
```

Update this version number as you release new versions of your platform.

#### Platform URL

The `PLATFORM_URL` setting defines the base URL where your application is hosted. This is important for generating links, references in emails, and other areas where the full URL of your application is needed.

```python
PLATFORM_URL = "http://127.0.0.1:8000"
```

Be sure to update this URL to reflect the actual domain where your platform will be deployed.


# Subnavigation

In ShipWithDjango, the subnavigation menu that users see when logged into the platform is fully customizable through a configuration file, eliminating the need to modify template files directly. This approach provides a flexible and centralized way to manage the navigation structure across your application.

The subnavigation configuration is defined in the `CONFIG/subnavigation.py` file. This file outlines the different sections and items that will appear in the user's subnavigation menu, allowing you to control what options are available based on the user's role or other conditions.

### Example Subnavigation Configuration

Here’s a breakdown of how the example subnavigation configuration is structured:

```python
from django.utils.translation import gettext_lazy as _
from django.conf import settings

GLOBAL_SUBNAV = [
    {
        'key' : 'default',
        'name' : _('Default'),
        'show_title' : False,
        'is_active' : True,
        'items' : [{
            'key': 'dashboard',
            'name': _('Dashboard'),
            'url_name' : 'main:dashboard',
            'icon': 'circle',
            'is_active': True,
        },
        {
            'key': 'adminpanel',
            'name': _('Adminpanel'),
            'url_name' : 'admin:index',
            'icon': 'hexagon',
            'is_active': True,
            'superuser_required': True,
        },
        ]
    },
    {
        'key' : 'account_settings',
        'name' : _('Account settings'),
        'show_title' : True,
        'is_active' : True,
        'items' : [{
            'key': 'billing',
            'name': _('Billing'),
            'url_name' : 'billing:manage_billing',
            'icon': 'credit-card',
            'is_active': True,
        },
        {
            'key': 'settings',
            'name': _('Settings'),
            'url_name' : 'authentication:user_settings',
            'icon': 'settings',
            'is_active': True,
        },
        {
            'key': 'logout',
            'name': _('Logout'),
            'url_name' : 'authentication:logout',
            'icon': 'log-out',
            'is_active': True,
        }]
    }
]
```

#### Structure and Components

1. **Subnavigation Sections**:
   * The `GLOBAL_SUBNAV` list contains dictionaries, each representing a section in the subnavigation menu.
   * Each section has a `key`, `name`, and other properties like `show_title` (controls if the section title is displayed) and `is_active` (determines if the section is active and visible).
2. **Menu Items**:
   * Each section contains an `items` list, which holds individual menu items.
   * Each item is defined by a `key`, `name`, `url_name` (the named URL pattern for the link), `icon` (the icon displayed next to the item), and `is_active`.
   * Some items, like the "Adminpanel," can have additional properties such as `superuser_required`, which restricts access to superusers.

#### Customizing the Subnavigation

To customize the subnavigation for your application:

1. **Add or Modify Sections**:
   * You can add new sections or modify existing ones by editing the `GLOBAL_SUBNAV` list. Define new sections with unique `key` values and populate them with relevant `items`.
2. **Customize Menu Items**:
   * Within each section, you can customize the menu items by changing their `name`, `url_name`, and `icon`. You can also control their visibility with `is_active` or restrict access to certain roles, like superusers, using additional flags.
3. **Dynamic Subnavigation**:
   * Utilize conditional logic to dynamically include subnavigation sections based on the presence of specific apps or conditions within your project.


# Tailwind CSS

ShipWithDjango leverages Tailwind CSS, a popular utility-first CSS framework, to help you create modern, responsive, and highly customizable user interfaces. Tailwind CSS is designed to make it easy to build visually consistent and adaptable designs directly in your HTML, without having to write custom CSS from scratch.

### What is Tailwind CSS?

Tailwind CSS is a utility-first CSS framework that provides a wide range of low-level CSS classes, allowing you to build custom designs without ever leaving your HTML. Instead of writing custom CSS or relying on predefined component classes, Tailwind gives you the building blocks to create your own designs with precision and flexibility.

For example, instead of writing a custom CSS rule to add padding to an element, you can use one of Tailwind's utility classes like `p-4` directly in your HTML. This approach enables rapid development and ensures that your designs are consistent across your application.

### Pros of Using Tailwind CSS

#### 1. **Rapid Development**

* **Utility-First Approach**: Tailwind's utility-first approach allows you to style elements directly in your HTML, eliminating the need for writing custom CSS. This can significantly speed up the development process, especially for prototyping and building out interfaces quickly.
* **Responsive Design**: Tailwind makes it easy to create responsive designs with built-in utility classes for different screen sizes. You can apply different styles for mobile, tablet, and desktop views without writing media queries manually.

#### 2. **Consistency**

* **Design Consistency**: By using Tailwind’s predefined classes, you ensure that the styling across your application is consistent. This reduces the chances of visual discrepancies that often occur when different developers work on the same project.
* **Avoiding Specificity Wars**: Tailwind’s utility classes are designed to be low in specificity, which helps you avoid issues with CSS specificity and overrides that can occur with traditional CSS methodologies.

#### 3. **Customization**

* **Configurable**: Tailwind is highly customizable. You can configure the framework to match your design system by modifying the Tailwind configuration file. This allows you to set custom colors, spacing, fonts, and more, tailored specifically to your project.
* **Extendable**: Tailwind's configuration can be extended with custom utility classes, components, or even plugins, providing flexibility to adapt the framework to your unique needs.

#### 4. **Performance**

* **Optimized for Production**: Tailwind CSS is designed to generate a minimal CSS file by purging unused classes in production builds. This results in smaller file sizes, faster loading times, and better performance for your application.

#### 5. **Community and Ecosystem**

* **Vibrant Community**: Tailwind CSS has a large and active community, which means you have access to a wealth of resources, including tutorials, plugins, and third-party components.
* **Tailwind UI**: Tailwind Labs offers Tailwind UI, a collection of professionally designed, pre-built components that can be easily integrated into your project, further speeding up development.

#### 6. **Integration with ShipWithDjango**

* **Seamless Integration**: ShipWithDjango comes with Tailwind CSS pre-integrated, so you can start using it right out of the box. This integration ensures that your front-end development process is streamlined and consistent with the overall architecture of your project.

### Learn More About Tailwind CSS

To get the most out of Tailwind CSS, it's helpful to familiarize yourself with the wide range of utility classes available and the best practices for using them. Here are some resources where you can learn more:

* **Official Tailwind CSS Documentation**: The [Tailwind CSS Documentation](https://tailwindcss.com/docs) is the best place to start. It provides comprehensive guides, examples, and API references for all Tailwind features.
* **Utility Classes**: You can explore the full list of [utility classes](https://tailwindcss.com/docs/utility-first) available in Tailwind CSS to see how you can style elements directly in your HTML.
* **Tailwind CSS Play**: Use the [Tailwind CSS Play](https://play.tailwindcss.com/) tool to experiment with Tailwind classes and build designs in a live environment. It's a great way to see how different classes work together.
* **Community Resources**: The Tailwind CSS community is very active, and you can find a wealth of additional resources, tutorials, and components on platforms like GitHub, YouTube, and Tailwind’s own [community page](https://tailwindcss.com/community).


# Configuration

ShipWithDjango uses Django Tailwind to seamlessly integrate Tailwind CSS into your Django project. This integration allows you to take full advantage of Tailwind's utility-first approach to styling while ensuring that it works smoothly within the Django ecosystem. For more detailed information on Django Tailwind, you can refer to the official documentation [here](https://django-tailwind.readthedocs.io/en/latest/).

The main configuration for Tailwind CSS in a ShipWithDjango project is located in `theme/static_src/tailwind.config.js`. This file allows you to customize Tailwind to better suit your project's design needs.

### Example Configuration

Here’s an example of a minimal `tailwind.config.js` file, along with explanations of the different configuration options:

```javascript
javascriptCopy code/**
 * This is a minimal config.
 *
 * If you need the full config, get it from here:
 * https://unpkg.com/browse/tailwindcss@latest/stubs/defaultConfig.stub.js
 */

module.exports = {
    content: [
        /**
         * HTML. Paths to Django template files that will contain Tailwind CSS classes.
         */
        
        /*  Templates within theme app (<tailwind_app_name>/templates), e.g. base.html. */
        '../templates/**/*.html',

        /*
         * Main templates directory of the project (BASE_DIR/templates).
         * Adjust the following line to match your project structure.
         */
        '../../templates/**/*.html',

        /*
         * Templates in other django apps (BASE_DIR/<any_app_name>/templates).
         * Adjust the following line to match your project structure.
         */
        '../../**/templates/**/*.html',

        /**
         * JS: If you use Tailwind CSS in JavaScript, uncomment the following lines and make sure
         * patterns match your project structure.
         */
        /* JS 1: Ignore any JavaScript in node_modules folder. */
        '!../../**/node_modules',
        /* JS 2: Process all JavaScript files in the project. */
        '../../**/*.js',

        /**
         * Python: If you use Tailwind CSS classes in Python, uncomment the following line
         * and make sure the pattern below matches your project structure.
         */
        '../../**/*.py'
    ],
    theme: {
        screens: {
            'xxs': '320px', // Added 'xxs' screen size
            'xs': '480px', // Added 'xs' screen size
            'sm': '640px',
            'md': '768px',
            'lg': '1024px',
            'xl': '1280px',
        },
        extend: {
            colors: {
                'default' : {
                    'DEFAULT': '#11181C',
                },
                'primary' : {
                    'DEFAULT': '#35b54a',
                    'light' : '#e1fde1',
                },
                'secondary' : {
                    'DEFAULT' : '#090e15',
                },
                'card' : {
                    'DEFAULT': '#141826',
                },
                'success' : {
                    'DEFAULT': '#22c55e',
                    'light': '#dcfce7',
                    'dark' : '#14532d',
                },
                'warning' : {
                    'DEFAULT': '#f97316',
                    'light' : '#ffedd5',
                    'dark' : '#7c2d12',
                },
                'error' : {
                    'DEFAULT': '#ef4444',
                    'light' : '#fee2e2',
                    'dark' : '#7f1d1d',
                }
            }
        },
    },
    plugins: [
        /**
         * '@tailwindcss/forms' is the forms plugin that provides a minimal styling
         * for forms. If you don't like it or have own styling for forms,
         * comment the line below to disable '@tailwindcss/forms'.
         */
        require('@tailwindcss/forms'),
        require('@tailwindcss/typography'),
        require('@tailwindcss/aspect-ratio'),
    ],
}
```

#### Configuration Options

**1. Content**

The `content` array defines the paths to all the files where Tailwind CSS classes will be used. This is crucial for the PurgeCSS feature, which removes unused CSS classes from the final build, making the output CSS file smaller and more efficient.

* **Django Templates**: Specify the paths to your Django template files, ensuring that Tailwind processes these files and includes the necessary classes in the final CSS.
* **JavaScript Files**: If you use Tailwind classes in your JavaScript, you can include those paths here to ensure that Tailwind picks up all the necessary classes.
* **Python Files**: If you use Tailwind classes in Python strings (e.g., in views or forms), you can include Python files as well.

**2. Theme**

The `theme` section allows you to customize the default Tailwind design system, including breakpoints, colors, fonts, and more.

* **Screens**: This defines custom screen sizes for responsive design. In the example, additional screen sizes (`xxs` and `xs`) are added for finer control over small screens.
* **Extend**: This is where you can extend the default Tailwind theme. For example, you can add custom colors that match your brand or project design.
  * **Colors**: Custom colors like `primary`, `secondary`, `success`, `warning`, and `error` are defined, which can then be used throughout your application to maintain a consistent color scheme. For example, you can use the class `bg-primary` to set the primary color as background or `text-secondary` to set the secondary color as text color. This way you can easily change the whole color scheme of your application with just a few config changes.

**3. Plugins**

Tailwind CSS comes with several official plugins that add more functionality to the framework. The example configuration includes:

* **`@tailwindcss/forms`**: Provides basic form styling. This can be commented out if you prefer to style forms manually.
* **`@tailwindcss/typography`**: Adds beautiful typographic defaults for rich text content.
* **`@tailwindcss/aspect-ratio`**: Provides utilities for controlling the aspect ratio of elements.

These plugins enhance the utility of Tailwind CSS and help you avoid writing repetitive CSS for common tasks like form styling and typography.

### Customizing Tailwind CSS

You can further customize Tailwind CSS by modifying this configuration file to fit your project's needs. Whether you need to add more breakpoints, define new color schemes, or extend the framework with plugins, this configuration file is your starting point.

For a more detailed configuration and additional options, you can refer to the full Tailwind CSS configuration stub [here](https://unpkg.com/browse/tailwindcss@latest/stubs/defaultConfig.stub.js).

By customizing the Tailwind configuration, you can ensure that your project maintains a consistent and unique design language that is tailored specifically to your needs.


# Default Configuration

By default, ShipWithDjango is configured to use the `env` secrets manager, which reads secrets from the `.env` file located in the root of your project. While this approach works for development and testing, it's recommended to switch to one of the external providers listed above for production environments to enhance security.

You can find the config file at `CONFIG/secrets.py`

```python
SECRETS_MANAGER = 'env'  # Default secrets manager
```


# Setting your environment variables

Below is an example of what your `.env` file might look like:

```plaintext
DB_HOST=postgres
DB_NAME=shipwithdjango
DB_PASSWORD=Abc123!!
DB_USER=postgres
DB_PORT=5432

DEBUG=True

EMAIL_HOST=smtp.office365.com
EMAIL_PORT=587
EMAIL_HOST_USER=example@example.com
EMAIL_HOST_USER_NAME="Example Name"
EMAIL_HOST_PASSWORD=examplepassword
EMAIL_USE_TLS=True
SENDGRID_API_KEY=your_sendgrid_api_key_here

REDIS_HOST=redis

SECRET_KEY=your_secret_key_here

STRIPE_LIVE_MODE=False
STRIPE_PUBLIC_API_KEY=your_stripe_public_key_here
STRIPE_SECRET_API_KEY=your_stripe_secret_key_here
STRIPE_WEBHOOK_SECRET=your_stripe_webhook_secret_here
STRIPE_TEST_PUBLIC_API_KEY=your_stripe_test_public_key_here
STRIPE_TEST_SECRET_API_KEY=your_stripe_test_secret_key_here
STRIPE_TEST_WEBHOOK_SECRET=your_stripe_test_webhook_secret_here

OPENAI_API_KEY=your_openai_api_key_here
```

It is not necessary to modify all these variables at once. You can update them as needed based on the specific requirements of your application. Below is a breakdown of the key sections and what each set of environment variables controls.

### Database

These variables define the connection details for your application's database:

* `DB_HOST`: The hostname of your database server. If using Docker, this should be set to `postgres`, matching the service name in the Docker Compose file.
* `DB_NAME`: The name of the database your application will use.
* `DB_USER`: The username for accessing the database.
* `DB_PASSWORD`: The password for the database user.
* `DB_PORT`: The port number on which your database server is listening (default is 5432 for PostgreSQL).

### Debug

The `DEBUG` variable controls the debugging mode of your application:

* `DEBUG`: Set this to `True` during development to enable detailed error pages and logs. **Important: Set this to `False` before deploying your application to production to prevent exposure of sensitive information.**

### Email

These variables configure your application's email delivery settings:

* `EMAIL_HOST`: The SMTP server your application will use to send emails.
* `EMAIL_PORT`: The port on which the SMTP server is running.
* `EMAIL_HOST_USER`: The username for the SMTP server.
* `EMAIL_HOST_USER_NAME`: The name that will appear in the "From" field of outgoing emails.
* `EMAIL_HOST_PASSWORD`: The password for the SMTP server.
* `EMAIL_USE_TLS`: Whether to use TLS for secure email transmission (`True` or `False`).
* `SENDGRID_API_KEY`: If using SendGrid for email, set your API key here.

If using SMTP, ensure that the `EMAIL_HOST`, `EMAIL_PORT`, `EMAIL_HOST_USER`, `EMAIL_HOST_USER_NAME`, and `EMAIL_HOST_PASSWORD` are configured.&#x20;

For SendGrid, use `EMAIL_HOST_USER`, `EMAIL_HOST_USER_NAME`, and `SENDGRID_API_KEY`.

### Redis

The `REDIS_HOST` variable specifies the address of your Redis instance:

* `REDIS_HOST`: If using Docker, set this to `redis`, which matches the service name in the Docker Compose file.

### Secret Key

The `SECRET_KEY` is a critical component for the security of your Django application:

* `SECRET_KEY`: This should be a unique, secret key used for cryptographic signing. You can generate a strong secret key [here](https://djecrety.ir/).

### Stripe

To enable payment processing and subscription management, configure the following Stripe-related environment variables:

* `STRIPE_LIVE_MODE`: Set to `True` to enable live mode, or `False` for testing.
* `STRIPE_PUBLIC_API_KEY`: Your public Stripe API key for live mode.
* `STRIPE_SECRET_API_KEY`: Your secret Stripe API key for live mode.
* `STRIPE_WEBHOOK_SECRET`: The webhook secret for Stripe in live mode.
* `STRIPE_TEST_PUBLIC_API_KEY`: Your public Stripe API key for test mode.
* `STRIPE_TEST_SECRET_API_KEY`: Your secret Stripe API key for test mode.
* `STRIPE_TEST_WEBHOOK_SECRET`: The webhook secret for Stripe in test mode.

Ensure these variables are correctly set to integrate Stripe into your application effectively.<br>

### OpenAI

To enable OpenAI capabilities, set the `OPENAI_API_KEY` to your key.

By configuring these environment variables, you can fine-tune how ShipWithDjango operates, ensuring it meets your project's specific needs.


# Third-party providers

Managing sensitive information securely is one of the most critical aspects of any application. In ShipWithDjango, ensuring that your secrets—such as API keys, database passwords, and other confidential data—remain private and confidential is a top priority.

To help you keep your secrets safe, ShipWithDjango offers integration with several secret management providers:

* [**Infisical**](/secret-management/third-party-providers/infisical): A user-friendly, free-to-use secret management solution.
* [**AWS Secrets Manager**](/secret-management/third-party-providers/aws-secrets-manager): A robust and scalable service for managing secrets in the AWS ecosystem.
* [**Azure Key Vault**](/secret-management/third-party-providers/azure-key-vault): A secure cloud service for storing and accessing secrets in Microsoft Azure.


# Infisical

Infisical is a modern, user-friendly secret management platform designed to securely store and manage sensitive information such as API keys, passwords, and other confidential data. It helps developers and teams protect their secrets by providing a centralized, secure environment where these secrets can be stored and accessed as needed. Infisical offers features like real-time synchronization, environment-specific secrets, and seamless integration with popular development tools and workflows.

For more detailed information, you can visit the [Infisical website](https://infisical.com/).

Infisical is a great starting point, especially since it’s free and easy to use. To configure Infisical as your secrets manager, update the following settings:

```python
SECRETS_MANAGER = 'infisical'
INFISICAL_PROJECT_ID = None  # Your Infisical project ID
INFISICAL_CLIENT_ID = None  # Your Infisical client ID
INFISICAL_CLIENT_SECRET = None  # Your Infisical client secret
INFISICAL_ENVIRONMENT = None  # The environment (e.g., 'production', 'development')
```


# AWS Secrets Manager

AWS Secrets Manager is a secure and scalable service provided by Amazon Web Services (AWS) that helps you protect access to your applications, services, and IT resources without the upfront complexity of managing your own secret infrastructure. It allows you to securely store, manage, and retrieve sensitive information such as database credentials, API keys, and other secrets. AWS Secrets Manager integrates seamlessly with other AWS services, making it an ideal choice if you are already using AWS infrastructure, as it simplifies the management and rotation of secrets within your existing environment.

For more detailed information, you can visit the [AWS Secrets Manager page](https://aws.amazon.com/secrets-manager/).

To use AWS Secrets Manager, ensure you have the following settings configured:

```python
SECRETS_MANAGER = 'aws'
AWS_SECRET_NAME = None  # The name of the secret in AWS Secrets Manager
AWS_ACCESS_KEY_ID = None  # Your AWS access key ID
AWS_SECRET_ACCESS_KEY = None  # Your AWS secret access key
AWS_REGION = None  # The AWS region where your secrets are stored
```


# Azure Key Vault

Azure Key Vault is a cloud-based service provided by Microsoft Azure that allows you to securely store and manage sensitive information such as encryption keys, certificates, and secrets like API keys and passwords. It provides a centralized and secure environment for managing access to this confidential data while offering built-in tools for key rotation and auditing. Azure Key Vault integrates seamlessly with other Azure services, making it an excellent choice for organizations already using the Azure infrastructure, as it simplifies the management and protection of secrets within your existing ecosystem.

For more detailed information, you can visit the [Azure Key Vault page](https://azure.microsoft.com/en-us/services/key-vault/).

For Azure Key Vault, configure the following variables:

```python
SECRETS_MANAGER = 'azure'
AZURE_CLIENT_ID = None  # Your Azure client ID
AZURE_TENANT_ID = None  # Your Azure tenant ID
AZURE_CLIENT_SECRET = None  # Your Azure client secret
AZURE_KEY_VAULT_NAME = None  # The name of your Azure Key Vault
```


# Order of retrieval

The secrets manager in ShipWithDjango follows a specific order when retrieving secrets:

1. **Cache**: First, it checks its cache to see if the secret has already been retrieved during the current session.
2. **Environment File**: Next, it looks in the `.env` file. If the secret is found there, it returns that value.
3. **External Provider**: If the secret is not found in the cache or the `.env` file, the manager will then query the configured external secret management service (Infisical, AWS, or Azure).

This layered approach allows you to easily override secrets for local development or testing by simply adding them to your `.env` file, while still benefiting from the security of an external provider in other environments.


# Default Configuration

The authentication settings for ShipWithDjango are highly configurable, allowing you to control user registrations and enable or disable third-party logins with ease. These settings are managed through the `CONFIG/authentication.py` file, where you can adjust the configuration to suit your project’s needs.

Here’s a breakdown of the default configuration and how you can customize it:

```python
ALLOW_REGISTRATIONS = True

# Third-party login
# Global setting. If this is disabled, all third-party login will be disabled.
# This setting needs to be set to True to enable ANY individual third-party login.
ALLOW_THIRD_PARTY_LOGIN = False

# LinkedIn
ALLOW_LINKED_IN_LOGIN = False
LINKED_IN_CLIENT_ID = None
LINKED_IN_CLIENT_SECRET = None

# Github
ALLOW_GITHUB_LOGIN = False
GITHUB_CLIENT_ID = None
GITHUB_CLIENT_SECRET = None
```

### Registrations

The `ALLOW_REGISTRATIONS` setting controls whether new users can sign up for your application. If you set `ALLOW_REGISTRATIONS` to `False`, the signup page will be blocked, preventing any new registrations. This can be useful for maintaining a closed or invite-only platform.

### Third-Party Logins

ShipWithDjango supports third-party logins through GitHub and LinkedIn, offering your users a convenient way to authenticate using their existing accounts.

#### Enabling Third-Party Logins

To enable third-party logins, you first need to set `ALLOW_THIRD_PARTY_LOGIN` to `True`. This global setting must be enabled for any individual third-party login (such as GitHub or LinkedIn) to function. If this is set to `False`, no third-party login options will be available, even if they are individually configured.

#### **Github**

If you want to enable GitHub, you can do so by setting the `ALLOW_GITHUB_LOGIN` to `True`. Before you can integrate with GitHub, you will need to create an application in GitHub that can be used to authenticate with.[ Find out more here.](/authentication/github)

#### **LinkedIn**

If you want to enable LinkedIn, you can do so by setting the `ALLOW_LINKED_IN_LOGIN` to `True`. Before you can integrate with LinkedIn, you will need to create an application in LinkedIn that can be used to authenticate with. [Find out more here.](/authentication/linkedin)


# GitHub

To allow users to sign up and log in using their GitHub accounts, set `ALLOW_GITHUB_LOGIN` to `True`. Additionally, you will need to configure your GitHub application by registering it with GitHub:

1. Visit [GitHub Applications](https://github.com/settings/applications/new) while logged into your GitHub account.
2. Fill in the required details. Make sure the **Authorization callback URL** is set to `https://YOUR_DOMAIN_HERE.COM/swd/accounts/github/login/callback/`.
3. Once your application is created, GitHub will provide you with a **Client ID** and **Client Secret**.
4. Update the `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` in your `CONFIG/authentication.py` config file with these values.


# LinkedIn

To allow users to sign up and log in using their LinkedIn accounts, set `ALLOW_LINKED_IN_LOGIN` to `True`. To configure LinkedIn login:

1. Visit [LinkedIn Developers](https://www.linkedin.com/developers/apps/) while logged into your LinkedIn account and click on **Create app**.
2. Fill in the required details. The **Callback URL** should be set to `https://YOUR_DOMAIN_HERE.COM/swd/accounts/oidc/linkedin/login/callback/`.
3. Once the app is created, LinkedIn will provide a **Client ID** and **Client Secret**.
4. Enter these credentials into the `LINKED_IN_CLIENT_ID` and `LINKED_IN_CLIENT_SECRET` variables in your `CONFIG/authentication.py` config file.


# Default Configuration

ShipWithDjango provides flexible email configuration options, allowing you to choose between using a standard SMTP server or SendGrid for sending emails. The main settings for your email provider are managed through environment variables, ensuring secure and centralized management. However, you can control certain behaviors directly within the `CONFIG/email.py` file.

Here’s a breakdown of the default configuration and how you can customize it:

```python
from shipwithdjango.secrets import secret_manager

# This variable is used to determine which email provider to use
# This can be either normal SMTP or SendGrid.
# If you want to use SendGrid, set this to 'sendgrid' and set the SENDGRID_API_KEY variable.
EMAIL_PROVIDER = 'smtp' # 'smtp' or 'sendgrid'

# If this variable is set to True, sending emails will be done using the task queue (Huey) instead of the main thread.
# This is useful for sending emails asynchronously. If you set this to True, make sure to run the task queue worker.
# If you set this to False, emails will be sent synchronously and the main thread will be blocked until the email is sent.
EMAIL_USE_TASK_QUEUE = True

EMAIL_HOST = secret_manager.get_secret('EMAIL_HOST')
EMAIL_PORT = secret_manager.get_secret('EMAIL_PORT')
EMAIL_HOST_USER_NAME = secret_manager.get_secret('EMAIL_HOST_USER_NAME')
EMAIL_HOST_USER = secret_manager.get_secret('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = secret_manager.get_secret('EMAIL_HOST_PASSWORD')
EMAIL_USE_TLS = secret_manager.get_secret('EMAIL_USE_TLS')
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

SENDGRID_API_KEY = secret_manager.get_secret('SENDGRID_API_KEY')
```


# Using SendGrid

### What is SendGrid?

SendGrid is a cloud-based email service that provides a reliable and scalable way to send and manage email communications. It is widely used by developers and businesses to send transactional emails, marketing campaigns, and other types of email communications. SendGrid offers powerful features such as advanced analytics, email tracking, and customizable email templates, making it an excellent choice for managing large volumes of email with ease.

Key features of SendGrid include:

* **Scalability**: SendGrid can handle sending millions of emails per day, making it ideal for businesses of all sizes.
* **Email Tracking and Analytics**: Detailed reports on email delivery, open rates, click rates, and other metrics help you understand how your emails are performing.
* **Deliverability**: With SendGrid, you can ensure that your emails reach the inbox instead of getting caught in spam filters.
* **API and SMTP Integration**: SendGrid offers both API and SMTP relay options for sending emails, giving you flexibility in how you integrate it with your applications.

For more detailed information, you can visit the [SendGrid website](https://sendgrid.com/en-us).

### Configuring SendGrid in ShipWithDjango

Configuring SendGrid in ShipWithDjango is a straightforward process. Follow these simple steps to set up SendGrid as your email provider:

#### Step 1: Set the Email Provider to SendGrid

In your configuration file, set the `EMAIL_PROVIDER` variable to `'sendgrid'`. This tells ShipWithDjango to use SendGrid for sending emails.

#### Step 2: Configure the Required Variables

Next, you need to set the following environment variables to properly configure SendGrid:

* **`EMAIL_HOST_USER_NAME`**: This is the name that will be displayed in the "From" field of outgoing emails. It could be your company name, your application name, or any other identifier you want recipients to see.
* **`EMAIL_HOST_USER`**: This is the email address that will be used as the sender for outgoing emails. Ensure that this is a verified sender address in your SendGrid account.
* **`SENDGRID_API_KEY`**: This is the API key provided by SendGrid that allows your application to authenticate with their service and send emails. You can generate this key from the SendGrid dashboard under the API Keys section.

#### Example Configuration

```plaintext
EMAIL_PROVIDER=sendgrid
EMAIL_HOST_USER_NAME="Your Company Name"
EMAIL_HOST_USER=your-email@example.com
SENDGRID_API_KEY=your_sendgrid_api_key_here
```

#### Summary

By configuring these settings, ShipWithDjango will use SendGrid to handle all outgoing emails. This setup allows you to take advantage of SendGrid's powerful features, ensuring that your emails are delivered reliably and with advanced tracking capabilities.

For more detailed information on using SendGrid, visit their [official website](https://sendgrid.com/en-us).


# Using SMTP

### What is SMTP?

SMTP (Simple Mail Transfer Protocol) is the standard protocol for sending emails across the Internet. It is a reliable and widely-used method for email transmission, ensuring that emails are correctly routed and delivered to recipients. SMTP works by connecting to an email server and sending the email data, including the message content, sender, recipient, and any attachments.

SMTP is supported by virtually all email clients and services, making it a versatile and essential protocol for sending emails from web applications, such as those built with ShipWithDjango.

### Configuring SMTP in ShipWithDjango

ShipWithDjango uses SMTP by default for sending emails. To configure SMTP as your email provider, follow these steps:

#### Step 1: Set the Email Provider to SMTP

Ensure that the `EMAIL_PROVIDER` variable is set to `'smtp'`. This tells ShipWithDjango to use the SMTP protocol for sending emails.

#### Step 2: Configure the Required Variables

You will need to set the following environment variables to correctly configure the SMTP settings:

* **`EMAIL_HOST`**: The address of the SMTP server you are using to send emails. This could be a service like Gmail, Outlook, or a dedicated SMTP server provided by your hosting provider.
* **`EMAIL_PORT`**: The port number used by the SMTP server. Common ports are `587` for TLS, `465` for SSL, and `25` for non-encrypted connections.
* **`EMAIL_HOST_USER_NAME`**: The name that will appear in the "From" field of outgoing emails. This can be your application name, your company name, or another identifier.
* **`EMAIL_HOST_USER`**: The username used to authenticate with the SMTP server. This is usually the email address you are sending emails from.
* **`EMAIL_HOST_PASSWORD`**: The password for the SMTP server. This is required for authenticating the user account.
* **`EMAIL_USE_TLS`**: Set this to `True` to use TLS (Transport Layer Security) for secure email transmission. TLS is recommended for protecting the integrity and privacy of your emails.

#### Example Configuration

```plaintext
EMAIL_PROVIDER=smtp
EMAIL_HOST=smtp.yourprovider.com
EMAIL_PORT=587
EMAIL_HOST_USER_NAME="Your Company Name"
EMAIL_HOST_USER=your-email@example.com
EMAIL_HOST_PASSWORD=your_password_here
EMAIL_USE_TLS=True
```

#### Summary

SMTP is a reliable and standard protocol for sending emails, and ShipWithDjango supports it out of the box. By configuring the appropriate environment variables, you can easily set up SMTP to handle your application's email needs. Whether you're sending transactional emails, notifications, or newsletters, SMTP provides a robust foundation for email delivery.

For most applications, using SMTP is straightforward and secure, especially when combined with TLS to protect your email transmissions.


# Using the task queue for sending emails

ShipWithDjango uses Django Huey to integrate the Huey task queue, allowing you to send emails asynchronously. This means that when an email is sent, the request to send the email is placed in the task queue, and the email is sent in the background by a worker process. This approach ensures that the process of sending emails does not block the main application thread, keeping your application responsive, even under high traffic conditions.

#### Default Configuration

By default, ShipWithDjango is configured to use the task queue for sending emails. This is managed by the `EMAIL_USE_TASK_QUEUE` variable:

* **`EMAIL_USE_TASK_QUEUE=True`**: This is the default and recommended setting. Emails are sent asynchronously using the task queue, which helps maintain the performance and responsiveness of your application.
* **`EMAIL_USE_TASK_QUEUE=False`**: If set to `False`, emails will be sent synchronously on the main thread. This means the application will wait for the email to be sent before continuing with other tasks, which can lead to delays and decreased performance, especially during high traffic periods.

#### When to Disable the Task Queue

While it is generally advisable to keep `EMAIL_USE_TASK_QUEUE` set to `True`, there may be specific scenarios where you want to disable the task queue and send emails synchronously. For example:

* **Debugging**: If you are troubleshooting email sending and need immediate feedback, you might temporarily set `EMAIL_USE_TASK_QUEUE` to `False`.
* **Simplicity**: In very simple or small-scale applications where the overhead of managing a task queue is unnecessary, you might choose to send emails synchronously.

However, if you do choose to disable the task queue, be aware that this can cause delays in the application’s response time, particularly if your application needs to send a large number of emails or if the email server is slow to respond.


# Billing

The billing configuration in ShipWithDjango is highly flexible, allowing you to tailor the payment models to fit your specific needs. This configuration is managed through the `CONFIG/billing.py` file, where you can define how your application handles subscriptions, credits, or both. Below is an overview of the key settings and how to configure them.

### Billing Model

The `BILLING_MODEL` setting determines the payment model your application will use. It can be set to one of the following options:

* **`subscriptions`**: The application uses a subscription model. You need to define subscription plans in the `SUBSCRIPTIONS` list.
* **`credits`**: The application uses a credits model. You need to define credit packages in the `CREDIT_PACKAGES` list.
* **`both`**: The application uses both subscriptions and credits. You need to define both subscription plans and credit packages.
* **`none`**: The application does not use any billing model. Choose this option if you want to provide the service for free.

### Subscription Plans

If your `BILLING_MODEL` is set to `subscriptions` or `both`, you need to define the available subscription plans in the `SUBSCRIPTIONS` list. Each subscription plan is a dictionary with the following keys:

* **`key`**: A unique identifier for the subscription plan.
* **`name`**: The name of the subscription plan displayed to users.
* **`icon`**: The name of a Feather icon associated with the plan.
* **`description`**: A brief description of what the plan offers.
* **`price`**: A dictionary that includes:
  * **`value`**: The monetary value of the subscription.
  * **`currency_symbol`**: The currency symbol for the price (e.g., €, $, £).
* **`stripe_price_id`**: The ID of the Stripe price object, used to create the subscription in Stripe.
* **`show`**: A boolean value indicating whether to display this plan on the pricing page.
* **`lifetime`**: A boolean value indicating if this is a lifetime subscription.
* **`included`**: A list of features included in the plan.
* **`not_included`**: A list of features not included in the plan.

#### Example Subscription Plans

Here are examples of how you might configure different subscription plans:

1. **Free Tier**

   ```python
   {
       'key' : 'default',
       'name' : _('Free tier'),
       'icon' : 'smile',
       'description' : _('For those who want to try out the service before committing'),
       'price' : {
           'value' : 0.00,
           'currency_symbol' : '€',
       },
       'show' : False,
   }
   ```
2. **Lifetime License**

   ```python
   {
       'key' : 'lifetime',
       'name' : _('Lifetime license'),
       'description' : _('Enjoy all the features of the service forever'),
       'icon' : 'thumbs-up',
       'price' : {
           'value' : 299.00,
           'currency_symbol' : '€',
       },
       'stripe_price_id' : 'price_1PKewlRq8MH1iNLlqTtsRHrL',
       'show' : True,
       'lifetime' : True,
       'included': [_('One good thing'), _('One other good thing'), _('And one more good thing')],
       'not_included': [_('One bad thing'), _('One other bad thing'), _('And one more bad thing')],
   }
   ```
3. **Monthly Subscription**

   ```python
   {
       'key' : 'monthly',
       'name' : _('Monthly subscription'),
       'description' : _('Enjoy all the features of the service for a month'),
       'icon' : 'calendar',
       'price' : {
           'value' : 20.00,
           'currency_symbol' : '€',
       },
       'stripe_price_id' : 'price_1PKexCRq8MH1iNLl6Bub67Op',
       'show' : True,
       'lifetime' : False,
       'included': [_('One good thing'), _('One other good thing'), _('And one more good thing')],
       'not_included': [_('One bad thing'), _('One other bad thing'), _('And one more bad thing')],
   }
   ```

### Credit Packages

If your `BILLING_MODEL` is set to `credits` or `both`, you will define credit packages in the `CREDIT_PACKAGES` list. Each credit package is a dictionary with the following keys:

* **`key`**: A unique identifier for the credit package.
* **`name`**: The name of the credit package displayed to users.
* **`icon`**: The name of a Feather icon associated with the package.
* **`description`**: A brief description of what the package offers.
* **`price`**: A dictionary that includes:
  * **`value`**: The monetary value of the credit package.
  * **`currency_symbol`**: The currency symbol for the price.
* **`stripe_price_id`**: The ID of the Stripe price object, used to create the checkout session in Stripe.
* **`show`**: A boolean value indicating whether to display this package on the pricing page.
* **`credits`**: The number of credits provided by the package.

#### Example Credit Packages

Here is an example of how you might configure a credit package:

**10 Credits**

```python
{
    'key' : 'ten_credits',
    'name' : _('10 credits'),
    'description' : _('Get 10 credits to use on the service'),
    'icon' : 'thumbs-up',
    'price' : {
        'value' : 10.00,
        'currency_symbol' : '€',
    },
    'stripe_price_id' : 'price_1PNE60Rq8MH1iNLlO6gf9B55',
    'show' : True,
    'credits' : 10,
}
```

### Configuring Stripe

For both subscription plans and credit packages, the `stripe_price_id` is crucial as it links your plans and packages to Stripe’s payment processing. Make sure to configure these correctly by creating the corresponding prices in your Stripe dashboard.

#### Setting Up Subscription Plans in Stripe

* **Monthly or Annual Subscriptions**: In Stripe, create a "recurring" price and use the generated price ID in the `stripe_price_id` field.
* **Lifetime Subscriptions**: Create a "one-time" price in Stripe and use the generated price ID.

#### Setting Up Credit Packages in Stripe

* For credit packages, create a "one-time" price in Stripe for each package and use the corresponding price IDs.

###


# Stripe

ShipWithDjango integrates seamlessly with Stripe, allowing you to manage payments and subscriptions efficiently. The configuration for Stripe is managed through environment variables, ensuring that sensitive information like API keys and webhook secrets remain secure.

All the necessary configuration settings for Stripe are retrieved from your environment variables, which you can set up as described in the Setting up your environment variables section.

### Configuration Details

Here's an overview of the Stripe configuration settings:

* **Stripe Mode**:
  * `STRIPE_LIVE_MODE` controls whether your application is running in live mode (`True`) or test mode (`False`). This setting determines which API keys and webhook secrets will be used.
* **API Keys**:
  * `STRIPE_LIVE_PUBLIC_KEY` and `STRIPE_LIVE_SECRET_KEY` are used for live transactions.
  * `STRIPE_TEST_PUBLIC_KEY` and `STRIPE_TEST_SECRET_KEY` are used for test transactions in Stripe's sandbox environment.
* **Webhook Secrets**:
  * `STRIPE_LIVE_WEBHOOK_SECRET` is used to verify the authenticity of live webhook events.
  * `STRIPE_TEST_WEBHOOK_SECRET` is used to verify test webhook events.

By correctly configuring these settings, you can confidently handle payments and subscriptions in your application, whether you are in development or live production mode.


# Default Configuration

ShipWithDjango provides the capability to integrate with OpenAI's powerful tools, including DALL-E for generating images from textual descriptions. To use these features, you need to configure your OpenAI API key.

The configuration settings for OpenAI are managed in the `CONFIG/openai.py` file.

### Setting the OpenAI API Key

To enable the integration with OpenAI, you need to set the `OPENAI_API_KEY` variable in your environment variable. This key is essential for authenticating your requests to OpenAI's API, allowing your application to leverage the capabilities of OpenAI models, including DALL-E.

```python
OPENAI_API_KEY = secret_manager.get_secret('OPENAI_API_KEY')
```

[Find out here how you can set your OpenAI API key as an environment variable.](/secret-management/setting-your-environment-variables)

#### Obtaining Your OpenAI API Key

1. **Sign Up or Log In**: If you don't already have an OpenAI account, you'll need to sign up at [OpenAI's website](https://beta.openai.com/signup/). If you have an account, log in.
2. **API Key Access**: Once logged in, navigate to the API section of your account where you can generate a new API key.
3. **Set the API Key**: Copy the generated API key and set it your `OPENAI_API_KEY` environment variable.

#### Using OpenAI and DALL-E in Your Application

Once your API key is configured, your application will be able to interact with OpenAI's services. This includes generating images with DALL-E based on textual input, which can be a powerful feature in various use cases, from creative projects to dynamic content generation.

#### Security Considerations

It's important to keep your OpenAI API key secure. Do not expose this key in public repositories or share it openly. In ShipWithDjango, the `secret_manager` handles the retrieval of sensitive information, such as your API key, ensuring it is stored securely.

### Summary

To enable OpenAI integration in ShipWithDjango:

1. Obtain your OpenAI API key from [OpenAI's website](https://beta.openai.com/signup/).
2. Set the `OPENAI_API_KEY` variable in your environment.
3. Ensure that your API key is kept secure and is not exposed publicly.

With these steps, you can unlock the full potential of OpenAI and DALL-E within your ShipWithDjango project, enabling advanced AI-driven features and capabilities.


# Django REST framework

ShipWithDjango comes with Django REST Framework (DRF) pre-integrated, providing you with a powerful and flexible toolkit for building Web APIs. Django REST Framework is one of the most popular and widely-used libraries for creating APIs in Django, known for its simplicity, flexibility, and robust feature set.

### What is Django REST Framework?

Django REST Framework (DRF) is a powerful toolkit that enables developers to build Web APIs using Django. It provides a comprehensive suite of tools and features that make it easy to serialize data, handle authentication, and manage permissions, among other things. DRF is designed to work seamlessly with Django, allowing you to leverage Django's ORM, views, and URL routing while adding powerful API capabilities.

#### Key Features of Django REST Framework

* **Serializers**: DRF provides powerful serialization tools that convert complex data types, such as querysets and model instances, into Python data types that can then be easily rendered into JSON, XML, or other content types. Serializers also handle data validation and deserialization, making it easy to create and update data via your API.
* **Authentication**: DRF comes with a variety of authentication classes out of the box, including token-based authentication, session-based authentication, and third-party OAuth2 authentication. This flexibility makes it easier to secure your API and manage user access.
* **Permissions**: With DRF, you can define fine-grained permissions to control who can access your API endpoints. Permissions can be set globally or at the individual view level, giving you complete control over API access.
* **Viewsets and Routers**: DRF's viewsets allow you to define common patterns for your views, such as list and detail views, with minimal code. Combined with routers, which automatically generate URL patterns for your API, DRF helps reduce boilerplate code and simplifies API development.
* **Browsable API**: One of the standout features of DRF is its browsable API. When developing your API, DRF automatically generates a web-based interface for testing and interacting with your endpoints. This feature is incredibly useful for both development and debugging.
* **Pagination**: DRF supports pagination out of the box, making it easy to handle large datasets by breaking them into manageable chunks.
* **Throttling**: To protect your API from being overwhelmed by too many requests, DRF includes throttling mechanisms that limit the rate of requests a client can make.

### Pros of Using Django REST Framework

#### 1. **Ease of Use**

* **Integration with Django**: DRF integrates seamlessly with Django, allowing you to reuse your existing Django models, views, and templates while adding API capabilities. This tight integration reduces the learning curve and speeds up development.
* **Browsable API**: The automatic generation of a browsable API interface is a huge productivity booster, enabling developers to test endpoints without needing a separate API client.

#### 2. **Flexibility**

* **Highly Customizable**: DRF is highly customizable, allowing you to tailor authentication, permissions, and serialization to meet the specific needs of your project. Whether you're building a simple API or a complex multi-tiered application, DRF provides the tools you need.
* **Support for Various Content Types**: DRF supports multiple content types, including JSON and XML, giving you the flexibility to serve your API in the format that best suits your application.

#### 3. **Robust Security**

* **Comprehensive Authentication Options**: DRF includes built-in support for various authentication schemes, ensuring your API can be secured according to your requirements.
* **Granular Permissions**: You can control access at a very granular level, ensuring that only the right users have access to sensitive data or functionality.

#### 4. **Community and Ecosystem**

* **Large Community**: Django REST Framework is backed by a large and active community, meaning that you'll find plenty of resources, tutorials, and third-party packages to extend and enhance your API development.
* **Extensive Documentation**: DRF's documentation is comprehensive and well-maintained, making it easy to find answers and best practices as you build your API.

#### 5. **Performance**

* **Optimized for Large Data Sets**: DRF includes built-in tools for handling large data sets efficiently, such as pagination and throttling, ensuring your API remains responsive and performant under load.

### Learn more

For more information, you can explore the official Django REST Framework documentation [here](https://www.django-rest-framework.org/).


# Built-in API utilities

ShipWithDjango comes with several pre-built API utilities to help you quickly get started with building and managing APIs. These utilities are designed to handle common tasks such as user authentication, token management, and retrieving user profile information, ensuring that you have a solid foundation for your API from the start.

### API Structure

The API functionality in ShipWithDjango is located in the `api` folder in the root of your project. This folder contains everything you need to get started with creating and managing API endpoints, including serializers, views, and URLs.

#### User Authentication and Token Management

ShipWithDjango provides built-in endpoints for user authentication using JSON Web Tokens (JWT). The API includes endpoints that allow users to obtain Bearer tokens and refresh tokens, which are essential for securely managing user sessions in your API.

* **Token Obtain Pair Endpoint**: This endpoint allows users to authenticate and receive a pair of tokens: an access token (Bearer token) and a refresh token. The access token is used for authenticating API requests, while the refresh token is used to obtain a new access token when the old one expires.\
  \
  You can find the endpoint at `/api/token/`
* **Token Refresh Endpoint**: This endpoint allows users to refresh their access token using the refresh token. This is crucial for maintaining user sessions without requiring them to re-authenticate frequently.\
  \
  You can find the endpoint at `/api/token/refresh/`

#### User Profile Endpoint

ShipWithDjango also includes an endpoint that allows authenticated users to retrieve their own profile information. This is useful for creating user dashboards, account management pages, or any feature that requires displaying user-specific data.

* **User Profile Retrieval**: The user profile endpoint returns detailed information about the authenticated user, including their email, name, date of registration, and any associated subscription or billing information. This ensures that you can easily access and display the necessary user data in your application.

You can find the endpoint at `/users/me/`


# Postman

We recommend using Postman to test out your API endpoints.

Postman is a popular tool used by developers to test, develop, and document APIs. It provides an intuitive interface for sending HTTP requests to your API endpoints, viewing responses, and organizing your API tests into collections. Postman is widely used for debugging, testing, and monitoring APIs, making it an essential tool for anyone working with APIs.

For more detailed information, you can visit the [Postman website](https://www.postman.com/).

### What is Postman?

Postman is a powerful API testing and development tool that allows you to send HTTP requests to your APIs and see the responses in a clear, organized manner. With Postman, you can interact with your API endpoints, check the correctness of your responses, and ensure that your APIs behave as expected. It's not just limited to manual testing—Postman also offers features for automated testing, API monitoring, and generating API documentation.

#### Key Features of Postman

* **Request Building**: Postman allows you to easily construct HTTP requests by selecting the method (GET, POST, PUT, DELETE, etc.), entering the URL, setting headers, and providing body data. This makes it simple to test different API endpoints with various parameters.
* **Collections**: You can organize your API requests into collections, which are groups of related API calls. Collections can be shared with your team, making collaboration easier and ensuring that everyone is testing the API in a consistent way.
* **Environment Variables**: Postman supports environment variables, which allow you to reuse variables like API keys, URLs, or user tokens across multiple requests. This feature is particularly useful when testing APIs in different environments (development, staging, production).
* **Automated Testing**: With Postman, you can write tests for your API responses using JavaScript. This allows you to automate the testing process, run multiple tests at once, and ensure that your API behaves as expected under various conditions.
* **API Documentation**: Postman can automatically generate API documentation from your collections. This documentation is easy to share and helps ensure that your API is well-documented for other developers.
* **API Monitoring**: Postman offers monitoring tools that allow you to check the health of your APIs over time. You can set up automated tests that run at regular intervals and receive alerts if something goes wrong.


# Default Configuration

ShipWithDjango offers robust logging capabilities by integrating with Sentry and BetterStack, two powerful tools for monitoring, error tracking, and troubleshooting. Proper logging is essential for maintaining the health and performance of your application, helping you to quickly identify and address any issues that arise.

You can learn more about these services here:

* [Sentry](https://sentry.io/welcome/)
* [BetterStack](https://betterstack.com/)

The logging settings are managed in the `CONFIG/logging.py` file, where you can configure the path for local log files and enable integration with Sentry or BetterStack.

### Local Log File

The `LOGFILE_PATH` setting specifies where Django's error logs should be written. By default, logs are stored in the `app.log` file located within the `/logs` directory of your project:

```python
LOGFILE_PATH = 'app.log'  # Path is relative to the /logs directory
```

You can change this path if you need to store logs in a different location or with a different file name.


# Using Sentry

Sentry is a widely used tool for real-time error tracking and performance monitoring. If you want to leverage Sentry in your application, follow these steps:

1. **Enable Sentry**: Set the `USE_SENTRY` variable to `True`.
2. **Configure DSN**: Set the `SENTRY_DSN` variable to the DSN provided by Sentry when you set up your account.

```python
USE_SENTRY = False  # Change to True to enable Sentry
SENTRY_DSN = None  # Set this to your Sentry DSN
```

With Sentry enabled, your application will send error reports and performance data to Sentry, allowing you to monitor your application more effectively.


# Using Better Stack

Better Stack (formerly known as Logtail) is another excellent option for centralized logging and monitoring. To integrate BetterStack with your application:

1. **Enable BetterStack**: Set the `USE_BETTERSTACK` variable to `True`.
2. **Set Source Token**: Set the `BETTERSTACK_SOURCE_TOKEN` variable to the source token provided by BetterStack during setup.

```python
USE_BETTERSTACK = False  # Change to True to enable BetterStack
BETTERSTACK_SOURCE_TOKEN = None  # Set this to your BetterStack source token
```

When BetterStack is enabled, your application will send logs and error data to BetterStack for centralized monitoring and analysis.


# Translations

ShipWithDjango simplifies the process of managing translations through the use of Django Rosetta, a powerful tool that provides a fully functional graphical interface for handling your application's translations. This means you can easily manage your translations without needing to directly edit `.mo` and `.po` files. For more details about Django Rosetta, you can visit the [Django Rosetta documentation](https://django-rosetta.readthedocs.io/).

### Configuration Details

#### Source Language

The `SOURCE_LANGUAGE_CODE` and `SOURCE_LANGUAGE_NAME` settings define the primary language of your application, which serves as the source language for all translations.

```python
SOURCE_LANGUAGE_CODE = 'en-us'
SOURCE_LANGUAGE_NAME = 'English'
```

#### Rosetta Messages Per Page

The `ROSETTA_MESSAGES_PER_PAGE` setting controls how many translation messages are displayed per page in the Rosetta interface. Adjusting this number can help you manage the volume of translations you work with at one time.

```python
ROSETTA_MESSAGES_PER_PAGE = 100
```

#### Translating Languages

* **`ROSETTA_LANGUAGES`**: This setting lists the languages that can be translated from the source language using the admin panel. Note that these languages are only available in the admin panel for translation purposes and are not visible to users on the front end. If you want these languages to be selectable by users, you need to add them to the `LANGUAGES` setting.

  ```python
  ROSETTA_LANGUAGES = []
  ```
* **`LANGUAGES`**: This setting defines the languages available for users to select on the front end of your application. Languages listed here will also be available for translation in the admin panel.

  ```python
  LANGUAGES = [
      ('en-us', 'English')
  ]
  ```

#### Translation Service API Keys

If you use external translation services, ShipWithDjango supports integration with various providers through API keys. These services can assist in automating or improving the accuracy of your translations.

* **Yandex Translate**: Set the `YANDEX_TRANSLATE_KEY` to use Yandex's translation services.
* **Azure Translator**: Set the `AZURE_CLIENT_SECRET` to integrate with Microsoft's Azure Translator service.
* **DeepL**: Set the `DEEPL_AUTH_KEY` to use the DeepL translation service.

```python
YANDEX_TRANSLATE_KEY = None  # See http://api.yandex.com/translate/
AZURE_CLIENT_SECRET = None  # See https://learn.microsoft.com/en-us/azure/ai-services/translator/
DEEPL_AUTH_KEY = None  # See https://www.deepl.com/pro#developerr
```

### Adding More Languages

To add more languages for translation:

1. **For Admin Translation Only**: Add the language codes to `ROSETTA_LANGUAGES`. These languages will be available in the Rosetta interface but not on the front end.

   ```python
   ROSETTA_LANGUAGES = [
       ('es', 'Spanish'),
       ('fr', 'French'),
   ]
   ```
2. **For User Selection**: Add the language codes to `LANGUAGES`. This will make them available both in the Rosetta interface and on the front end for users to select.

   ```python
   LANGUAGES = [
       ('en-us', 'English'),
       ('es', 'Spanish'),
       ('fr', 'French'),
   ]
   ```

###


