IT박스

TemplateDoesNotExist-장고 오류

itboxs 2020. 7. 28. 08:17
반응형

TemplateDoesNotExist-장고 오류


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에서 위젯 가져 오기 module.data.models에서 import serializer 가져 오기 *

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'),
)

rest_framework나열되어 있는지 확인하십시오 settings.py INSTALLED_APPS.


나를 rest_framework/api.html위해, 손상된 설치 또는 다른 알 수없는 이유로 파일 시스템에서 실제로 누락되었습니다. 다시 설치 djangorestframework하면 문제가 해결되었습니다.

$ pip install --upgrade djangorestframework

DRF는 요청 된 것과 동일한 형식으로 데이터를 리턴하려고합니다. 브라우저에서 이것은 HTML 일 가능성이 높습니다. 대체 응답을 지정하려면 ?format=매개 변수를 사용하십시오 . 예를 들면 다음과 같습니다 ?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


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.


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.

참고URL : https://stackoverflow.com/questions/21408344/templatedoesnotexist-django-error

반응형