Django: TemplateDoesNotExist (rest_framework/api.html)
Asked Answered
H

16

169

In my view function, I'd like to return a json object (data1) and some text/html (form). Is this possible?

MY code

@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    if request.is_ajax():
        if request.method == 'POST':
            serializer = SignupSerializer(data=request.data)
            print 'ser'
            print serializer
            if not serializer.is_valid():
                return Response(serializer.errors,\
                                status=status.HTTP_400_BAD_REQUEST)
            else:
                serializer.save()
                data={'status': 'Created','message': 'Verification email has been sent to your email. Please verify your account.'}
                return Response(data, template_name='register.html')
    else:
        return HttpResponse('hello world')

When I call the url I get status code 500 with error as displayed below

TemplateDoesNotExist rest_framework/api.html

when I check as a API, I get response with 200 ok status. This shows Im unable to get my html page

How should I get my html depending on request?

Hepzi answered 14/7, 2016 at 6:21 Comment(0)
B
424

Make sure you have rest_framework in your settings's INSTALLED_APPS

Bifurcate answered 14/7, 2016 at 7:23 Comment(4)
Its already present. I believe @api_view is not allowing me to render html page..Is there any other solutionHepzi
You want to double check that by opening the django shell and looking at the INSTALLED_APPS. It's unlikely api_view since I got it working and it would return an HTTP 415 Unsupported Media Type.Bifurcate
this function works with CURL command, I also get response, when i try to render html with my browser, I get the above listed errorHepzi
This should be selected has answer?Motorbus
G
90

Make sure you install pip install djangorestframework and include rest_framework in the setting.py

INSTALLED_APPS = [
    'rest_framework',
]
Gusman answered 8/4, 2019 at 19:49 Comment(0)
L
33

This is my attempt to explain the problem and collect everyone else's responses into a single list. Thanks to everyone for giving me shoulders to stand on!

I believe this happens because Django REST Framework wants to render a template (rest_framework/api.html), but the template can't be found. It seems there are two approaches to fix this:

Approach 1: Make templates work

Ensure REST Framework is included in INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework',
    ...
]

And ensure APP_DIRS is True in your template configuration (it defaults to False if not specified). This allows Django to look for templates in installed applications. Here's a minimal configuration that seems to work, though you might have more config here:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
    },
]

Approach 2: Return a JSON response

If you tell REST Framework to render a JSON response then it doesn't need to use a template so you don't need to change the APP_DIRS settings as mentioned above. It also seems like you might not even need to list rest_framework in INSTALLED_APPS, though it might be necessary to have it there for other reasons.

You can do this globally in settings.py:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ]
}

Or if you're using the @api_view decorator then you can specify JSONRenderer on each view:

@api_view(['GET'])
@renderer_classes([JSONRenderer])
def some_view(request):
    return Response({'status': 'yay'})

See the REST Framework renderers documentation for details.

Landman answered 13/3, 2020 at 19:33 Comment(0)
A
28

I also had same kind of problem. Make sure you have rest_framework installed in your setting in "installed apps"

After answered 15/9, 2020 at 2:40 Comment(0)
D
15

''' Try one of these for sure help you out:

1: add rest_framework to settings.py app list, sometime order in which your applications are listed may be the reason. '''

INSTALLED_APPS = [
    'rest_framework',
    ...
]

''' 2: review your template settings. See Backend, DIR and APP_DIRS. in case you have customized the rest-framework template please check if the path you have defined is correct, make APP_DIRS: True . In most of the cases this will resolve. '''

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR, os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ....
    }
]

''' 3: check the default renderer classes settings: '''

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        ...
    ]
}

''' 4: If you are using api_view decorators on function based view make sure you have provided renderers correctly. i.e.

@renderer_classes([JSONRenderer]) '''

Doyle answered 2/3, 2022 at 4:57 Comment(1)
At last! 24 hrs of intense hunt later, I find this as the solution that worked for me. Thanks!Vally
B
14

Make sure that you added rest_framework in your installed_apps to your settings.py file:

INSTALLED_APPS = [
    'rest_framework',
]
Blessington answered 16/9, 2021 at 19:8 Comment(0)
E
12

I hit this issue when upgrading from an old Django version to Django 2.0. My settings.py did not have a TEMPLATE directive at all, so I snagged the following from a new django-admin.py startproject ... run:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

Add that to your settings.py if you don't have TEMPLATES directive in your settings.py. Worked for me.

Evangelineevangelism answered 21/12, 2017 at 18:54 Comment(1)
Specifically, in my case, 'APP_DIRS': True got overlooked; that fixed my issue.Barley
Y
11

I have come across the same issue and found out that rest_framework wasn't added to the installed apps in settings.py. Adding it resolved my issue.

Yb answered 4/7, 2020 at 6:2 Comment(0)
L
6

setting.py add rest_framework , if rest_framework is not added

Ex:

INSTALLED_APPS = ["rest_framework"]

Lacrimatory answered 25/7, 2023 at 4:41 Comment(1)
Why is this needed though ?Plumbago
K
3

The order of the installed apps matters a lot. In my case i added 'rest_auth' above 'rest_framework' so it gave this error but when i reordered it ('rest_framework' above 'rest_auth', 'rest_auth.registration', 'rest_framework.authtoken' etc), this error cleared.

sample Proper order below:

INSTALLED_APPS = [

...
'rest_framework',
'rest_auth',
'rest_auth.registration',
'rest_framework.authtoken',
...

]

Thanks.

Kado answered 16/12, 2021 at 17:16 Comment(0)
E
2

Other than adding 'rest_framework' inside your INSTALLED_APPS, try adding the following inside your TEMPLATES.OPTIONS:

'loaders': [
     'django.template.loaders.filesystem.Loader',
     'django.template.loaders.app_directories.Loader'
],
Eloign answered 14/3, 2017 at 3:51 Comment(0)
S
2

In installed apps if you used rest_framework in your project add rest_framework in setting.py file:

INSTALLED_APPS = [
    'rest_framework',]
Stieglitz answered 24/11, 2023 at 14:25 Comment(0)
L
1

Adding this decorator above that view @renderer_classes([JSONRenderer])

Lunge answered 2/10, 2019 at 10:13 Comment(0)
M
1

instead of using HttpResponse, use:

from rest_framework.response import Response

return Response(data=message, status=status.HTTP_200_OK)
Moolah answered 23/10, 2020 at 22:9 Comment(0)
G
0

I faced a same issue. But I installed django_filters and did not included it in INSTALLED_APPS. After putting it in INSTALLED_APPS, it worked. So look for other third party apps as well.

Garamond answered 21/2 at 13:8 Comment(0)
W
-1

I have came across the same problem, I was sending an empty response. Try to put a different infomation into Response() in create_user function to check if it works at all

Wattle answered 26/4, 2019 at 6:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.