hi how can i put the images in my django project - django-models

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'

Related

React Native (expo) + Django JWT axios error

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...."

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/'

Django Rest Framework endpoint does not work with SPA and axios, but works with other client like vscode REST Client extension

I bootstrapped this project with cookiecutter-django, and did not make any changes to the security settings or DRF endpoints. You can find settings/base.py and settings/local.py below. Currently both Django and React work on localhost. I am trying to do a crossorigin setup. E.g. React static will be served by Firebase in www.mydomain.com, and Django app will be on some other host. Thanks.
I call Axios in a React SPA like this (handleLogin is the onClick handler):
const domain = "http://localhost:8000/";
const handleLogin = () => {
axios
.post(domain + "auth-token/", {
username: username,
password: password,
})
.then((res) => {
setErrorMessage("Success res:" + JSON.stringify(res));
})
.catch((err) => {
setErrorMessage("Error err:" + JSON.stringify(err));
});
};
And I get the error:
Error err:{"message":"Network Error",
"name":"Error",
"stack":"Error: Network Error\n at createError (https://localhost:3000/taskpane.js:15266:15)\n at XMLHttpRequest.handleError (https://localhost:3000/taskpane.js:14751:14)",
"config":{"url":"http://localhost:8000/auth-token/","method":"post",
"data":"{\"username\":\"johndoe\",\"password\":\"mypass\"}",
"headers":{"Accept":"application/json, text/plain, */*",
"Content-Type":"application/json;charset=utf-8"},
"transformRequest":[null],"transformResponse":[null],
"timeout":0,"xsrfCookieName":"XSRF-TOKEN",
"xsrfHeaderName":"X-XSRF-TOKEN",
"maxContentLength":-1,"maxBodyLength":-1}}
Following vscode REST Client extension request works, e.g. I get a token:
# Send Request
POST http://127.0.0.1:8000/auth-token/
Content-Type: application/json
{
"username": "johndoe",
"password": "mypass"
}
settings/base.py:
"""
Base settings to build other settings files upon.
"""
from pathlib import Path
import environ
ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
# mysite/
APPS_DIR = ROOT_DIR / 'mysite'
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False)
if READ_DOT_ENV_FILE:
# OS environment variables take precedence over variables from .env
env.read_env(str(ROOT_DIR / '.env'))
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool('DJANGO_DEBUG', False)
# Local time zone. Choices are
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# though not all of them may be available with every OS.
# In Windows, this must be set to your system time zone.
TIME_ZONE = 'Europe/Istanbul'
# https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'
# https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# https://docs.djangoproject.com/en/dev/ref/settings/#locale-paths
LOCALE_PATHS = [str(ROOT_DIR / 'locale')]
# DATABASES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': env.db('DATABASE_URL', default='postgres:///mysite'),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
# URLS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = 'config.urls'
# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = 'config.wsgi.application'
# APPS
# ------------------------------------------------------------------------------
DJANGO_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# "django.contrib.humanize", # Handy template tags
'django.contrib.admin',
'django.forms',
]
THIRD_PARTY_APPS = [
'crispy_forms',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
]
LOCAL_APPS = [
'mysite.users.apps.UsersConfig',
# Your stuff: custom apps go here
'mysite.tmp.apps.TmpConfig',
]
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# MIGRATIONS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules
MIGRATION_MODULES = {'sites': 'mysite.contrib.sites.migrations'}
# AUTHENTICATION
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model
AUTH_USER_MODEL = 'users.User'
# https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url
LOGIN_REDIRECT_URL = 'users:redirect'
# https://docs.djangoproject.com/en/dev/ref/settings/#login-url
LOGIN_URL = 'account_login'
# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = [
# https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
# https://docs.djangoproject.com/en/dev/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'},
]
# MIDDLEWARE
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#middleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# STATIC
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR / 'staticfiles')
# https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [str(APPS_DIR / 'static')]
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# MEDIA
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR / 'media')
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
{
# https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
'DIRS': [str(APPS_DIR / 'templates')],
'OPTIONS': {
# https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
# https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
# https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'mysite.utils.context_processors.settings_context',
],
},
}
]
# https://docs.djangoproject.com/en/dev/ref/settings/#form-renderer
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = 'bootstrap4'
# FIXTURES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs
FIXTURE_DIRS = (str(APPS_DIR / 'fixtures'),)
# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly
SESSION_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly
CSRF_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-browser-xss-filter
SECURE_BROWSER_XSS_FILTER = True
# https://docs.djangoproject.com/en/dev/ref/settings/#x-frame-options
X_FRAME_OPTIONS = "DENY"
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
'DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend',
)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-timeout
EMAIL_TIMEOUT = 5
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL.
ADMIN_URL = 'admin/'
# https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = [('''John Doe''', 'me#johndoe.com')]
# https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# LOGGING
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#logging
# See https://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
}
},
'root': {'level': 'INFO', 'handlers': ['console']},
}
# django-allauth
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', False)
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_AUTHENTICATION_METHOD = 'username'
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_EMAIL_REQUIRED = True
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_ADAPTER = 'mysite.users.adapters.AccountAdapter'
# https://django-allauth.readthedocs.io/en/latest/configuration.html
SOCIALACCOUNT_ADAPTER = 'mysite.users.adapters.SocialAccountAdapter'
# django-rest-framework
# -------------------------------------------------------------------------------
# django-rest-framework - https://www.django-rest-framework.org/api-guide/settings/
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
}
# django-cors-headers - https://github.com/adamchainz/django-cors-headers#setup
CORS_URLS_REGEX = r'^/api/.*$'
# Your stuff...
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = 'me#johndoe.com'
SERVER_EMAIL = 'me#johndoe.com'
settings/local.py:
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="mysecret",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1"]
# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend"
)
# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
INSTALLED_APPS += ["debug_toolbar"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
# django-extensions
# ------------------------------------------------------------------------------
# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration
INSTALLED_APPS += ["django_extensions"] # noqa F405
# Your stuff...
# ------------------------------------------------------------------------------
# just use sqlite for the time being
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ROOT_DIR / 'db.sqlite3',
}
}

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