模板不存在。 Django寻找错误的路径

Posted

技术标签:

【中文标题】模板不存在。 Django寻找错误的路径【英文标题】:Template does not exist. Django looking for wrong path 【发布时间】:2018-06-16 23:38:15 【问题描述】:

我正在关注 django 教程,但这个错误已经出现了一段时间。我已经将课程代码放在我的旁边,以便对其进行比较以尝试找到错误,但我没有任何运气

TemplateDoesNotExist at /posts/new/
posts/post_form.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/posts/new/
Django Version: 1.11
Exception Type: TemplateDoesNotExist
Exception Value:    
posts/post_form.html
Exception Location: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/template/loader.py in select_template, line 53
Python Executable:  /Users/chrismaltez/anaconda3/envs/simplesocialenv/bin/python
Python Version: 3.5.0
Python Path:    
['/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial',
 '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python35.zip',
 '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5',
 '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/plat-darwin',
 '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/lib-dynload',
 '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages']

Here is the postmortem traceback:

Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

django.template.loaders.filesystem.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/templates/posts/post_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/contrib/admin/templates/posts/post_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/contrib/auth/templates/posts/post_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/bootstrap3/templates/posts/post_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/accounts/templates/posts/post_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/groups/templates/posts/post_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/posts/templates/posts/post_form.html (Source does not exist)

This is the last line of the traceback:

raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) 

据我所知,它可能没有找对地方

-simple_social_clone
--simplesocial
---posts
----templates
-----posts
------post_form.html

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from . import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.HomePage.as_view(), name='home'),
    url(r'^accounts/', include('accounts.urls', namespace='accounts')),
    url(r'^accounts/', include('django.contrib.auth.urls')),
    url(r'^test/$', views.TestPage.as_view(),name='test'),
    url(r'^thanks/$', views.ThanksPage.as_view(),name='thanks'),
    url(r'^posts/', include('posts.urls',namespace='posts')),
    url(r'^groups/', include('groups.urls',namespace='groups')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls))
    ] + urlpatterns

这里是项目级views.py

from django.views.generic import TemplateView

class TestPage(TemplateView):
    template_name = 'test.html'

class ThanksPage(TemplateView):
    template_name = 'thanks.html'


class HomePage(TemplateView):
    template_name = 'index.html'

这是应用级别的views.py

from django.shortcuts import render
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy

from django.http import Http404
from django.views import generic

from braces.views import SelectRelatedMixin
# Create your views here.

from . import models
from . import forms

from django.contrib.auth import get_user_model
User = get_user_model()

class PostList(SelectRelatedMixin,generic.ListView):
    model = models.Post
    select_related = ('user','group')

class UserPosts(generic.ListView):
    model = models.Post
    template_name = 'posts/user_post_list.html'

    def get_queryset(self):
        try:
            self.post.user = User.objects.prefetch_related('posts').get(
                username__iexact=self.kwargs.get('username')
            )
        except User.DoesNotExist:
            raise Http404
        else:
            return self.post_user.posts.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['post_user'] = self.post_user
        return context

class PostDetail(SelectRelatedMixin, generic.DetailView):
    model = models.Post
    select_related = ('user','group')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user__username__iexact=self.kwargs.get('username'))

class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):

    fields = ('message','group')
    model = models.Post

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView):
    model = models.Post
    select_related = ('user','group')
    success_url = reverse_lazy('posts:all')

    def get_queryset(self):
        queryset = super().get_queryet()
        return queryset.filter(user_id = self.request.user.id)

    def delete(self, *args, **kwargs):
        messages.success(self.request,'Post Deleted')
        return super().delete(*args,**kwargs)

这是应用级别的 urls.py:

from django.conf.urls import url

from . import views

app_name = 'posts'

urlpatterns = [

    url(r'^$', views.PostList.as_view(), name='all'),
    # url(r'new/$', views.CreatePost.as_view(),name='create'),
    url(r"new/$", views.CreatePost.as_view(), name="create"),
    url(r'by/(?P<username>[-\w]+)/$', views.UserPosts.as_view(),name='for_user'),
    url(r'by/(?P<username>[-\w]+)/(?P<pk>\d+)/$', views.PostDetail.as_view(),name='single'),
    url(r'delete/(?P<pk>\d+)/$', views.DeletePost.as_view(), name='delete'),
]

这是应用级别的模型:

from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings

import misaka
# Create your models here.

from groups.models import Group
from django.contrib.auth import get_user_model
User = get_user_model()

from django import template
register = template.Library()

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts')
    created_at = models.DateTimeField(auto_now=True)
    #auto generates datetime stamp of post
    message = models.TextField()
    message_html = models.TextField(editable=False)
    #doesnt allow others to edit post
    group = models.ForeignKey(Group, related_name='posts', null=True, blank=True)

    def __str__(self):
        return self.message

    def save(self, *args, **kwargs):
        self.message_html = misaka.html(self.message)
        super().save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse(
            'posts:single',
            kwargs=
                'username':self.user.username,
                'pk':self.pk
            
        )

    class Meta:
        ordering = ['-created_at']
        unique_together = ['user','message']

这里是 post_form.html

% extends 'posts/post_base.html' %
% load bootstrap3 %

% block post_content %
<h4>Create a new Post</h4>
<form id="postForm" action="% url 'posts:create' %" method="POST">
    % csrf_token %
    % bootstrap_form form %
    <input type="submit" value="Post" class="btn btn-primary btn-large">


    </form>


% endblock %

最后是项目模板级别:

enter code here     </div>

    </nav>
    <div class="container mycontent">

        % block content %

        % endblock %


        </div>

</body>
</html>

[][2]

【问题讨论】:

你的项目simplesocialsimple_social_clone的根是什么? @guillermochamorro 我相信根是 simple_social_clone。我将发布我设置它的方式的图像。我在项目中有多个应用程序。 根目录是你的 manage.py 所在的位置。 啊。在这种情况下,根是 simplesocial。 当你意识到你的模板文件上一级而不是实际在你的模板文件夹中的那一刻:(谢谢你的帮助。 【参考方案1】:

您似乎将所有模板都放在一个文件夹下,而 Jose(您正在学习的教程的讲师)将它们安排在每个应用程序中。确保您已在设置中正确设置所有内容。我在做同样的课程(ps,在我的社区里把群改成社区):

【讨论】:

以上是关于模板不存在。 Django寻找错误的路径的主要内容,如果未能解决你的问题,请参考以下文章

Django CMS - 创建第一页时模板不存在错误

Django 模板不存在@

模板不存在。加载静态文件和模板 Django 项目结构

模板不存在“django 2.0”

模板不显示验证错误(Django)

django收集静态寻找不存在的目录