Daniel Ojeda Daniel Ojeda - 1 year ago 95
Python Question

Django client test (get, post) response load data from main db instead fixtures loaded in test db

I'm new in Django, and I have this problem:
I use self.client to test routes in my app.

class BookSell(TestCase):
fixtures = [

def test_get_book_sell(self):
book = Books.objects.get(pk=1)
print(book.name)#it prints "El Quijote" in the test output
response = self.client.get('/sell/book-sell')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Book Sell")
self.assertContains(response, "El Quijote")#book name

The view method linked to that path should load some data from the database and then render it.
But when I run

python manage.py test app_name

it doesn't load data from fixtures, because the response doesn't contain "El Quijote". Only when I run:

python manage.py loaddata fixture_name.yaml ...

and then run again the tests the view method loads data from the database.

So I conclude that when I run the tests, my views methods load data from main database instead of test database

What is that I'm doing wrong?
Is there a way to load just data from test database?

django version: 1.9.4

python version: 2.7.6

I'm sure that the fixtures load with sucess in test database

Answer Source

Finally I discovered what I was doing wrong, thanks to this answer: Django: reload form data after db values change

I had a form like this:

class BookSellForm(forms.Form):

    books = [('', 'Choose a book')]
    books.extend(Books.objects.values_list('id', 'name'))
    libro = forms.ChoiceField(books)

And that was the problem, I had to change to this

class BookSellForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(BookSellForm, self).__init__(*args, **kwargs)
        books = [('', 'Choose a book')]
        books.extend(Books.objects.values_list('id', 'name'))
        self.fields['book'] = forms.ChoiceField(books)

and then everything worked fine, I hope this will be helpful to someone in the future.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download