I have a template which contains four forms (in hidden modals, not that that matters). Each form has a {% csrf_token %}
tag in it. When I render the template in a test, for only the first {% csrf_token %}
encountered, an empty string is returned; for the other three instances, the <input type="hidden" name="csrfmiddlewaretoken" ...>
element is rendered correctly.
I can’t quite see what could be happening - it’s a single render from a single GET request. Snippet of test code:
def test_home_page(self):
c = Client(headers=HEADERS)
resp = c.get('/')
s = resp.content.decode(resp.charset)
soup = BeautifulSoup(s, 'html.parser')
forms = soup.find_all('form')
for f in forms:
inp = f.find('input', {'name': 'csrfmiddlewaretoken'})
print(f.attrs)
print(f' {inp}')
and the output:
{'id': 'frm-login-modal', 'action': '/accounts/login/', 'method': 'post', 'enter-buttons': '#signin-buttons button.btn-primary'}
None
{'class': ['rdc-vanilla'], 'action': '/accounts/external', 'method': 'post'}
<input name="csrfmiddlewaretoken" type="hidden" value="zJjibteg6bAMX6zTREudDYjW5eIf9le16WohD73ipDhkuEy9C5Lzb1FRh1yuspDf"/>
{'id': 'frm-verify-or-backup', 'action': '/accounts/verify', 'method': 'post', 'class': ['flex-grow-1']}
<input name="csrfmiddlewaretoken" type="hidden" value="zJjibteg6bAMX6zTREudDYjW5eIf9le16WohD73ipDhkuEy9C5Lzb1FRh1yuspDf"/>
{'id': 'frm-signup-modal', 'action': '/accounts/signup/', 'method': 'post'}
<input name="csrfmiddlewaretoken" type="hidden" value="zJjibteg6bAMX6zTREudDYjW5eIf9le16WohD73ipDhkuEy9C5Lzb1FRh1yuspDf"/>
What could cause only the first instance of the tag to be rendered differently? Could it be something to do with the LazyObject
used to return the token on demand? I’m using Django 5.1.5.