簡體   English   中英

Django表單測試使用外鍵模型字段生成錯誤

[英]Django form test generates error with a foreign key model field

測試提交的表單時遇到問題。 在使用models.ForeignKey定義的字段中,測試會生成錯誤。

字段gender_optmodels.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.

test.py中的URL“/ quiz / patient / new /”指向視圖(在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字段類型。

感謝任何幫助。

首先,您需要創建一個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())
        ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM