【问题标题】:Testing a form on Django在 Django 上测试表单
【发布时间】:2020-03-04 02:31:52
【问题描述】:

我正在尝试对表单进行测试。它一直返回无效。不过其他形式也可以。

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 中复制值,但仍然失败!

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

【问题讨论】:

标签: python django unit-testing testing


【解决方案1】:

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

【讨论】:

  • 好收获。我编辑了包含 audio_file 的问题。结果还是一样。
  • 你是对的!那是给我带来问题的领域。将其设置为 null=True, blank=True 确实可以解决问题。除了我需要这个字段是强制性的。但现在至少我知道发生了什么事。稍后我解决它
猜你喜欢
  • 2019-10-20
  • 2015-10-23
  • 2018-11-10
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 2012-11-27
  • 1970-01-01
相关资源
最近更新 更多