I have two django applications, currently running on localhost. I plan to have them on two separate servers, but for now, they are running on my machine.
App A is running on :8000
App B is running on :8010
When I try to make a request from A to B by using:
import requests
requests.post('http://0.0.0.0:8010/api/plan', data=post_data)
I get a connection error:
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='0.0.0.0', port=8010): Max retries exceeded with url: /api/plan (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f82fed36630>: Failed to establish a new connection: [Errno 111] Connection refused',))
In my B app I have ALLOWED_HOSTS = ['*']
Anyone has any idea what am I missing?
You should add cors-headers to your projects settings.py
For example:
INSTALLED_APPS = [
"corsheaders",
# ...
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
# ...
]
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_ALL_METHODS = [
"GET", "POST" # add allowed methods here
]
CORS_URLS_REGEX = r"^/api/.*$"
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
Related
So I have a backend with django and I am using react native for frontend. I added a emulator in android studio.
And when I start the backend like: python manage.py runserver I can run also the frontend with expo start.
But now I want to fetch the data with react native. So I start the backend with:
python manage.py runserver 192.168.1.68:19000 - settings file of django:
INSTALLED_APPS = [
'corsheaders',
'DierenWelzijnAdmin.apps.DierenwelzijnadminConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ALLOWED_HOSTS = ['192.168.1.68', '127.0.0.1', ]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
"http://localhost:8081",
"http://localhost:19006",
"http://localhost:19002",
"http://192.168.1.69:8000",
"http://192.168.1.68:19000",
]
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
And react native service:
export const fetchCategoryData = async () => {
try {
const response = await fetch("http://192.168.1.68:19000/animal/categories/main_groups/", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
return await response.json();
//setCategoryData(data);
} catch (error) {
console.error("There was a problem with the fetch operation:", error);
throw error;
}
};
And when I then start the react native app with expo start and I do a r after a.
I get this message:
warn No apps connected. Sending "reload" to all React Native apps failed. Make sure your app is running in the simulator or on a phone connected via USB.
The emulator I installed from android studio is: Pixel 2 XL and if I do: adb devices
I see the emulator:
List of devices attached
emulator-5554 device
And I already whiped the data several times from the emulator.
Question:
How to run the react native for fetching data from the backend?
Oke, I changed the backend to:
192.168.1.68:8000
and in frontend also:
192.168.1.68:8000
and it works now :)
This was indeed very stupid of me. Because I did fetch('//192.168.1.68:19000'). But that is my emulator host. Of course that doesn't work
I am building a project with Vue.js on the front-end and Django on the back-end. I am using port 8000 for Django and port 8080 for Vue.js. Every time I route to something on the 8080 port, I get this error like this that gets printed out every second:
[01/Apr/2022 17:18:57] "GET /ws HTTP/1.1" 404 2292
Not Found: /ws
This is my vue.config.js:
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'^/ws': {
target: 'http://localhost:8000'
}
}
}
})
Here is the Django urls.py:
urlpatterns = [
path('favicon.ico', include('django.contrib.staticfiles.urls')),
path('admin/', admin.site.urls),
path('api/', include('users.urls')),
path('api/', include('leagues.urls')),
]
I can't figure out why this happens or how to fix it.
In your proxy config, you probably want something like this:
'^/ws': {
target: 'localhost:8080',
},
... basically, don't proxy the /ws path, send those requests to the devserver. Or maybe there is a common prefix for your django endpoints you can use to qualify paths that should be proxied.
I found the solution to a similar way as Thomas. It seems that the default behavior of setting a proxy in vue.config.js is to send a GET request to /ws. I had to change the /ws in Thomas's answer to /api since that is what the back-end uses for their routes, so I ended up with this:
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:8000'
}
}
}
})
having the problem to find a way how to configure properly front end app in Angular 9 consuming back REST webservice. On the remote server with the static IP i run my angular dev server with (i know it is only for dev purposes but i want to get rid of this error first)
ng serve --host 0.0.0.0 --port 80
so i can access it from the outside. then i have my django app also with the dev server at
127.0.0.1:8000
In the angular service.ts file i am trying to inject the header
export class FlightService {
httpOptions = {
headers: new HttpHeaders({
'Access-Control-Request-Method':'GET',
'Access-Control-Request-Headers':'origin, x-requested-with, accept'
})
};
private endpoint = 'http://127.0.0.1:8000/services';
constructor(private http: HttpClient) { }
//GET All Services
getAllServices(): Observable<any>{
return this.http.get(this.endpoint, this.httpOptions)
}
}
In the settings.py of my django backend i have put at the top the corsheaders module:
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
and allowed all the host (after trying many things with whitelist which none of worked:
CORS_ALLOW_CREDENTIALS = False
CORS_ALLOW_METHODS = [
# 'DELETE',
'GET',
'OPTIONS'
#'PATCH',
#'POST',
#'PUT',
]
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'x-forwarded-for'
]
But I fail all the time. After i added the httpOptions i get the error in the browser:
http.js:2403 Refused to set unsafe header "Access-Control-Request-Method"
and as well:
Refused to set unsafe header "Access-Control-Request-Headers"
So at least i know the Angular is trying to append it.
Please help, how to approach it? I guess the problem is on the client side. I also tried to set up Nginx with a proxy to Angular dev, but also fail to append the headers on the Nginx configuration.
These CORS headers are not for you to set, the browser will do it automatically if it detects that you are trying to access cross domain resources.
So I have this Django application with django-summernote, and I'm having trouble uploading image files via the editor. When I click the upload button and choose an image from my computer, I get an error saying "Failed to save attachment". And in the console, I see this error: "POST /summernote/upload_attachment/ 500". Let me show you my code. settings.py
INSTALLED_APPS = [
...
'django_summernote',
...
]
...
DEBUG = True
...
SUMMERNOTE_CONFIG = {
'iframe': True,
'lang' : 'ko-KR',
'summernote': {
'width': '100%',
'height': '450px',
'placeholder':'First sentence',
'toolbar': [
['style', ['style',]],
['font', ['fontsize', 'bold', 'italic', 'strikethrough']],
['color', ['forecolor', ]],
['para', ['ul', 'ol', 'height']],
['insert', ['link']],
['misc', ['picture', 'fullscreen', 'print', 'help', ]],
],
},
'js': (
'static/summernote-ext-print.js',
),
'js_for_inplace': (
'/static/summernote-ext-print.js',
),
'css': (
'//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css',
'/mvp/static/summernote.css',
),
'css_for_inplace': (
'//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css',
'/summernote.css',
),
'codemirror': {
'theme': 'base16-dark',
'mode': 'htmlmixed',
'lineNumbers': 'true',
},
'lazy': False,
}
SUMMERNOTE_THEME = 'bs4'
X_FRAME_OPTIONS = 'SAMEORIGIN'
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
path('summernote/', include('django_summernote.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I don't see what I've done wrong. Everything else except uploading image works fine. BTW, I'm using Django 3.x and Bootstrap 4.x.
+++ If it gives you any further info: I also keep getting these errors in the console as well. Might be related?
Refused to apply style from '<myURL>/summernote.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Failed to load resource: the server responded with a status of 404 () ... summernote-ext-print.js Failed to load resource: the server responded with a status of 500 () .../summernote/upload_attachment/
This has been making me so frustrated for days. I'd very much appreciate your help. :)
I'm currently trying to setup a Google app engine flex using a django framework with django-channels. for my current project i need a websocket, so i'm trying to reconstruct the tutorial offered on the website by Django-channels: https://channels.readthedocs.io/en/latest/tutorial/
Currently I'm stuck on adding redis to my google-app-flex instance. I followed the google documentation on setting up a redis connection - unfortunatly the example is in Flask: google doc
I assume my error is trivial, and i just need to connect django CHANNEL_LAYERS to redis proporly.
executing sudo gcloud redis instances describe <redisname> --region=us-central1 gives me following responce:
Image: "Redis Describtion"
executing sudo gcloud app describe, this responce:
I configured my app.yaml as follows:
# app.yaml
# [START runtime]
runtime: python
env: flex
entrypoint: daphne django_channels_heroku.asgi:application --port $PORT --bind 0.0.0.0
runtime_config:
python_version: 3
automatic_scaling:
min_num_instances: 1
max_num_instances: 7
# Update with Redis instance IP and port
env_variables:
REDISHOST: '<the ip in "host" from "Redis Describtion" image above>'
REDISPORT: '6379'
# Update with Redis instance network name
network:
name: default
# [END runtime]
..and in my settings.py i added this as the redis connection (which feels really wrong btw):
#settings.py
import redis
#settings.py stuff...
#connect to redis
redis_host = os.environ.get('REDISHOST', '127.0.0.1')
redis_port = int(os.environ.get('REDISPORT', 6379))
redis_client = redis.StrictRedis(host=redis_host, port=redis_port)
# Channels
ASGI_APPLICATION = "django_channels_heroku.routing.application"
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
what am i doing wrong. how do i connect to Redis using Django correctly?
here are some Links:
https://cloud.google.com/memorystore/docs/redis/connect-redis-instance-flex
Django, Redis: Where to put connection-code
Deploying Django channels app on google flex engine
How to connect to Redis instance (memorystore) from Google's Standard App Engine (Python 3.7)
https://cloud.google.com/memorystore/docs/redis/connect-redis-instance-flex
https://cloud.google.com/memorystore/docs/redis/quickstart-gcloud
My mistake is in the settings.py:
Correct version:
#settings.py
#settings stuff...
redis_host = os.environ.get('REDISHOST', '127.0.0.1')
redis_port = int(os.environ.get('REDISPORT', 6379))
#redis_client = redis.StrictRedis(host=redis_host, port=redis_port) #this is not needed
# Channels
ASGI_APPLICATION = "django_channels_heroku.routing.application"
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [(redis_host, redis_port)],
},
},
}