You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Google认证模板标签未渲染问题求助

问题

访问网站时,页面直接显示模板原始代码 <a href="{% provider_login_url 'google' %}?next=/">Login with google</a>,而非可点击的登录链接。尝试将settings.py中的SITE_ID从1改为2,未解决问题。

相关模板文件内容

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Django Google signin</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
       {% load socialaccount %}
       <h2>Google Login</h2>
       <a href="{% provider_login_url 'google' %}?next=/">Login with google</a>
    </body>
</html>

settings.py配置

"""
Django settings for transcendence project.

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

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

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

from pathlib import Path

# 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/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-$$gm@ghswh(&c&$kq6oj-3rxf(2+5-zg$jwo0=&49pzgdi7@u2'

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

ALLOWED_HOSTS = []


# Application definition

SITE_ID=1

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'auth_system',
    "django.contrib.sites",
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
]

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "SCOPE": [
            "profile",
            "email",
        ],
        "AUTH_PARAMS": {"access_type": "online"},
        "OAUTH_PKCE_ENABLED": True,
    }
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    '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',
    'allauth.account.middleware.AccountMiddleware',
]

ROOT_URLCONF = 'transcendence.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'transcendence.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/5.1/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/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = 'static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

AUTHENTICATION_BACKENDS = {
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend"
}

LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
解决方案

模板标签未被解析,本质是Django没有处理模板中的模板语法,按以下步骤排查:

  • 检查视图渲染方式
    确保视图使用django.shortcuts.render而非HttpResponse直接返回模板内容。正确示例:

    from django.shortcuts import render
    
    def login_view(request):
        return render(request, 'login.html')
    

    若用open读取模板文件再返回HttpResponse,Django不会解析模板标签,必须用render或TemplateResponse。

  • 确认模板文件后缀
    模板文件必须以.html结尾,不能用.txt或其他后缀,否则Django可能跳过模板语法解析。

  • 验证模板加载路径

    • 如果模板放在项目根目录的templates文件夹,需在TEMPLATES的DIRS中添加路径:
      TEMPLATES = [
          {
              # ...其他配置
              'DIRS': [BASE_DIR / 'templates'],
              # ...
          }
      ]
      
    • 如果模板放在app的templates文件夹(如auth_system/templates),确保APP_DIRS设为True,且对应app已加入INSTALLED_APPS。
  • 重启开发服务器
    修改settings或模板后,重启Django开发服务器,确保配置生效。


内容的提问来源于stack exchange,提问作者Arrow Stuhl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:27:00