Proibido (403) Verificação CSRF falhou. Pedido cancelado.

Estou dando deploy em um projeto pelo raillway, no servidor de testes “localhost” ele roudou normal, porém agora no deploy está dando erro 403 Verificação CSRF falhou. Pedido cancelado.

"""
DESENVOLVIDO POR MINATO-BAN
Django settings for configurações project.

Generated by 'django-admin startproject' using Django 4.2.6.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
import os


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '###'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['https://web-production-8187.up.railway.app']
CSRF_TRUSTED_ORIGINS = ['https://web-production-8187.up.railway.app']



# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'páginas',
    'controledeacesso',
    'treinamentos',
    'documentos',
    'relatorios',
    'users',
    'rh',
]


AUTH_USER_MODEL = 'users.CustomUser'



MIDDLEWARE = [
    "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.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'arquivos' 
        ],
        '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 = 'configurações.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'pt-BR'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')


# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_REDIRECT_URL = 'principal'
LOGIN_URL = 'login'
LOGOUT_REDIRECT_URL = 'login'

— From Google translate —

Forneça mais detalhes sobre sua aplicação. Onde você está recebendo esse erro? (Que visualização ou página está gerando isso?)

Você está usando visualizações e modelos padrão do Django ou um front-end JavaScript?

Você seguiu todas as etapas documentadas em How to use Django’s CSRF protection | Django documentation | Django ?

Nota lateral: as entradas ALLOWED_HOSTS não especificam o esquema. (Seria 'web-production-8187.up.railway.app' e não 'https://web-production-8187.up.railway.app'.)

— The original English —

Please provide more details about your application. Where are you getting this error? (What view or page is generating it?)

Are you using the standard Django views and templates, or are you using a JavaScript front end?

Have you followed all of the steps documented at How to use Django’s CSRF protection | Django documentation | Django ?

Side note: The ALLOWED_HOSTS entries don’t specify the scheme. (It would be 'web-production-8187.up.railway.app' and not 'https://web-production-8187.up.railway.app'.)

"Every time I try to login to my application, this error appears. I’m using a custom user and a custom user manager

class CustomUserManager(UserManager):
    pass

class CustomUser(AbstractUser):
    PATENTES = (
        ('Marinheiro', 'Marinheiro'),
        ('Cabo', 'Cabo'),
        ('Aluno', 'Aluno'),
        ('3° Sargento', '3° Sargento'),
        ('2° Sargento', '2° Sargento'),
        ('1° Sargento', '1° Sargento'),
        ('SubOficial', 'SubOficial'),
        ('Cadete', 'Cadete'),
        ('Aspirante-a-Oficial', 'Aspirante-a-Oficial'),
        ('Guarda-Marinha', 'Guarda-Marinha'),
        ('Segundo-Tenente', 'Segundo-Tenente'),
        ('Primeiro-Tenente', 'Primeiro-Tenente'),
        ('Capitão-Tenente', 'Capitão-Tenente'),
        ('Capitão-de-Corveta', 'Capitão-de-Corveta'),
        ('Capitão-de-Fragata', 'Capitão-de-Fragata'),
        ('Capitão-de-Mar-e-Guerra ⭐', 'Capitão-de-Mar-e-Guerra ⭐'),
        ('Contra-Almirante ⭐⭐', 'Contra-Almirante ⭐⭐'),
        ('Vice-Almirante ⭐⭐⭐', 'Vice-Almirante ⭐⭐⭐'),
        ('Almirante-de-Esquadra ⭐⭐⭐⭐', 'Almirante-de-Esquadra ⭐⭐⭐⭐'),
        ('Almirante ⭐⭐⭐⭐⭐', 'Almirante ⭐⭐⭐⭐⭐'),
        ('Conselheiro', 'Conselheiro'),
    )
    STATUS = (
        ('Ativo','Ativo'),
        ('Demitido','Demitido'),
        ('Aposentado','Aposentado'),
    )
    patente = models.CharField(choices=PATENTES,max_length=50, null=True)
    status = models.CharField(choices=STATUS, max_length=50, null=True)
    datapromo = models.DateField(("Última Promoção"),default=timezone.now, null=True)
    responsavel = models.TextField(("Responsável pela promoção"), null=True)
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        validators=[RegexValidator(
            regex=r'^[a-zA-Z0-9@_:.,-]+$',
            message=_('Enter a valid username. This value may contain only letters (uppercase and lowercase), numbers, @, :, -, and _ characters.'),
            code='invalid_username',
        )],
        help_text=_('150 characters or fewer. Letters (uppercase and lowercase), digits, @, :, -, and _ only.'),
    )

    def __str__(self):
        return f"{self.username} ({self.patente})"

Are you using a custom template for the login form? If so, please post it here.

When posting code or templates here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then the code (or template), then another line of ```. (I’ve taken the liberty of adding this to your post above.)

class LoginViewModificada(LoginView):
    template_name = 'templates/login.html'
    authentication_form = LoginForm

class LoginForm(AuthenticationForm):
    username = forms.CharField(label='Nickname',widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(label='Senha',widget=forms.PasswordInput(attrs={'class': 'form-control'}))


{% load static %}

<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Marinha do Brasil - Login</title>
    <link rel="icon" type="image/x-icon" href="{% static "img/MarBrs.ico" %}"> 
    <link rel="stylesheet" href="{% static 'boostr/bootstrap.min.css' %}">
    <script src="{% static 'boostr/js/bootstrap.min.js' %}"></script>
</head>
<body>
    <section class="vh-100" style="background: rgb(0,73,137);
    background: linear-gradient(90deg, rgba(0,73,137,1) 0%, rgba(0,73,137,1) 35%, rgba(0,73,137,1) 100%);">
        <div class="container py-5 h-100">
          <div class="row d-flex justify-content-center align-items-center h-100">
            <div class="col-10 col-md-6 col-lg-6 col-xl-4">
              <div class="card shadow-2-strong" style="border-radius: 1rem;">
                <div class="card-body p-5">
                  <div class="container text-center">
                    <img width="100px" src="{% static 'img/MarBrs.png' %}" alt="Marinha do Brasil">
                    <h5>Acesse ao fazer login!</h5>
                  </div>
                  <br>
                    <form method="post">
                        {% csrf_token %}
                        <div class="form-group">
                          {{ form.as_p }}
                        <div class="text-center">
                        <button style="background: rgb(0,73,137);
                        background: linear-gradient(90deg, rgba(0,73,137,1) 0%, rgba(0,73,137,1) 35%, rgba(0,73,137,1) 100%);" type="submit" class="ms-2 mt-3 btn btn-primary btn-lg col-12">Login</button>
                      </div>
                    </div>
                      </form>
      
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
</body>
</html>

vou tentar fazer o host de uma aplicação só com o painel de adm, caso funcione vou ir implementando aos poucos o código da outra até achar o que causou o erro

Não acho que seja o aplicativo, acho que é alguma interação entre o servidor e o projeto. (Você pode tentar fazer login no administrador para ver se a mesma coisa acontece. Se isso acontecer, isso demonstra que o problema não é com seu aplicativo, formulário, modelo ou visualização.)

Posso tentar adicionar 'https://*.up.railway.app' a CSRF_TRUSTED_ORIGINS. Se isso não funcionar, tentarei adicionar 'https://*.railway.app'. (Isso é apenas algo para tentar - não deveria ser necessário fazer isso, mas não conheço ferrovia para saber o que mais procurar.)

— And the original English —

I don’t think it’s the app at all, I think it’s some interaction between the server and the project. (You can try logging into the admin to see if the same thing happens. If it does, that demonstrates that the problem is not with your app, form, template, or view.)

I might try adding 'https://*.up.railway.app' to CSRF_TRUSTED_ORIGINS. If that doesn’t work, then I’d try adding 'https://*.railway.app'. (This is just something to try - it shouldn’t be necessary to do this, but I don’t know railway to know what else to look for.)

the problem is the railway, i testing other simples aplication, not working admin painel