101
votes

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

Thanks in advance

10

10 Answers

248
votes

Make sure you have rest_framework in your settings's INSTALLED_APPS

57
votes

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

INSTALLED_APPS = [
    'rest_framework',
]
21
votes

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.

19
votes

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

12
votes

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.

8
votes

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.

2
votes

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'
],
1
votes

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

1
votes

instead of using HttpResponse, use:

from rest_framework.response import Response

return Response(data=message, status=status.HTTP_200_OK)
0
votes

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