I am writing my first Django application following this book:
http://chimera.labs.oreilly.com/books/1234000000754/ch05.html#_passing_python_variables_to_be_rendered_in_the_template
There is a test in the book that checks that html is returned as expected. Here is the test:
def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) expected_html = render_to_string('home.html') print(expected_html) print(response.content.decode()) self.assertEqual(response.content.decode(), expected_html)
My test does not work in the assertEqual test, because I added csrf token to my HTML using the Django Template Language . This is what my HTML page looks like:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To-Do lists</title> </head> <body> <h1>Your To-Do list</h1> <form method="POST"> <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/> {% csrf_token %} </form> <table id="id_list_table"> <tr><td>{{ new_item_list }}</td></tr> </table> </body> </html>
My statement does not work due to render_to_string method not including the token. Here are my two print statements included in my test printout:
F<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To-Do lists</title> </head> <body> <h1>Your To-Do list</h1> <form method="POST"> <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/> </form> <table id="id_list_table"> <tr><td></td></tr> </table> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To-Do lists</title> </head> <body> <h1>Your To-Do list</h1> <form method="POST"> <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/> <input type='hidden' name='csrfmiddlewaretoken' value='VAiGvXZLHCjxWEWdjhgQRBwBSnMVoIWR' /> </form> <table id="id_list_table"> <tr><td></td></tr> </table> </body> </html> F.
He does not have this problem in the book (he uses 1.8 ), so I was wondering if the behavior of the method has changed or how I will write this test to pass.
source share