我正在尝试测试包含 ImageField 的表单,但出现错误。我尝试过单步执行 Django 代码,但我一直迷路,看不到问题所在。我已经研究了应该如何做到这一点,我认为我做的一切都是正确的。
这是在我的测试中的 assertTrue 语句中发生的错误:
TypeError: is_valid() takes exactly 2 arguments (1 given)
这是我的文件:
# forms.py
class UploadMainPhotoForm(forms.Form):
photo = forms.ImageField(error_messages={'required': err_msg__did_not_choose_photo})
def is_valid(self, request):
# Run parent validation first
valid = super(UploadMainPhotoForm, self).is_valid()
if not valid:
return valid
if request.FILES:
photo_file = request.FILES['photo']
file_name, file_ext = os.path.splitext(photo_file.name)
else:
self._errors['photo'] = 'You forgot to select a photo.'
return False
# Return an error if the photo file has no extension
if not file_ext:
self._errors['photo'] = err_msg__photo_file_must_be_jpeg
return False
return True
# upload_photo.html (template)
<form method="post" enctype="multipart/form-data" action=".">{% csrf_token %}
<input type="file" name="photo" />
<input type="submit" name="skip_photo" value="Skip Photo" />
<input type="submit" name="upload_photo" value="Upload Photo">
</form>
# form_tests.py
class TestUploadMainPhotoForm(TestCase):
def initial_test(self):
post_inputs = {'upload_photo': '[Upload Photo]'}
test_photo = open('photo.jpg', 'rb')
file_data = {'file': SimpleUploadedFile(test_photo.name, test_photo.read())}
self.assertTrue(UploadMainPhotoForm(post_inputs, file_data).is_valid())