> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Host Django Applications

> Learn how to create and host Django applications on Square Cloud.

export const PortNote = ({lang}) => {
  if (lang == 'pt-br') {
    return <Note>
            <b>Qual porta devo usar para o meu servidor?</b><br />
            Você deve usar a porta <b>80</b> para o seu servidor. A porta 80 é a porta padrão para tráfego HTTP; a Square Cloud a encaminha para 443 (HTTPS) para estabelecer uma conexão segura.<br />
            Certifique-se de configurá-la antes de compactar e enviar seu projeto.
        </Note>;
  }
  return <Note>
            <b>What port should I use for my server?</b><br />
            You should use port <b>80</b> for your server. Port 80 is the default port for HTTP traffic, which is handled by Square Cloud to route it to 443, HTTPS, for a secure connection.<br />
            Make sure to configure it before compressing and uploading your project.
        </Note>;
};

export const PyDepFiles = ({lang}) => {
  const desc = {
    "pt-br": {
      requirements: "Arquivo padrão usado em projetos Python para listar todas as bibliotecas externas e dependências necessárias para o seu projeto. Cada linha neste arquivo especifica um pacote a ser instalado usando o pip, o gerenciador de pacotes do Python",
      pyproject: "Um arquivo de configuração moderno para projetos Python que permite especificar requisitos do sistema de compilação e metadados do projeto. É utilizado por ferramentas como o Poetry para gerenciar dependências e empacotamento."
    },
    en: {
      requirements: "Standard file used in Python projects to list all the external libraries and dependencies that your project needs. Each line in this file specifies a package to be installed using pip, the Python package manager.",
      pyproject: "A modern configuration file for Python projects that can specify build system requirements and project metadata. It is used by tools like Poetry to manage dependencies and packaging."
    }
  };
  return <CardGroup cols={2}>
            <Card title="requirements.txt" icon="file-lines" href="../../articles/how-to-create-your-requirements">
            {desc[lang].requirements}
            </Card>
            <Card title="pyproject.toml" icon="file" href="../../articles/how-to-create-your-pyproject">
            {desc[lang].pyproject}
            </Card>
        </CardGroup>;
};

export const RecommendedPlan = ({lang, plan, tier, cpu, appType}) => {
  const url = `https://squarecloud.app/${lang}/pay?plan=${plan.toLowerCase()}&tier=${tier}`;
  if (lang == 'en') {
    return <Note>
        <b>Wondering how much RAM and CPU your plan needs to host {appType}?</b><br />
        Don't worry, we're here to help.
        Our <a href={url}>{plan}</a> plan offers <b>{tier}GB</b> of RAM and <b>{cpu}vCPU</b>, which should be sufficient for most {appType}. 
        However, if you are working on a larger project and seeking extra stability, we recommend considering our <b>Pro</b> plan. With additional resources, you can maintain stability even during demand spikes. 
        To purchase, simply click <a href="https://squarecloud.app/en/pay?plan=pro">here</a>.
      </Note>;
  } else {
    return <Note>
          <b>Está se perguntando quanta RAM e CPU seu plano precisa para hospedar {appType}?</b><br />
          Não se preocupe, estamos aqui para ajudar.
          Nosso plano <a href={url}>{plan}</a> oferece <b>{tier}GB</b> de RAM e <b>{cpu}vCPU</b>, o que deve ser suficiente para a maioria dos {appType}.
          No entanto, se você estiver trabalhando em um projeto maior e precisar de mais estabilidade, recomendamos considerar nosso plano <b>Pro</b>.
          Com recursos adicionais, você pode manter a estabilidade mesmo durante picos de demanda.
          Para comprar, basta clicar <a href={`https://squarecloud.app/${lang}/pay?plan=pro`}>aqui</a>.
        </Note>;
  }
};

export const appType_0 = "a Django application"

## Introduction

To develop and host {appType_0} on Square Cloud, it's essential to follow a structured sequence of configurations and prerequisites. This technical guide will cover the entire process, from initial setup to production deployment.

### Prerequisites

