TemplateDoesNotExist-Django错误

问题:TemplateDoesNotExist-Django错误

我正在使用Django Rest Framework。而且我不断出错

Exception Type: TemplateDoesNotExist
Exception Value: rest_framework/api.html

我不知道我怎么了。这是我第一次尝试使用REST Framework。这是代码。

views.py

import socket, json
from modules.data.models import *
from modules.utils import *
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from modules.actions.serializers import ActionSerializer


@api_view(['POST'])
@check_field_exists_wrapper("installation")
def api_actions(request, format = None):

    action_type = request.POST['action_type']
    if action_type == "Shutdown" : 
        send_message = '1'
        print "Shutting Down the system..."
    elif action_type == "Enable" : 
        send_message = '1'
        print "Enabling the system..."
    elif action_type == "Disable" : 
        send_message = '1'
        print "Disabling the system..."
    elif action_type == "Restart" : 
        send_message = '1'
        print "Restarting the system..."

    if action_type in ["Shutdown", "Enable", "Disable"] : PORT = 6000
    else : PORT = 6100

    controllers_list = Controller.objects.filter(installation_id = kwargs['installation_id'])

    for controller_obj in controllers_list:
        ip = controller_obj.ip
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip, PORT))
            s.send(send_message)
            s.close()
        except Exception as e:
            print("Exception when sending " + action_type +" command: "+str(e))

    return Response(status = status.HTTP_200_OK)

models.py

class Controller(models.Model):
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 255, unique = True)
    ip = models.CharField(max_length = 255, unique = True)
    installation_id = models.ForeignKey('Installation')

serializers.py

从django.forms中导入从rest_framework中导入小部件从modules.data.models中导入序列化器*

class ActionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Controller
        fields = ('id', 'name', 'ip', 'installation_id')

urls.py

from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = patterns('modules.actions.views',
    url(r'^$','api_actions',name='api_actions'),
)

I’m using Django Rest Framework. and I keep getting an error

Exception Type: TemplateDoesNotExist
Exception Value: rest_framework/api.html

I dont know how I’m going wrong. This is the first time I’m trying out hands on REST Framework. This is code.

views.py

import socket, json
from modules.data.models import *
from modules.utils import *
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from modules.actions.serializers import ActionSerializer


@api_view(['POST'])
@check_field_exists_wrapper("installation")
def api_actions(request, format = None):

    action_type = request.POST['action_type']
    if action_type == "Shutdown" : 
        send_message = '1'
        print "Shutting Down the system..."
    elif action_type == "Enable" : 
        send_message = '1'
        print "Enabling the system..."
    elif action_type == "Disable" : 
        send_message = '1'
        print "Disabling the system..."
    elif action_type == "Restart" : 
        send_message = '1'
        print "Restarting the system..."

    if action_type in ["Shutdown", "Enable", "Disable"] : PORT = 6000
    else : PORT = 6100

    controllers_list = Controller.objects.filter(installation_id = kwargs['installation_id'])

    for controller_obj in controllers_list:
        ip = controller_obj.ip
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip, PORT))
            s.send(send_message)
            s.close()
        except Exception as e:
            print("Exception when sending " + action_type +" command: "+str(e))

    return Response(status = status.HTTP_200_OK)

models.py

class Controller(models.Model):
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 255, unique = True)
    ip = models.CharField(max_length = 255, unique = True)
    installation_id = models.ForeignKey('Installation')

serializers.py

from django.forms import widgets from rest_framework import serializers from modules.data.models import *

class ActionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Controller
        fields = ('id', 'name', 'ip', 'installation_id')

urls.py

from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = patterns('modules.actions.views',
    url(r'^$','api_actions',name='api_actions'),
)

回答 0

确保您已rest_framework在中列出settings.py INSTALLED_APPS

Make sure you have rest_framework listed in your settings.py INSTALLED_APPS.


回答 1

对我来说,rest_framework/api.html由于安装损坏或其他未知原因,文件系统上实际上缺少该文件系统。重新安装djangorestframework解决了问题:

$ pip install --upgrade djangorestframework

For me, rest_framework/api.html was actually missing on the filesystem due to a corrupt installation or some other unknown reason. Reinstalling djangorestframework fixed the problem:

$ pip install --upgrade djangorestframework

回答 2

请注意,DRF尝试以请求的相同格式返回数据。在您的浏览器中,这很可能是HTML。要指定替代响应,请使用?format=参数。例如:?format=json

如其他受访者所述,TemplateDoesNotExist当您在浏览器中访问API端点并且未将rest_framework包含在已安装应用程序列表中时,通常会发生此错误。

如果您的应用程序列表中未包含DRF,但又不想使用HTML Admin DRF页面,请尝试使用其他格式来“避免”此错误消息。

来自此处的文档的更多信息:http : //www.django-rest-framework.org/topics/browsable-api/#formats

Please note that the DRF attempts to return data in the same format that was requested. From your browser, this is most likely HTML. To specify an alternative response, use the ?format= parameter. For example: ?format=json.

The TemplateDoesNotExist error occurs most commonly when you are visiting an API endpoint in your browser and you do not have the rest_framework included in your list of installed apps, as described by other respondents.

If you do not have DRF included in your list of apps, but don’t want to use the HTML Admin DRF page, try using an alternative format to ‘side-step’ this error message.

More info from the docs here: http://www.django-rest-framework.org/topics/browsable-api/#formats


回答 3

不是您的情况,而是为定制loaders了可能的原因Django。例如,如果您有设置(自以来Django 1.8):

TEMPLATES = [
{
    ...
    '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'
        ],
        'loaders': [
            'django.template.loaders.filesystem.Loader',
        ],
        ...
    }
}]

Django将不尝试一下使用模板的应用程序文件夹,因为你应该明确地添加django.template.loaders.app_directories.Loaderloaders了这一点。

请注意,默认情况下django.template.loaders.app_directories.Loader包含在中loaders

Not your case, but also possible reason is customized loaders for Django. For example, if you have in settings (since Django 1.8):

TEMPLATES = [
{
    ...
    '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'
        ],
        'loaders': [
            'django.template.loaders.filesystem.Loader',
        ],
        ...
    }
}]

Django will not try to look at applications folders with templates, because you should explicitly add django.template.loaders.app_directories.Loader into loaders for that.

Notice, that by default django.template.loaders.app_directories.Loader included into loaders.


回答 4

我遇到了同样的错误消息。就我而言,这是由于将后端设置为Jinja2。在我的设置文件中:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.jinja2.Jinja2',
...

将其更改回默认值可解决此问题:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
...

仍然不确定是否有办法将Jinja2后端与rest_framework一起使用。

I ran into the same error message. In my case, it was due to setting the backend to Jinja2. In my settings file:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.jinja2.Jinja2',
...

Changing this back to the default fixed the problem:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
...

Still not sure if there is a way to use the Jinja2 backend with rest_framework.