React Native (expo) + Django JWT axios error - reactjs

Trying to make Login Screen. Using axios to get data from Django JWT url('http://127.0.0.1:8000').
Tried to find url works from Postman and also from terminal and both worked, but I got AxiosError from simulator. Does anyone know why my base url not work on React Native App?
I tried 'http://localhost:3000/' and 'http://10.0.2.2:8000'too but not worked.
This is my Codes...
LoginScreen.js
const LogInScreen = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify({ email, password });
axios
.post("http://127.0.0.1:8000/api/token/", body, config, console.log(body))
.then((res) => {
console.log("token");
AsyncStorage.setItem("access_token", res.data.access);
AsyncStorage.setItem("refresh_token", res.data.refresh);
axiosInstance.defaults.headers["Authorization"] =
"JWT " + AsyncStorage.getItem("access_token");
navigate("Home");
console.log(res);
console.log(res.data);
})
.catch((error) => console.log("error", error));
};
console.log(body) showed up {"email":"test#mail.com","password":"Test1234"}
console.log('token') not showed up, and 'error' part pop up.
Django urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/user/', include('api_user.urls')),
path('api/flashcard/', include('api_card.urls')),
]
settings.py
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
# 'rest_framework_simplejwt',
'rest_framework_simplejwt.token_blacklist',
'api_card.apps.ApiCardConfig',
'api_user.apps.ApiUserConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
CORS_ALLOW_ALL_ORIGINS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000', "http://127.0.0.1:8000"
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=90),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': False,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer', 'JWT'),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
AUTH_USER_MODEL = 'api_user.User'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
terminal worked find so i think the problem is React Native expo app part ...
$ curl -d '{"email":"test#mail.com" , "password": "Test1234"}' -H "Content-Type: application/json" "http://127.0.0.1:8000/api/token/"
{"refresh":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9....","access":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...."

Related

hi how can i put the images in my django project

how can i put the images in my django project, i have already installed pillow but when i try to save the images in the admin page it doesn't work and it doesn't show up in my detailed page, it just displays as text. I don't know what to do please help me solve this. THANKS IN ADVANCE
type here
my models file is there
from django.db import models
from django.core.validators import *
# Create your models here.
class Acueil(models.Model):
image = models.ImageField(blank=True)
class Animal(models.Model):
class Classe(models.TextChoices):
OISEAU = 'OIS'
MAMIFERE = 'MAM'
INSECTE = 'INSE'
REPTILE = 'REP'
POISSON = 'POI'
AMPHIBIEN = 'AMPH'
class Habitat (models.TextChoices):
JUNGLE = 'JUN'
SAVANE = 'SAV'
MARAI = 'MAR'
OCEAN = 'OCE'
FERME = 'FERM'
MONTAGNE = 'MON'
name = models.CharField( max_length = 50)
classe = models.CharField(choices=Classe.choices, max_length = 10 )
cris = models.CharField(max_length=20)
cut = models.FloatField(validators= [MinValueValidator(1.00), MaxValueValidator(5000)])
poids = models.FloatField(validators= [MinValueValidator(0), MaxValueValidator(100000)])
mode_life = models.CharField(max_length=1000)
comportement = models.CharField(max_length=1000)
habitat = models.CharField(choices= Habitat.choices,max_length=10)
description = models.CharField(max_length=2000)
nutrution = models.CharField(max_length=1000)
life_durée = models.IntegerField(validators= [MinValueValidator(1), MaxValueValidator(1000) ])
colors = models.CharField(max_length=25)
image = models.ImageField(blank=True)
my templates are here
{% extends 'wild/animal_base.html' %} {% block content %}
<h1>{{animal.name}}</h1>
<h2>{{animal.image}}</h2>
<ul>
<li>Classe :{{ animal.get_classe_display }}</li>
<li>Cris :{{ animal.cris}}</li>
<li>Taille :{{ animal.cut}} CM</li>
<li>Poids :{{ animal.poids}} KG</li>
<li>Habitat :{{ animal.habitat}}</li>
<li>Durée de vie :{{ animal.life_durée }} ANS</li>
<li>Nutrition :{{ animal.nutrution }}</li>
<li>Couleur :{{ animal.colors}}</li>
</ul>
<p>Comportement :{{animal.comportement}}</p>
<p>Mode de vie : {{animal.mode_life}}</p>
Retour à la liste d'animaux
{%endblock%}
settings
"""
Django settings for puerta project.
Generated by 'django-admin startproject' using Django 4.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-&i5qs$pywed8%c(t$5#=qzk3#p-+ttet_a#g&fr5f4%pa-#qw+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'wild',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'puerta.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'puerta.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Internal server error 500 while sending data from react to Django rest framework

I am making a crop prediction system where user will send some data to backend and crop_prediction function will predict a crop and send it to frontend to display it.
I checked my views.py function it is working properly on Django rest framework.
But when sending data it is giving internal server error.
Please suggest any modification in my code.
My frontend code to send data
async function userDataHandler(userData) {
const response = await fetch("http://localhost:8000/Efarma/", {
method: "POST",
body: JSON.stringify(userData),
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
}
Django views code:-
from django.shortcuts import render
from firebase import firebase
import numpy as np
# from rest_framework.parsers import JSONParses
from django.views.decorators.csrf import csrf_exempt
import pickle
from efarma import config
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer
from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
def weather_fetch(city_name):
"""
Fetch and returns the temperature and humidity of a city
:params: city_name
:return: temperature, humidity
"""
api_key = config.weather_api_key
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
temperature = round((y["temp"] - 273.15), 2)
humidity = y["humidity"]
return temperature, humidity
else:
return None
#api_view(('POST','GET',))
#permission_classes((permissions.AllowAny,))
def crop_prediction(request):
permission_classes = [permissions.IsAuthenticated]
if request.method == 'POST':
N = float(request.form['nitrogen'])
P = float(request.form['phosphorous'])
K = float(request.form['pottasium'])
ph = float(request.form['ph'])
rainfall = float(request.form['rainfall'])
city = request.form.get("city")
if weather_fetch(city) != None:
temperature, humidity = weather_fetch(city)
data = np.array([[N, P, K, temperature, humidity, ph, rainfall]])
my_prediction = pickle.load(open('cropRecommendationBackend\\model\\model.pkl','rb'))
final_prediction=my_prediction.predict(data)
value=final_prediction[0]
firebase =firebase.FirebaseApplication('https://e-farma-5dc42-default-rtdb.firebaseio.com/')
result=firebase.get(final_prediction,None)
return Response(result)
else: return Response("Some error occured")
else: return Response("Some error occured")
Settings.py file:-
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6o=k+7ec442!!jxbtwu9q-+fb%l=1t6o0z2f!(-qpm1!4a#pl^'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'efarma',
'rest_framework',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
ROOT_URLCONF = 'cropRecommendationBackend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'cropRecommendationBackend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'

localhost: 3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. REACT and DJANGO

I am able to get list of objects on http://127.0.0.1:8000/api/todos running on DJANGO,
I wanna product detail page with id, http://127.0.0.1:8000/api/todos/14.
http://127.0.0.1:8000/api/todos/14. works fine in POSTMAN, and even in chrome. but in react I get
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/todos/14' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using Axios.
Product.js
const [dataItems, setDataItems] = useState([]);
useEffect(() => {
axios
.get("http://127.0.0.1:8000/api/todos/")
.then((res) => {
console.log(res);
setDataItems(res.data);
})
.catch((err) => {
console.log(err);
});
}, []);
ProductDetail.js
const [detailItems, setDetailsItems] = useState([]);
useEffect(() => {
axios.get("http://127.0.0.1:8000/api/todos/14").then((res) => {
console.log(res);
});
}, []);
I have installed django-cors-headers and http://127.0.0.1:8000/api/todos this work fine. Here is my settings.xml for cors-headers.
Settings.xml
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hero.apps.HeroConfig',
'rest_framework.authtoken',
'users.apps.UsersConfig',
'rest_framework',
'corsheaders',
]
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',
]
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000'
]
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'todos', views.TodoView, 'todo')
urlpatterns = [
path('api/', include(router.urls)),
path('', views.home),
]
views.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'todos', views.TodoView, 'todo')
urlpatterns = [
path('api/', include(router.urls)),
]
Serializers.py
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'title', 'description', 'completed')
This api call works inside react and I can get list of object and console output
http://127.0.0.1:8000/api/todos
[
{
"id": 14,
"title": "First",
"description": "first",
"completed": false
},
{
"id": 15,
"title": "Second",
"description": "second item",
"completed": false
},
{
"id": 16,
"title": "Third",
"description": "third item",
"completed": false
}
]
http://127.0.0.1:8000/api/todos/14 doesn't work.
I have seen similar question, but I am able to make connection with localhost:3000 and get all the values here. it just for the detail object with id not showing up.
You're facing a CORS issue because your React client wants to access data from another server
You can see this topic where someone talks about using django-cors-headers with pip install django-cors-headers
Sorry, stack overflower, I have my api pointing to two urls. api/users and api/todos. I thought it was doable but, I got the error. Not really sure why, but it fixed my issues.

Django Rest Framework GET request returning Unathorized on React Frontend

it's my first question of SO. please, point out where I need to clarify at any point.
Im building a django back-end, react front-end app. I have this view that returns a 401 response whenever I try to directly access it on the front-end, even when a user is logged in. I have access to my other views but this one. It works fine in the drf browsable API.
I'm using both Session and TokenAuthentication in my default authentication classes.
Here's my base settings.py
import os
from decouple import config
import datetime
ALLOWED_HOSTS = []
BASE_DIR =
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
'rest_auth',
'rest_framework.authtoken',
'dj_rest_auth',
'allauth',
'allauth.account',
'allauth.socialaccount',
'corsheaders',
'djoser',
'dj_rest_auth.registration',
'channels',
'core'
]
SITE_ID = 1
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Whitenoise Middleware
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'home.urls'
AUTH_USER_MODEL = 'core.User'
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'core.serializers.UserSerializer'
}
ACCOUNT_ADAPTER = 'core.adapter.CustomAccountAdapter'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
REST_FRAMEWORK = {
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
#'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
# 'dj_rest_auth.jwt_auth.JWTCookieAuthentication'
],
"DEFAULT_PARSER_CLASSES": ["rest_framework.parsers.JSONParser"],
}
REST_USE_JWT = False
# JWT_AUTH_COOKIE = 'core.auth'
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1),
'USER_ID_CLAIM': 'id',
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
ASGI_APPLICATION = 'home.routing.application'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'build', 'static')
STATICFILES_DIRS = []
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
REDIS_URL = config('REDIS_URL', 'redis://localhost:6379')
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.redis.core.RedisChannelsLayer',
'CONFIG': {'hosts': [REDIS_URL]},
},
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = False
DJOSER = {
'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}',
'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': '#/activate/{uid}/{token}',
'SEND_ACTIVATION_EMAIL': True,
'SERIALIZERS': {},
}
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
#ACCOUNT_EMAIL_VERIFICATION = "mandatory"
# OLD_PASSWORD_FIELD_ENABLED = True
# PASSWORD_RESET_TIMEOUT_DAYS = 1
# ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 2
Here's the view where I first noticed the error
class StoreDetailView(RetrieveAPIView):
# Should return an object of all the attributes of a store if request.user is owner of store
serializer_class = StoreSerializer
permission_classes = (IsAuthenticated, )
def get_object(self):
try:
user = self.request.user
return Store.objects.get(owner=user)
# store = Store.objects.get(owner=self.request.user)
# return store
except ObjectDoesNotExist:
raise Http404('This store was not found for this user')
Check if the session_id or token is being passed in the request's headers.
This article explains in great detail on how to use Token based authentication with DRF.
Check if you have implemented any of the permission_classes, the functions for permissions requests exactly, if you dont allow GET method, the user cant read the object.
Here's and example I have implemented for my custom permissions:
class IsBusinessOwnerOrReadOnly(BasePermission):
"""
The request is authenticated and is the same user as the business owner, or is a read-only request.
"""
def has_permission(self, request, view):
return bool(
request.method in SAFE_METHODS or
request.user and
request.user.is_authenticated
)
def has_object_permission(self, request, view, obj):
if not isinstance(obj, Business):
raise Exception('This object is not a Business class instance')
return request.method in SAFE_METHODS or obj.owner.pk == request.user.pk

Why I am getting a Server Error(500) in production?

I created an app with DjangoREST , React and Redux it is Deployed on Heroku , but I am getting a Server Error(500) . I used allauth for token Authentication . Every urls is working fine in development but not in production .
I am successfully getting a token by /rest-auth/login/ url and the token is also passed successfully in the headers as "Authorization" : Token token .
This the error I am getting also I console.log the error -
urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from todo import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/todos/', views.TodoList.as_view()),
path('api/todos/<int:pk>/', views.TodoDetail.as_view()),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('api/user/', views.UserAPI.as_view()),
re_path(r'^', views.FrontendAppView.as_view())
]
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'dj-react-todo.herokuapp.com']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'todo',
'corsheaders' ,
'rest_framework',
'rest_framework.authtoken',
'rest_auth' ,
'allauth',
'allauth.socialaccount' ,
'allauth.account',
'rest_auth.registration',
]
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
ROOT_URLCONF = 'backend.urls'
WSGI_APPLICATION = 'backend.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication'
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build', 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = (
'content-type' ,
'xsrfheadername' ,
'xsrfcookiename',
'X-CSRFTOKEN'
)
CSRF_COOKIE_NAME = "XCSRF-TOKEN"
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = False
views.py
class TodoList(APIView):
serializer_class = TodoSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, format=None):
todos = Todo.objects.filter(user=request.user)
serializer = TodoSerializer(todos, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = TodoSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
from rest_framework import serializers
from .models import Todo
from django.contrib.auth.models import User
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'user', 'title', 'description', 'completed', 'deadline', 'crucial')
def create(self , validated_data):
return Todo.objects.create(**validated_data)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
This is how I created my actionCreator to get all the todos created by a user -
import axios from 'axios' ;
import { ADD_TODO, FETCH_TODOS, DELETE_TODO, TOGGLE_CHECKBOX, CRUCIAL_TODO} from './types' ;
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "XCSRF-TOKEN";
axios.defaults.headers.post['Access-Control-Allow-Methods'] = 'PATCH, DELETE, POST, GET, OPTIONS';
export const getTodos = () => dispatch => {
const token = localStorage.getItem('token')
const config = {
'headers': {
'Authorization': `Token ${token}` ,
}
}
if (token){
axios.get('https://dj-react-todo.herokuapp.com/api/todos/', config)
.then(res => {
dispatch({
type: FETCH_TODOS ,
payload: res.data
});
})
.catch(err => console.log(err))
}
}
I don't understand why I am getting this error , I already pass the token and I am getting the authenticated user also through that token .
I checked the heroku logs and it is also showing 500 Server Error .

Resources