Django表单测试使用外键模型字段生成错误

时间:2014-07-02 12:47:03

标签: python django testing

测试提交的表单时遇到问题。在使用 models.ForeignKey 定义的字段中,测试会生成错误。

字段 gender_opt models.py 中定义为

class Patient(models.Model):
    gender_opt = models.ForeignKey(GenderOption, null=False, blank=False)
使用

给出的ForeignKey

class GenderOption(models.Model):
    gender_txt = models.CharField(max_length=50)

在我的forms.py中我有

class PatientForm(ModelForm):
class Meta:
    model = Patient

fields = [
         other fields
        'gender_opt'
    ]

widgets = {
other widgets

'gender_opt': Select(attrs={'class': 'form-control', 'id': 'gender_id', 'required': "",
                                     'data-error': "Gender must be filled"}),
}

我的 test.py

from django.test import TestCase
from django.contrib.auth.models import *

class FormValidation(TestCase):
def test_patient_add_ok(self):
    """test save patient data successfuly"""

    data = {u'cpf_id': [u'248.215.628-98'], u'state_txt': [u'RJ'], 
            u'citizenship_txt': [u'BR'], u'name_txt': [u'Test pacient'],
            u'date_birth_txt': [u'15/01/2003'], u'country_txt': [u'BR'],
            u'gender_opt': [u'1']}


    response = self.client.post('/quiz/patient/new/', data)
    errors = response.context['patient_form'].errors

错误中,我收到了以下消息:

Select a valid choice. That choice is not one of the available choices.

网址' / quiz / patient / new /'在 test.py 中指向视图(在views.py中)

def patient_create(request, template_name="quiz/register.html"):

   gender_options = GenderOption.objects.all()

   patient_form = PatientForm()

if request.method == "POST":

    patient_form = PatientForm(request.POST)

    if patient_form.is_valid():
        new_patient = patient_form.save(commit=False)
        new_patient.save()



context = {'patient_form': patient_form,
           'gender_options': gender_options,
}

return render(request, template_name, context)

我认为问题是models.ForeignKey字段类型。

感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

首先,您需要创建一个GenderOption对象。此外,在测试表单时,您实际上并不需要使用self.client发出请求:

class FormValidation(TestCase):
    def test_patient_add_ok(self):
        """test save patient data successfully"""

        # create GenderOption
        gender_opt = GenderOption.objects.create(gender_txt='M')

        data = {u'cpf_id': [u'248.215.628-98'], u'state_txt': [u'RJ'], 
                u'citizenship_txt': [u'BR'], u'name_txt': [u'Test pacient'],
                u'date_birth_txt': [u'15/01/2003'], u'country_txt': [u'BR'],
                u'gender_opt': [str(gender_opt.id)]}

        form = PatientForm(data=data)
        self.assertTrue(form.is_valid())
        ...