'What is equivalent to TestCase.client in normal script

For example with TestCase I can check login post and so on with self.client

class TestMyProj(TestCase):
   response = self.client.login(username="[email protected]", password="qwpo1209")

   response = self.client.post('/cms/content/up',
        {'name': 'test', '_content_file': fp},
        follow=True)

However now I want to use this in script not in test case.

because this is very useful to make initial database.

I want to do like this.

def run():
   response = client.login(username="[email protected]", password="qwpo1209")    
   with open('_material/content.xlsx','rb') as fp:
       response = client.post('/cms/content/up',
       {'name': 'faq_test', 'scenario_content_file': fp})

What is equivalent to TestCase.client in normal script??


More details

If there is not file upload, I can make database directory from model.

However, I want to upload file and parse then put into database, same as user does. (via form_valid and so on)

so, I want to use post for url from script.


My Solution

Use from django.test.client import Client as Willem Van Onsem mensioned.

somehow client.login returns True not response.

So, I use post to login

def run():
    client = Client()
    #response = client.login(username="[email protected]", password="guest")# it doesn't work some how.
    response = client.post('/login/', {'username': '[email protected]', 'password': 'guest'},follow=True)
    with open('_material/content.xlsx','rb') as fp:
        response = client.post('/cms/content/up',
        {'name': 'test','is_all':"True", '_content_file': fp})


Solution 1:[1]

It is a Client object [Django-doc], so:

from django.test.client import Client

def run():
    client = Client()
    response = client.login(username="[email protected]", password="qwpo1209")
    response = client.post(
        '/cms/content/up',
        {'name': 'test', '_content_file': fp},
        follow=True
    )

The documentation discusses the parameters that can be passed when constructing a Client object.

Solution 2:[2]

Generally I recommend to create command to make initial database instead of using the Client class that we can use to test the application. https://docs.djangoproject.com/en/4.0/howto/custom-management-commands/ You can also take advantage of bulk methods to create many instances in a single query.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem
Solution 2 Dominik