5👍
✅
This happens because you have OneToOneField
, since that your every new Thing
must be connected to User
that wasn’t picked before. So because you already had dummy_thing
with dummy_user
as User
, you can’t save new Thing
instance with same dummy_user
.
I believe your intention was that every Thing
has a User
, so you should use ForeignKey
instead of OneToOneField
.
But if i’m wrong, if you really need OneToOneField
, then to test your POST
request just create new user and login as new user, then thing.user = request.user
will take dummy_user2
and there would be no conflicts with unique values.
class SampleTest(TestCase):
def setUp(self):
# Every test needs access to the request factory.
self.factory = RequestFactory()
self.dummy_user = User.objects.create_user(username='dummy', password='nothings')
self.dummy_thing = Thing.objects.create(name="Dummy Book",
description="Book For Dummies.",
slug="dummy-book",
user=self.dummy_user)
self.dummy_user2 = User.objects.create_user(username='dummy2', password='nothing')
def test_form_post(self):
dummy_thing = Thing.objects.get(name="Dummy Book")
self.client.login(username=dummy_thing2.user.username, password='nothing')
# Test POST invalid data
response = self.client.post('/accounts/create_thing/', { })
self.assertFormError(response, 'form', 'name', 'This field is required.')
self.assertFormError(response, 'form', 'description', 'This field is required.')
self.assertTemplateUsed(response, 'things/create_thing.html')
self.assertEqual(response.status_code, 200)
# Test POST valid data?
response = self.client.post('/accounts/create_thing/', { 'name': 'new name', 'description': 'new description', })
self.assertEqual(response.status_code, 200)
Source:stackexchange.com