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

时间:2018-01-08 00:01:55

标签: python django templates django-models django-templates

我正在关注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'

这是app level 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)

这是app level 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>

enter image description here

1 个答案:

答案 0 :(得分:0)

似乎您将所有模板都放在一个文件夹中,而Jose(您正在关注的教程的讲师)将它们按应用进行排列。确保已正确设置所有设置。我正在做同样的课程(ps,将组更改为我的社区):enter image description here