[Python] CRSF Token Interfering With TDD - Is there a variable that stores csrf output?

Discussão em 'Python' iniciado por Stack, Agosto 15, 2025.

  1. Stack

    Stack Membro Participativo

    So, I kept returning a Failing test in Django when comparing expected to actual html with form input, so I printed out the result and realized the difference was the rather simple line, caused by my {% csrf_token %}, as follows:

    <input type='hidden' name='csrfmiddlewaretoken' value='hrPLKVOlhAIXmxcHI4XaFjqgEAMCTfUa' />


    So, I expect a simple answer, but I haven't been able to find it: How do I render the result of a csrf_token for use in testing?

    Here's the Test setup and failure:

    def test_home_page_returns_correct_html_with_POST(self):
    request = HttpRequest()
    request.method = 'POST'
    request.POST['item_text'] = 'A new list item'

    response = home_page(request)

    self.assertIn('A new list item', response.content.decode())

    expected_html = render_to_string(
    'home.html',
    {'new_item_text': 'A new list item'},
    ******this is where I'm hoping for a simple one-line mapping******

    )
    self.assertEqual(response.content.decode(), expected_html)


    Here's the rendering from views.py:

    def home_page(request):
    return render(request, 'home.html', {
    'new_item_text': request.POST.get('item_text'),
    })


    And here's the test failure, when I run the test with python manage.py test

    FAIL: test_home_page_returns_correct_html_with_POST (lists.tests.HomePageTest)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
    File "C:\Users\Me\PycharmProjects\superlists\lists\tests.py", line 29, in test_home_page_returns_correct_html_with_POST
    self.assertEqual(response.content.decode(), expected_html)
    AssertionError: '<!DO[298 chars] <input type=\'hidden\' name=\'csrfmiddlew[179 chars]tml>' != '<!DO[298 chars] \n </form>\n\n <table
    id="id_list_t[82 chars]tml>'

    ----------------------------------------------------------------------

    Continue reading...

Compartilhe esta Página