Skip to content

made Browsable API base template cachable: omit CSRF token when unnecessary #7717

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
Mar 16, 2021
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
2 changes: 1 addition & 1 deletion rest_framework/templates/rest_framework/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ <h1>{{ name }}</h1>
<script>
window.drf = {
csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
csrfToken: "{% if request %}{{ csrf_token }}{% endif %}"
csrfToken: "{% if request %}{% if post_form or put_form %}{{ csrf_token }}{% endif %}{% endif %}"
};
</script>
<script src="{% static "rest_framework/js/jquery-3.5.1.min.js" %}"></script>
Expand Down
20 changes: 14 additions & 6 deletions tests/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,23 @@
from django.shortcuts import render


def test_base_template_with_context():
context = {'request': True, 'csrf_token': 'TOKEN'}
result = render({}, 'rest_framework/base.html', context=context)
assert re.search(r'\bcsrfToken: "TOKEN"', result.content.decode())


def test_base_template_with_no_context():
# base.html should be renderable with no context,
# so it can be easily extended.
result = render({}, 'rest_framework/base.html')
# note that this response will not include a valid CSRF token
assert re.search(r'\bcsrfToken: ""', result.content.decode())


def test_base_template_with_simple_context():
context = {'request': True, 'csrf_token': 'TOKEN'}
result = render({}, 'rest_framework/base.html', context=context)
# note that response will STILL not include a CSRF token
assert re.search(r'\bcsrfToken: ""', result.content.decode())


def test_base_template_with_editing_context():
context = {'request': True, 'post_form': object(), 'csrf_token': 'TOKEN'}
result = render({}, 'rest_framework/base.html', context=context)
# response includes a CSRF token in support of the POST form
assert re.search(r'\bcsrfToken: "TOKEN"', result.content.decode())