'Factoryboy build is showing object does not exist
@pytest.mark.django_db(transaction=True)
class testAllAPIEndPoints(TestCase):
# This function will help us authenticate as admin
def authenticate_asAdmin(self):
self.user = AdminFactory.create()
self.token = Token.objects.create(user= self.user)
self.client.force_login(self.user)
# This function will build an instructor. Note: build does not commit to database
def build_instructor(self):
user = UserFactory()
inst = InstructorFactory.build(user=user)
return inst
def test_addCourses(self):
self.authenticate_asAdmin()
inst = self.build_instructor()
course = CourseFactory.build() # Creates a new course
tag = self.build_courseTag()
print("tag")
print(tag.id)
data = dict(
name=course.name,
description = course.description,
instructor = inst.user.id,
tags = [tag.id]
)
# Error I am getting:
# b'{"instructor":["Invalid pk \\"10795\\" - object does not exist."]}'
response =self.client.post('http://localhost:8000/api/courses/',
data = data,
headers={'Content-Type': 'application/json','Authorization':'Token ' + self.token.key}, follow=True)
print(response.content)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
I am trying to add course here which has instructor as foreign key. I am using the build() function from factory boy which as I can see is working fine. I tried to create a create function instead like this:
# This function will create an instructor. Note: create will commit to database
def create_instructor(self):
inst = InstructorFactory.create()
return inst
And then creating a new instructor:
inst = self.create_instructor()
but I am getting similar error:
b'{"instructor":["Invalid pk \"11105\" - object does not exist."]}'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
