[Answered ]-Django testing a form, self.request kwargs gives keyerror

1👍

Because your form requires the request in order to initialise, you can’t just create an instance of it, you need to actually post your data as a request. You can do this with self.client.post, eg

def test_CourseForm_invalid_name_exists(self):
    # we use client.post because the form requires a request in __init__()
    # if you need a logged in user, first use
    # self.client.login(username='john', password='johnpassword')
    response = self.client.post("/form/url/", data={
        'user': self.user,
        'id': '4d192045-07fa-477f-bac2-5a99fe2e7c05',
        'course_name': "name",
        'grade_level': "SEC"
    },)
    self.assertContains(response, "A course with that name already exists.", html=True)

Leave a comment