* **Square Cloud Account**: Register through the [signup page](https://squarecloud.app/en/signup) using your email.
* **Active Paid Plan**: Ensures dedicated resources and optimized performance for your application. Check our [available plans](https://squarecloud.app/en/pricing) and choose the most suitable for your needs.

<RecommendedPlan appType="Django applications" plan="Standard" tier="4" cpu="4" lang="en" />

## Creating project

To create a Django application, you need to have Python and pip installed on your system before following the steps.

### Installing library

With Python and pip installed, you can create a new Django project. First, install Django using pip:

```bash theme={null}
pip install django
```

### Developing project

Create a new Python file (e.g., `app.py`) and add the following code to create a basic Django application:

```python app.py theme={null}
from django.conf import settings
from django.http import HttpResponse
from django.urls import path
from django.core.wsgi import get_wsgi_application

# Basic Django settings
settings.configure(
    DEBUG=False,                # Disable debug mode
    SECRET_KEY='mysecretkey',   # Define your secret key
    ALLOWED_HOSTS=['*'],        # Allow all hosts for simplicity
    ROOT_URLCONF=__name__,      # Set the root URL configuration to this module
    MIDDLEWARE_CLASSES=(),      # Use an empty tuple to disable middleware
)

# Simple view
def index(request):
    return HttpResponse("Hello world!")  # Return a simple HTTP response

# URL configuration
urlpatterns = [
    path('', index),  # Map the root URL to the index view
]

# WSGI application
application = get_wsgi_application()

# WSGI server
if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    httpd = make_server('', 80, application)  # Serve the application using WSGI server on port 80
    print("Django server running on port 80...")
    httpd.serve_forever()  # Start the server
```

In the code above, we created a basic route that returns "Hello, World!" when accessed. The application is configured to run on port 80, which is the default port for HTTP traffic.

Next, we need to create our dependencies file. In Python we have requirements.txt or a pyproject.toml

<PyDepFiles lang="en" />

## Choosing a production server

Django's built-in development server is not suitable for production use. Instead, we recommend using a production-ready WSGI server like Gunicorn.

<CardGroup cols={1}>
  <Card title="Gunicorn" icon="unicorn" href="/en/tutorials/python/how-to-use-gunicorn">
    Gunicorn is a Python WSGI HTTP server for UNIX. It's a pre-fork worker model, which means that it forks multiple worker processes to handle requests.
    This makes it a great choice for running python web applications in production.
  </Card>
</CardGroup>

## Deploying

After preparing your project files, you can now upload them to Square Cloud and host your project.
To do so, create a ZIP file containing all your project files.

<Note>
  If you have a Django project that needs to apply migrations, make sure to apply them before deploying to Square Cloud.\
  You can do this by running the following command in your local environment:

  ```bash theme={null}
  python manage.py migrate
  ```
</Note>

<PortNote lang="en" />

### Via dashboard

<Steps>
  <Step title="Access the Upload Page">
    Access the [upload page](https://squarecloud.app/en/dashboard/new) and upload your project zip file.
  </Step>

  <Step title="Configure Your Environment">
    After uploading your zip, you will need to configure the name, main file or runtime environment and other settings for your project.\
    If you are uploading a web project, make sure to select "Web Publication" and set a subdomain to your project.
  </Step>

  <Step title="Deploy Your Project">
    Finally, click on the "Deploy" button to host your project on Square Cloud.\
    After deployment, you can monitor your project's status and logs from the dashboard.

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/dashboard/uploading.gif" alt="Uploading application to Square Cloud" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>
</Steps>

### Via CLI

To use this method, you need to create a config file named `squarecloud.app` in the root directory of your project. This file will contain the necessary configuration for your project.

<Card title="Learn more about: how to create the configuration file for Square Cloud." icon="link" href="/en/getting-started/config-file">
  The squarecloud.app file is a configuration file that will be used to configure your application; it will be used to define your environment.
</Card>

<Steps>
  <Step title="Install the CLI">
    First, you need to have the CLI installed in your environment. If you don't have it yet, run the following command in your terminal:

    ```
    npm install -g @squarecloud/cli
    ```

    If you already have it, we recommend updating it. To do this, run the following command in your terminal:

    <Tabs>
      <Tab title="Windows">
        ```bash theme={null}
        squarecloud update
        ```
      </Tab>

      <Tab title="Linux, macOS, and WSL">
        ```bash theme={null}
        curl -fsSL https://cli.squarecloud.app/install | bash
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Authenticate">
    Now, to authenticate and use other CLI commands, you will find your authorization key [here](https://squarecloud.app/en/account/security) by clicking on "Request API Key". After obtaining your authorization key, run the following command:

    ```bash theme={null}
    squarecloud auth login
    ```
  </Step>

  <Step title="Upload Your Project">
    Finally, to deploy your application to Square Cloud using the CLI, you need to run the following command:

    ```bash theme={null}
    squarecloud upload 
    ```

    Or if you created the zip manually, you can use:

    ```bash theme={null}
    squarecloud upload --file <path/to/zip> 
    ```
  </Step>
</Steps>

## Additional Resources

For more information about Django and its tools, visit the [official Django documentation](https://docs.djangoproject.com/en/5.0/).
There, you will find detailed guides, tutorials, and API documentation to help you make the most of Django.

## Troubleshooting

<CardGroup cols={1}>
  ### Custom Domain

  <Card horizontal>
    To use a custom domain (e.g., `mysite.com`) instead of the default URL `mysite.squareweb.app`, you need the **Standard plan or higher**. The subdomain is defined by the **SUBDOMAIN** field in the configuration file. See: [How to set up your custom domain](https://docs.squarecloud.app/en/tutorials/platform/custom-domain).
  </Card>

  ### Minimum RAM Requirements

  <Card horizontal>
    **Minimum: 512MB RAM** for simple websites/APIs. For sites with frameworks (Next.JS, React, Vue, Angular, etc.), we always recommend **at least 1GB RAM**. For larger applications, allocate more RAM to prevent the application from running out of memory and crashing.
  </Card>

  ### Could not find this site.

  <Card horizontal>
    Check if the **subdomain/domain** matches what's configured in the **SUBDOMAIN** field or in the **custom domain settings**. If you just uploaded the site, wait up to **60 seconds** for Square to enable **first access**.

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/cloudflare/en/unauthorized.webp" alt="Cloudflare site not found error" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Card>

  ### Site took too long to respond...

  <Card horizontal>
    Check if you correctly configured **port 80** and **host 0.0.0.0** in the application. We recommend using Square's forced environment variables: **PORT** and **HOST** from the `.env` file.

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/cloudflare/en/timeout.webp" alt="Cloudflare request timeout error" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Card>
</CardGroup>

## Contact us

If you continue facing **technical difficulties**, our **specialized support team** is available to assist you. [**Contact us**](https://squarecloud.app/en/support) and we'll be happy to help you resolve any issue.
