首页 > 解决方案 > 在 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 复制值,但仍然失败!

我已经被这个问题困扰了一段时间......有任何线索吗?

标签: pythondjangounit-testingtesting

解决方案


打印 的值form.errors,从上面您忘记添加的代码的外观来看,您可以通过添加模型中的字段audio_file来解决此问题。null=True, blank=Trueaudio_file


推荐阅读