首页 > 解决方案 > Django - 对于帐户中子目录 /snippets 中的 html - TemplateDoesNotExist at /friend_request/user_id/

问题描述

如果未在 settings.py 的 TEMPLATES 中分配模板目录,我将面临一个非常常见的错误

问题在于,应用程序整体正常工作,当我想访问子目录中的 .html 文件时,我收到错误“TemplateDoesNotExist at /friend_request/user_id/”。

这里的 Settings.py 模板

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'accounts/templates/accounts')],
    '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',
        ],
    },
},

]

我分配了正确的上下文,被传递到包含指向我的friend_requests.html 子目录/snippets 文件的链接的sociel.html 文件

这里是views.py中的视图

def friend_requests(request, *args, **kwargs):
context = {}
user = request.user
user_id = None
friend_requests = None
if user.is_authenticated:
    user_id = user.pk
    account = Account.objects.get(pk=user_id)
    if account == user:
        friend_requests = FriendRequest.objects.filter(receiver=account, is_active=True)
        context['friend_requests'] = friend_requests
    else:
        return HttpResponse("You can't ciew another users fried requests.")
else:
    redirect("login")
return render(request, "friend_requests.html", context)

这里是social.html中的参考

<a href="{% url 'friend_requests' 'user_id' %}"><p id="rd_contact">Requests</p></a>

urls.py 中的引用如下所示

path('friend_request/<user_id>/', views.friend_requests, name='friend_requests'),

关于我的目录结构。

|templates
 |accounts
  |snippets
   |friend_request.html
  |social.html(containing link to friend_request

当我将friend_request.html 上移一个目录,进入accounts 目录时,链接有效,我得到了我想要的页面。但是对于结构,我想在子目录中使用friend_request.html。

所以问题不是,我给social.html的变量不起作用,而是链​​接没有在包含friend_request.html的子目录中搜索

我希望这能说明我的意图。

views.py 中的变量是硬编码的,但也可以通过 {% url 'friend_requests' user.pk %} 访问但由于我有另一个重定向(“登录”),如果没有用户经过身份验证,这个整数应该通过意见.py

if user.is_authenticated:
    user_id = user.pk
    ...
else:
    redirect("login")

我已经在 stackflow 上找到了一个描述类似问题的贡献,但没有回答我的问题

标签: pythondjango

解决方案


好的,我解决了这个问题。答案通常是微不足道的。我已经尝试将子目录片段包含到我的返回渲染中,如下所示:

return render(request, "snippets/friend_requests.html", context)

但这没有用。最后,我只需要包含我的应用模板顶部的整个路径。像这样:

return render(request, "accounts/snippets/friend_requests.html", context)

感谢所有对此问题发表评论的人!


推荐阅读