即使在设置中进行了配置,Django也找不到我的模板目录?
我正在尝试为 django 邮件模块使用 HTML 模板。我当前的问题是我收到此错误:
django.template.exceptions.TemplateDoesNotExist
当我尝试在我的应用程序中渲染 HTML 时,调用users:
html = render_to_string('email/email_confirm.html', context)
这是我的文件夹布局,我的应用程序称为用户,我的项目设置位于/core. 我的模板位于 BASE_DIR。
这是我在设置中的模板代码:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
如何让 Django 正确找到模板文件夹?我已经连接了所有应用程序并且数据工作正常。这严格来说是模板路径问题。
编辑:我保留了我的APP_DIRS= True 并将模板/电子邮件文件夹移动到用户应用程序文件夹中。
django 还是找不到模板?
这是有问题的 View.py:
class CustomUserCreate(APIView):
permission_classes = [AllowAny]
def post(self, request, format='json'):
serializer = CustomUserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
if user:
# GENERATE EMAIL CONFIRMATION TOKEN
user_data = serializer.data
user = User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
# GENERATE EMAIL CONFIRMATION TEMPLATE
current_site = get_current_site(request).domain
relative_link = reverse('users:email-verify')
# CHANGE TO HTTPS in PRODUCTION
absurl = 'http://'+current_site+relative_link+"?token="+str(token)
email_body = 'Hi '+ user.username+', Please use link below to verify your email n' + absurl
context = {
'name': user.first_name,
}
html = render_to_string('email/email_confirm.html', context)
text = render_to_string(email_body, context)
data = {'to_email':user.email,
'email_subject': 'Verify your email',
'email_body':email_body,
'message':text,
'html_message':html
}
Util.send_email(data)
return Response(user_data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
编辑 2:首先我尝试这样做:
template = get_template('email/email_confirm.html', { 'name': user.first_name})
我得到TypeError: unhashable type: 'dict'了上述错误。
然后我把它转过来这样做:
absurl = 'http://'+current_site+relative_link+"?token="+str(token)
email_body = 'Hi '+ user.username+', Please use link below to verify your email n' + absurl
context = {
'name': user.first_name,
}
template = get_template('email/email_confirm.html')
email = render_to_string(template, context)
data = {'to_email':user.email,
'email_subject': 'Verify your email',
'email_body':email_body,
'html_message':email
}
Util.send_email(data)
这导致此错误:
raise TypeError(f'{funcname}() argument must be str, bytes, or '
TypeError: join() argument must be str, bytes, or os.PathLike object, not 'Template'
最终编辑:
data = {'to_email':user.email,
'email_subject': 'Please Verify Your Email',
'email_body':email_body,
'html_message':html
}