0

1.env

  • python : 3.8.14
  • django version : '4.2.4'

2.Purpose

  • Make sure that the static file is saved
  • Make sure that the static file can be accessed from the web browser

3.Issue

The problem is that after running django server, the static file can be accessed through url, but not in the unitest environment.

For example, suppose a file is stored in the following path

'MAPPER  #<- project dir  
 |-datasets #<-app name
    |-static
       |-datasets
          |-images
             |-Recursion Cellular Image Classification.jpeg

3.1 Access the browser after running the server

  • enter the following path into the browser to confirm that it works well. http://localhost:8000/static/datasets/static/datasets/images/Recursion Cellular Image Classification.jpeg

3.2 unittest

  • get a 404 status code. and cannot get the image file
from django.test import Client
client = Client()
res_redirect = self.client.get(res.url)

4. try

I tried using requests.get , but i didn't work requests.get(http://localhost:8000/static/datasets/static/datasets/images/Recursion Cellular Image Classification.jpeg)

5. Question

SO this is my question, how can i access file through url in unittest env

3
  • Try replacing spaces with underscore in filename and check. Commented Aug 11, 2023 at 2:56
  • tks reply , but it didn't work. Commented Aug 11, 2023 at 7:20
  • is allow setting.py static files ? Commented Aug 11, 2023 at 13:09

1 Answer 1

0

You will need to URL encode to properly handle the spaces in the URL. a [space] character is %20, eg,

requests.get(
    'http://localhost:8000/static/datasets/static/datasets/images/Recursion%20Cellular%20Image%20Classification.jpeg'
)

(Don't forget the quotes)

However, seeing as you are working with a property or field, res.url you'll need to pass it to a function to urlEncode it. As you are already using requests you can use:

#safe argument allows the / and : in http://localhost:80000 to be unencoded
encoded_url = requests.utils.quote(res.url, safe="/:")

requests.get(encoded_url) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.