'Manually referencing dummy file in Django HttpRequest for testing form submission
In Django, I am trying to create automated tests for a project that includes a file submission via ModelForm. One of the model fields is a FileField, and a test file has already been placed into the project directory so it can be referenced.
In order to test the form submission I am creating a dummy user and manually generating an HttpRequest() containing POST data. However, I am unsure of how to manually insert the file into the FileField portion -- I assume I need to reference it somehow, but I don't know exactly how to do that.
The test is below:
def test_form_submit(self):
user = User.objects.create_user(
username="testuser",
email="[email protected]",
password="asdfasdf"
)
request = HttpRequest()
request.POST = {
"file": [insert file here], # is a FileField
"name": "Richard",
"date": "2022-01-28",
"desc": "A test submission."
}
form = FileSubmissionForm(request.POST, user=user)
form.save()
self.assertEqual(Submission.objects.count(), 1)
How do I properly reference the file for this test case? The dummy file is located at $MEDIA_ROOT/testing/dummy_file.txt.
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
