samedi 6 janvier 2018

Django Testing: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist:

I get the error from the ProductTestCase:

django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: 
Product has no name_text

It would be great to know how to fix this issue and why it only occurs when on Foreign keys. I am sure that the Department is fine it just it does not seem to be passed over to Product.

I have added in Department test as well, it works fine.

Thank you for your time.

I know of this page here, but it appears not to point out how to fix the issue, but catch the issue. Which is useful but knowing how to stop it in the first place is also useful.

Department Test

class DepartmentTestCase(ModelTestCase):

    def setUp(self):
        super(DepartmentTestCase, self).setUp()
        self.department_form = self.get_department_form(department_name_text=self.department_name)

    def test_valid_input(self):
        self.assertTrue(self.department_form.is_valid())

Product Test (updated: change to match comment improvement)

class ProductTestCase(ModelTestCase):
    @classmethod
    def setUpTestData(cls):
        super(ProductTestCase, cls).setUpTestData()

    def setUp(self):
        super(ProductTestCase, self).setUp()

        self.product_data = {'barcode_text': self.barcode
                             }
        department_inst = Department.objects.create(department_name_text=self.department_name) 

        maker_inst = Maker.objects.create(maker_name_text=self.maker_name)

        self.product_data.update({'name_text': department_inst,
                                  'from_maker': maker_inst})

    def test_valid_input(self):
        product_form = ProductForm(self.product_data)

        self.assertTrue(product_form.is_valid())

    def test_form_save(self):
        product_form = ProductForm(self.product_data)
        product_instance = product_form.save()
        #I believe the error occurs when the form is saved
        self.assertEqual(Product.objects.get(pk=product_instance_id), product_instance)

Department Form

class DepartmentForm(ModelForm):
    field_names = {'department_name_text': 'Department Name'}

    class Meta:
        model = Department
        fields = ['department_name_text']

    def __init__(self, *args, **kwargs):
        super(DepartmentForm, self).__init__(*args, **kwargs)
        for field, name in self.field_names.items():
            self.fields[field].label = name

Aucun commentaire:

Enregistrer un commentaire