Skip to content

Fix backend template rendering #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 19, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions rest_framework_filters/backends.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

from django.template import loader
from django.template import Template, TemplateDoesNotExist, loader
from rest_framework import compat
from django_filters.rest_framework import backends

Expand Down Expand Up @@ -28,8 +28,11 @@ def to_html(self, request, queryset, view):
# forces `form` evaluation before `qs` is called. This prevents an empty form from being cached.
filter_instance.form

context = {
try:
template = loader.get_template(self.template)
except TemplateDoesNotExist:
template = Template(backends.template_default)

return compat.template_render(template, context={
'filter': filter_instance
}
template = loader.get_template(self.template)
return compat.template_render(template, context)
})
28 changes: 27 additions & 1 deletion tests/test_backends.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@

from rest_framework.test import APITestCase
from rest_framework.test import APITestCase, APIRequestFactory

from .testapp import models, views

factory = APIRequestFactory()


class BackendTest(APITestCase):

Expand Down Expand Up @@ -33,3 +35,27 @@ def test_filter_fields_reusability(self):
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['username'], 'user1')
self.assertDictEqual(views.FilterFieldsUserViewSet.filter_fields, {'username': '__all__'})

def test_backend_output_sanity(self):
"""
Sanity check to ensure backend can at least render something without crashing.
"""
class SimpleViewSet(views.FilterFieldsUserViewSet):
filter_fields = ['username']

view = SimpleViewSet(action_map={})
backend = view.filter_backends[0]
request = view.initialize_request(factory.get('/'))
html = backend().to_html(request, view.get_queryset(), view)

self.assertHTMLEqual(html, """
<h2>Field filters</h2>
<form class="form" action="" method="get">
<p>
<label for="id_username">Username:</label>
<input id="id_username" name="username" type="text" />
<span class="helptext">Filter</span>
</p>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
""")