python - 在 Django 上测试表单
问题描述
我正在尝试在表单上运行测试。它一直返回无效。其他形式虽然工作正常。
forms.py 中的表单:
class SongForm(forms.ModelForm):
class Meta():
model = Song
fields = ('title', 'type', 'audio_file', 'description', 'written_by', 'song_text')
表格来自models.py中的模型:
class Song(models.Model):
title = models.CharField(max_length=120)
SONG_TYPES = (
('KI', 'Kiirtan'),
('PS', 'Prabhat Samgiita'),
('BH', 'Bhajan'),
)
type = models.CharField(max_length=30, choices=SONG_TYPES)
capo = models.PositiveIntegerField(blank=True, null=True, validators=[MaxValueValidator(12)])
description = models.TextField(blank=True)
uploader = models.ForeignKey('Profile', null=True, on_delete=models.SET_NULL)
written_by = models.CharField(max_length=50, blank=True)
song_text = models.TextField(blank=True)
audio_file = models.FileField(upload_to='songs/')
upload_date = models.DateField(auto_now=False, auto_now_add=True)
edit_date = models.DateField(auto_now=True, auto_now_add=False)
chords = models.ManyToManyField('Chord', related_name='chords', through='ChordIndex')
tests/test_forms.py 中的测试:
def test_Song_form_is_valid(self):
the_data = {
'title': 'a song',
'type': 'KI',
'description': '',
'audio_file': '103_VASANTA_AJ_JAGALO_04Tsyry.mp3'
'written_by': '',
'song_text': '',
}
form = SongForm(data=the_data)
self.assertTrue(form.is_valid())
该表单使用 POST 方法在 Web 应用程序中正常工作。我什至尝试从测试中的有效 POST 复制值,但仍然失败!
我已经被这个问题困扰了一段时间......有任何线索吗?
解决方案
打印 的值form.errors
,从上面您忘记添加的代码的外观来看,您可以通过添加模型中的字段audio_file
来解决此问题。null=True, blank=True
audio_file
推荐阅读
- linux - 自定义内核的 kdump 工具问题
- javascript - 找到 3 个点的所有共线
- scrapy - scrapy 无法处理“<”字符
- android - 带有匕首 2 的不同范围的单个实例
- docker - Docker 映像中的 Jira 和汇合更改架构
- swiftui - 尝试将 url 传递给 SwiftUI 中的图像加载器给我 nil
- reactjs - 如何使用 react-native-cookies 在 REACT NATIVE 中设置 cookie
- ios - 在 Swift 中将自定义视图锚定到 Mapbox NavigationViewController 中的现有视图
- spring-boot - 我们可以在 Spring JPA @Query 中替换等于、大于或小于运算符吗?
- c# - 防止 API 推送在保存时多次运行