Can't import requests in Django
I'm having problem importing requests in views.py. I've already installed requests in the environment and I already checked through Django shell by importing requests and there was no error. But every time I import requests in views.py I get the error ModuleNotFoundError. Can anyone help me.
from django.shortcuts import render
#from django.http import HttpResponse
import json
import requests
#from matplotlib.style import context
# Create your views here.
# Think of views as a place to handle your various
# web pages we are going to do this with either
# functions based view or class basesd view
def home_view(request, *args, **kwargs):
print (args, kwargs)
print ("This is the request")
print ("Request has been Sent")
putdata = {"supplier_name": "Django", "supplier_contact": "8000", "supplier_address": "America", "supplier_email": "Django@gmail.com", "supplier_state": "New York", "supplier_country": "America"}
post = requests.post("http://localhost:8085/api/supplier", json=putdata)
print(post.text)
return HttpResponse("<h1>Hello World</h1>") # string of HTML code
return render(request, "home.html", {})
I'm new to Django so forgive the messy code, I'm just trying various things in order to see how they work.
check whether you are running the script in the installed environment.
You probably haven't installed the required package. Try this in your terminal:
pip install requests
Try writing this in the list of apps installed in the project's settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Add this...
'requests',
]
I found the answer from Django Tutorial in Visual Studio Code official Docs. Turns out instead of pip install requests. I need to do python -m pip install requests.
Could you have started your Django project in virtual environment? If you have a virtual environment, can you check pip module is installed with pip3 show requests after activating it?
Example scenario:
#install venv
python3 -m venv venv
#activate venv
source venv/bin/activate
#on Windows (cmd.exe)
venv\Scripts\activate.bat
#on Windows (PowerShell)
venv\Scripts\Activate.ps1
#install requests in virtual environment
pip install request
Also if the PATH for pip is not set up on your machine, replace pip with python3 -m pip:
python3 -m pip install requests
If PIP Path exists like this:
pip3 show requests
Otherwise:
python3 -m pip show requests
Finally, make sure you choose the right interpreter.