I'm currently trying to make a dating app, my first project from scratch. I downloaded a sample project to use as a reference and I want to fire it up on my local server and see what the actual website looks like so I can play around with it and understand the code better. However, after running downloading it through a zip file and then trying to run it on buy local server I get. When I go to the site, I get;
Exception Value:
'AnonymousUser' object is not iterable
Here is a link to the project and also settings.py
project- https://github.com/TheCodingCrusader/Django_Tinder
here is my settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8-jze0w4ek6d+d1_tdij96dg5xk299d4etey_p=qrg^2dh+58e'
# 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',
#mine
'registration',
'app',
]
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 = 'music_tinder.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 = 'music_tinder.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',
},
]
# 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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
STATICFILES_STORAGE = 'custom_storages.StaticStorage'
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATICFILES_DIR = (
STATIC_PATH,
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'index'
original projects settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u)-vf#0bv3!3)g-58(pox4_^-o$m8#5%idk3bmegowsimy%6)l'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*', 'localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
'app',
'storages',
]
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 = 'music_tinder.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 = 'music_tinder.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
#DATABASES['default'] = dj_database_url.config(default='sqlite3://...')
#DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
#DATA
DATABASES['default'] = dj_database_url.parse('sqlite3://...', conn_max_age=600)
#import dj_database_url
#DATABASES = {'default': dj_database_url.config(default=os.environ['DATABASE_URL'])}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/howto/static-files/
#STATIC_URL = '/static/'
#MEDIA_URL = '/media/'
AWS_STORAGE_BUCKET_NAME = 'faketinder'
AWS_ACCESS_KEY_ID = os.environ['AWS_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_KEY']
AWS_S3_CUSTOM_DOMAIN = 's3.amazonaws.com/' + AWS_STORAGE_BUCKET_NAME
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
STATICFILES_STORAGE = 'custom_storages.StaticStorage'
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
AWS_HEADERS = {
'Access-Control-Allow_Origin' : '*'
}
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATICFILES_DIR = (
STATIC_PATH,
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'index'
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from . import forms
from django.shortcuts import redirect
from . import models
from .models import UserProfile
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
import os
from django.core import serializers
import json
#login_required
def index(request):
try:
user = (User.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0])
except IndexError:
user = None
print (User.username)
try:
bio = models.UserProfile.objects.get(user=request.user).bio
except models.UserProfile.DoesNotExist:
create = UserProfile.objects.get_or_create(user = request.user)
return redirect('profile')
friend = models.UserProfile.objects.get(user=request.user).friends.all()
context = dict(user = user, friend = friend)
return render(request, 'index.html', context)
def create_vote(request, user_id, vote):
user = User.objects.get(pk=user_id)
models.UserVote.objects.create(
user = user,
voter = request.user,
vote = vote
)
return redirect('index')
#login_required
def nice(request, user_id):
return create_vote(request, user_id, True)
#login_required
def nope(request, user_id):
return create_vote(request, user_id, False)
#login_required
def profile(request):
info = User.objects.get(username=request.user)
user = models.UserProfile.objects.get(user=request.user)
name = info.first_name
last = info.last_name
email = info.email
bio = user.bio
website = user.website
if request.method == 'POST':
form = UserCreationForm(request.POST, request.FILES)
if form.is_valid:
if request.POST['first_name'] != name:
info.first_name = request.POST['first_name']
else:
info.name = name
if request.POST['last_name'] != last:
info.last_name = request.POST['last_name']
else:
info.last = last
if request.POST['email'] != email:
info.email = request.POST['email']
else:
info.email = email
if request.POST['bio'] != bio:
user.bio = request.POST['bio']
else:
user.bio = bio
if request.POST['website'] != website:
user.website = request.POST['website']
else:
user.bio = bio
if len(request.FILES) != 0:
user.photo = request.FILES['image']
if info.check_password(request.POST['password']) ==True:
if request.POST['new_password'] != "":
info.set_password(request.POST['new_password'])
info.save()
user.save()
context = dict(info=info, user = user)
return render(request, "profile.html", context)
def create_vote(request, user_id, vote):
user = User.objects.get(pk=user_id)
models.UserVote.objects.create(
user=user,
voter=request.user,
vote=vote
)
if vote:
if models.UserVote.objects.filter(
user = request.user,
voter=user,
vote=True
).count():
npm = models.UserProfile.objects.get(user=request.user)
npm.friends.add(User.objects.get(username=user.username))
npm = models.UserProfile.objects.get(user=user)
npm.friends.add(User.objects.get(username=request.user))
npm.save()
return render(request, 'match.html', dict(
match=user,
))
return redirect('index')
def network(request):
friend = models.UserProfile.objects.get(user=request.user).friends.all()
context = dict(friend = friend)
return render(request, 'network.html', context)
'DATABASE_URL' is not defined in settings.py, default is fetched from user variable which i dont think you have configureddefault=os.environ['DATABASE_URL'])
Since he hasn't given you the DBConfigration details, you cannot fire it up and tinker with it. What u can do see is to create a new project and copy the views, models, urls.py and start it fresh
Related
I have a Django Iframe that is working fine on Chrome and Mozilla but in Safari I'm getting the above mentioned error. I think the cookies are not detected because when I checked it was empty and no CSRF tokens were found. I am attaching the screenshots.
Error Displayed in browsers console log Browser Cookies is empty. This is my settings.py file:
"""
Django settings for shopify_django_app project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
from shopify_app import *
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Make this unique and store it as an environment variable.
# Do not share it with anyone or commit it to version control.
SECRET_KEY = config('DJANGO_SECRET')
DEBUG = int(config('DEBUG'))
# SHOPIFY SETTINGS
SHOPIFY_API_KEY = config('SHOPIFY_API_KEY')
SHOPIFY_API_SECRET = config('SHOPIFY_API_SECRET')
SHOPIFY_APP_NAME = config('SHOPIFY_APP_NAME')
SHOPIFY_API_VERSION = 'unstable'
SHOPIFY_TEST = config('SHOPIFY_TEST') # For the purpose of Shopify Payments
INTERNAL_IPS = ('127.0.0.1',)
ALLOWED_HOSTS = config('DJANGO_ALLOWED_HOSTS').split(" ")
CSP_FRAME_ANCESTORS = ("'self'", 'https://*.myshopify.com')
# default source as self
CSP_DEFAULT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'", "https://fonts.gstatic.com")
# style from our domain and bootstrapcdn
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", "https://fonts.googleapis.com")
# scripts from our domain and other domains
CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'")
# images from our domain and other domains
CSP_IMG_SRC = ("'self'",
"https://*.s3.amazonaws.com", "data:", "https://cdn.shopify.com")
SESSION_COOKIE_SAMESITE = None
SESSION_COOKIE_SECURE = True
XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'PUT']
CSRF_COOKIE_SAMESITE = None
CSRF_COOKIE_SECURE = True
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
CSRF_TRUSTED_ORIGINS = [config('CSRF_TRUSTED_ORIGINS')]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Local
'shopify_app.apps.ShopifyAppConfig',
'home.apps.HomeConfig',
'notification',
'api',
'payment',
'debug_toolbar',
# 3rd party
'django_extensions',
'rest_framework',
'rest_framework.authtoken',
'django_celery_beat',
'storages',
# 'iframetoolbox',
]
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',
'csp.middleware.CSPMiddleware',
'shopify_app.middleware.LoginProtection',
'debug_toolbar.middleware.DebugToolbarMiddleware',
# 'iframetoolbox.middleware.IFrameFixMiddleware',
# 'shopify_app.iframe_middleware.SafariIFrameFixMiddleware'
]
ROOT_URLCONF = 'shopify_django_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
"APP_DIRS": True,
'DIRS': [],
'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',
'shopify_app.context_processors.current_shop',
],
},
},
]
WSGI_APPLICATION = 'shopify_django_app.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'),
# }
# }
DATABASES = {
'default': {
'ENGINE': config('SQL_ENGINE'),
'NAME': config('SQL_DATABASE'),
'USER': config('SQL_USER'),
"PASSWORD": config('SQL_PASSWORD'),
"HOST": config('SQL_HOST'),
"PORT": config('SQL_PORT'),
}
}
# 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',
},
]
DATA_UPLOAD_MAX_MEMORY_SIZE = None
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# AWS Settings
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
DEFAULT_FILE_STORAGE = config('DEFAULT_FILE_STORAGE')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
if DEBUG:
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_QUERYSTRING_AUTH = False
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
else:
CLOUDFRONT_DOMAIN = config('AWS_CLOUDFRONT_DOMAIN')
CLOUDFRONT_DOMAIN_ID = config('AWS_CLOUDFRONT_ID')
AWS_S3_CUSTOM_DOMAIN = CLOUDFRONT_DOMAIN
AWS_DEFAULT_ACL = None
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = f'{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/'
STATICFILES_LOCATION = 'static'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# Redis Settings
REDIS_HOST = config('REDIS_HOST')
REDIS_PORT = config('REDIS_PORT')
# SNS Settings
SNS_ACCESS_KEY_ID = config('SNS_ACCESS_KEY_ID')
SNS_SECRET_ACCESS_KEY = config('SNS_SECRET_ACCESS_KEY')
SNS_REGION_NAME = config('SNS_REGION_NAME')
ANDROID_PLATFORM_APP_ARN = config('ANDROID_PLATFORM_APP_ARN')
IOS_PLATFORM_APP_ARN = config('IOS_PLATFORM_APP_ARN')
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
AUTH_USER_MODEL = 'shopify_app.User'
# CELERY SETTINGS
CELERY_BROKER_URL = config('CELERY_BROKER_URL')
CELERY_RESULT_BACKEND = config('CELERY_RESULT_BACKEND')
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Kolkata'
# CELERY BEAT SETTINGS
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# EMAIL SETTINGS
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_USE_TLS = True
EMAIL_PORT = config('EMAIL_PORT')
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
Need help. I am stuck with this issue for days.
I have a bug and not sure how to fix it, I've been writing an e-comm site and all of a sudden I'm getting a 404 page, Everything was working fine. The bug report tells me that the path matched the last one, but still getting 404. It's not only one app, it's all of them. I just have no clue how to fix this.
Settings:
from pathlib import Path
import environ
import os
import dj_database_url
env = environ.Env()
# read the .env file
environ.Env.read_env()
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = env('SECRET_KEY')
DEBUG = True
ALLOWED_HOSTS = ['*']
TAX_RATE_PERCENTAGE = 23
FREE_DELIVERY_THRESHOLD = 200
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sitemaps',
'django.contrib.sites',
'cloudinary_storage',
'cloudinary',
'allauth',
'allauth.account',
'allauth.socialaccount',
'mathfilters',
'crispy_forms',
'ckeditor',
'home',
'boutique',
'bag',
'checkout',
'profiles'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'IMC.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / "templates"],
'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',
'django.template.context_processors.media',
'bag.contexts.bag_contents',
],
'builtins': [
'crispy_forms.templatetags.crispy_forms_tags',
'crispy_forms.templatetags.crispy_forms_field',
]
},
},
]
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "None"
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False
ACCOUNT_USERNAME_MIN_LENGTH = 3
LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'
ACCOUNT_LOGOUT_REDIRECT_URL = '/'
SITE_ID = 1
WSGI_APPLICATION = 'IMC.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/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.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = 'static_root'
# WHITENOISE - static storage
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
# CLOUDINARY for media storage
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
},
}
# STRIPE
STRIPE_CURRENCY = 'eur'
if "DEV" in os.environ:
STRIPE_PUBLIC_KEY = env('STRIPE_PUBLIC_KEY')
STRIPE_SECRET_KEY = env('STRIPE_SECRET_KEY')
STRIPE_WH_SECRET = env('STRIPE_WH_SECRET')
else:
STRIPE_PUBLIC_KEY = os.environ.get('STRIPE_PUBLIC_KEY')
STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY')
STRIPE_WH_SECRET = os.environ.get('STRIPE_WH_SECRET')
# SESSION_COOKIE_SECURE = True
# SECURE_BROWSER_XSS_FILTER = True
# SECURE_CONTENT_TYPE_NOSNIFF = True
# SECURE_HSTS_SECONDS = 3153600
# SECURE_REDIRECT_EXEMPT = []
# SECURE_SSL_REDIRECT = True
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# EMAIL
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
NOTIFY_EMAIL = os.environ.get('NOTIFY_EMAIL')
DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER')
# CLOUDINARY_CONFIG
if "DEV" in os.environ:
CLOUDINARY_STORAGE = {
'CLOUD_NAME': env('CLOUD_NAME'),
'API_KEY': env('API_KEY'),
'API_SECRET': env('API_SECRET'),
}
else:
CLOUDINARY_STORAGE = {
'CLOUD_NAME': os.environ.get('CLOUD_NAME'),
'API_KEY': os.environ.get('API_KEY'),
'API_SECRET': os.environ.get('API_SECRET'),
}
Root-URLS:
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.contrib import admin
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import path, include
from django.views.generic.base import RedirectView
from home.views import IndexView
urlpatterns = [
path('', include('home.urls')),
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('boutique/', include('boutique.urls')),
path('bag/', include('bag.urls', namespace='bag')),
path('checkout/', include('checkout.urls', namespace='checkout')),
path('profiles/', include('checkout.urls', namespace='profiles')),
path('favicon.ico', RedirectView.as_view(
url=staticfiles_storage.url('img/favicon.ico'))),
url(r'^.*/$', IndexView.as_view())
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
App-urls:
from django.urls import path
from home.views import (
ContactView, IndexView,
TermsView, GalleryView,
aboutview, PrivacyView
)
urlpatterns = [
path('', IndexView.as_view(), name='home'),
path('about/', aboutview, name='about'),
path('gallery/', GalleryView.as_view(), name='gallery'),
path('contact/', ContactView.as_view(), name='contact'),
path('terms/', TermsView.as_view(), name='terms'),
path('privacy/', PrivacyView.as_view(), name='privacy'),
]
APP-View:
from django.conf import settings
from django.contrib import messages
from django.core.mail import send_mail
from django.shortcuts import reverse, render
from django.views import generic
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from .forms import ContactForm
from boutique.models import Product
from .models import (About, Scarfs, Paintings,
ImageGallery, Home, PrivacyPolicy,
TermsConditions, Comment)
class IndexView(ListView):
model = Home
template_name = "home/index.html"
context_object_name = "home"
def get_context_data(self, **kwargs):
comments = Comment.objects.all()
context = super().get_context_data(**kwargs)
context['comments'] = comments
return context
def aboutview(request):
feat_item = Product.objects.filter(feat_item=True)
about = About.objects.all()
scarfs = Scarfs.objects.all()
paintings = Paintings.objects.all()
context = {
'feat_item': feat_item,
'about': about,
'scarfs': scarfs,
'paintings': paintings,
}
return render(request, "home/about.html", context)
class GalleryView(ListView):
model = ImageGallery
template_name = "home/gallery.html"
context_object_name = "images"
class TermsView(ListView):
model = TermsConditions
template_name = "home/terms.html"
context_object_name = "terms"
class PrivacyView(ListView):
model = PrivacyPolicy
template_name = "home/privacy.html"
context_object_name = "policys"
class ContactView(generic.FormView):
form_class = ContactForm
template_name = "home/contact.html"
def get_success_url(self):
return reverse("contact")
def form_valid(self, form):
""""Getting clean data from the form and creating
a message to get sent to default email."""
messages.success(self.request,
"Thank you for getting in touch with us. We have received your message.")
name = form.cleaned_data.get('name')
email = form.cleaned_data.get('email')
message = form.cleaned_data.get('message')
full_message = f"""
Received Message/Comment below from:
Name: {name}
Email: {email},
___________________________
Message/Comment:
{message}
"""
send_mail(
subject="Message/Comment from Webpage contact form",
message=full_message,
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=[settings.NOTIFY_EMAIL]
)
return super(ContactView, self).form_invalid(form)
Django Error page:
All apps error page:
Hi There actually i am creating a notes taking app using django. For better ux i have used django ckeditor for providing a good editor to write beautiful and informative notes. I have used django.ckeditor richtextfield for this purpose. Now i want to encrypt the data of this text field so it can be stored safefly. I have used djanog-cryptography package and used encrypt method.
Problem -: When i am retreiving the note_contents in my template its showing nothing.
I am attaching my views and models and settings.py
views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . models import UserCreatedNote
from . forms import AddNoteForm
# Create your views here.
#login_required
def notes(request):
if request.method=='POST':
form = AddNoteForm(request.POST)
if form.is_valid():
form_data = form.save(commit=False)
form_data.user = request.user
form_data.save()
notes = UserCreatedNote.objects.filter(user=request.user)
form = AddNoteForm()
context = {'notes': notes,'add_note_form':form}
return render(request,'usernotes.html',context)
notes = UserCreatedNote.objects.filter(user=request.user)
form = AddNoteForm()
context = {'notes': notes,'add_note_form':form}
return render(request,'usernotes.html',context)
#login_required
def edit(request,id):
note = get_object_or_404(UserCreatedNote, pk=id)
if request.method == 'POST':
form = AddNoteForm(request.POST, instance=note)
if form.is_valid():
form_data = form.save(commit=False)
form_data.user = request.user
print(form_data.id)
form_data.save()
form = AddNoteForm(instance=note)
context={'note':note,'u_form':form}
return render(request,'edit_note.html',context)
form = AddNoteForm(instance=note)
context={'note':note,'u_form':form}
return render(request,'edit_note.html',context)
#login_required
def delete(request,id):
note = UserCreatedNote(id=id,user=request.user)
note.delete()
return redirect('/user/notes/')
settings.py
"""
Django settings for keepsafe project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = config('DEBUG')
SECRET_KEY = config('SECRET_KEY')
# 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!
# SECURITY WARNING: don't run with debug turned on in production!
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ALLOWED_HOSTS = ['*']
AUTH_USER_MODEL = "useraccounts.keepsafeusermodel"
AUTHENTICATION_BACKENDS = (
'useraccounts.backends.CaseInsensitiveModelBackend',
)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'crispy_forms',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'useraccounts.apps.UseraccountsConfig',
'notes.apps.NotesConfig',
'django_cleanup.apps.CleanupConfig',
'ckeditor',
]
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 = 'keepsafe.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['notes/templates/notes','useraccounts/templates/useraccounts','keepsafe/templates/keepsafe'],
'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 = 'keepsafe.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '',
'USER':'',
'PASSWORD':'',
'HOST':''
}
}
# 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 = 'Asia/Calcutta'
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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = "bootstrap4"
LOGIN_REDIRECT_URL = 'user_profile'
LOGIN_URL = 'user_login'
if not DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST ='smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = ''
CKEDITOR_CONFIGS = {
'default': {
# 'toolbar': None, You can change this based on your requirements.
'width': 'auto',
},
}
# CRYPTOGRAPHY_BACKEND = 'cryptography.hazmat.backends.default_backend()'
# CRYPTOGRAPHY_DIGEST = 'cryptography.hazmat.primitives.hashes.SHA256'
# CRYPTOGRAPHY_KEY = None
# CRYPTOGRAPHY_SALT = 'django-cryptography'
# SIGNING_BACKEND = 'django_cryptography.core.signing.TimestampSigner'
django_heroku.settings(locals())
https://django-cryptography.readthedocs.io/en/latest/settings.html
when i use this in my settings it throws an error that 'str has no object digest_size' something.
Models.py
from django.db import models
from django.contrib.auth import get_user_model
from ckeditor.fields import RichTextField
from django_cryptography.fields import encrypt
# Create your models here.
class UserCreatedNote(models.Model):
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
note_title = models.CharField(default='',max_length=100,blank=True,null=True)
note_tags = encrypt(models.CharField(default='',max_length=20,blank=True,null=True))
note_contents = RichTextField(default='',max_length=1000,blank=True,null=True)
creation_time = models.DateTimeField(auto_now_add=True)
last_modified_time = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-creation_time',]
def __str__(self):
return str(self.user)
class UserQueries(models.Model):
email = models.TextField(default="",primary_key=True,max_length=80)
name = models.CharField(default="",max_length=80)
subject = models.CharField(default="",max_length=100)
message= models.CharField(default="",max_length=5000)
def __str__(self):
return self.name
I am quite new to django and i am trying to use Djoser for Authentication but i am getting "Authentication credentials were not provided" on every call. Following is my settings file.
"""
Django settings for django_dir project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
import environ
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_DIR = environ.Path(__file__) - 2
APPS_DIR = ROOT_DIR.path('my_apps')
MEDIA_ROOT = str(APPS_DIR('media'))
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
# APPS_DIR = os.path.join(BASE_DIR, 'my_apps'),
env = environ.Env()
# STATIC FILE CONFIGURATION
# ----------------------------------------------
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
# STATIC_URL = '/static/'
STATICFILES_DIRS = (
str(APPS_DIR.path('static')),
# str(ROOT_DIR.path('frontend')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATES_DIR = os.path.join(BASE_DIR, 'my_apps/templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'm!nh54$kig!!=in(fqny#grtd!e(_$jjrph-95g0_52xsdw*&c'
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
# django apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites', # new
'allauth', # new
'allauth.account', # new
'allauth.socialaccount',
'rest_auth',
'rest_auth.registration',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
# local apps
'my_apps.users.apps.UsersConfig',
]
# CORS conf
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'http://localhost:4200',
'http://127.0.0.1:4200'
)
# djangorestframework CONFIGURATION
# ------------------------------------------------------------------------------
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10,
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
}
# myproject/settings.py
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
SITE_ID = 1
# LOGIN_REDIRECT_URL = '/auth/login/'#'/auth-token/token/create/'
AUTH_USER_MODEL = 'users.User'
SESSION_COOKIE_AGE = 7200
REST_AUTH_SERIALIZERS = {
}
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'my_apps.users.serializers.RegisterSerializer',
}
# LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'
# djoser settings
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': {
'user_create': 'my_apps.users.serializers.RegisterSerializer',
'user': 'my_apps.users.serializers.UserSerializer',
'current_user': 'my_apps.users.serializers.UserSerializer'
},
}
# Important default settings
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = None
# EMAIL CONFIGURATION
# --------------------
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Production
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='changethis <info#changethis.org>')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
ACCOUNT_EMAIL_SUBJECT_PREFIX = ''
'''
SERVER_EMAIL = 'mazharabbasazhar72#gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'mazharabbasazhar72#gmail.com' #'mazharabbasazhar72#gmail.com'# os.environ['SENDGRID_USER_NAME']
EMAIL_HOST_PASSWORD = 'change' #os.environ['SENDGRID_PASSWORD']
EMAIL_PORT = 587
EMAIL_USE_TLS = True
'''
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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 = 'covid.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'my_apps/templates')],
'OPTIONS': {
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
AUTH_TEMPLATE_CONSTANTS = {
'project_name': 'Gateway Platform',
'support_email': 'support#gatewayplatform.com',
}
WSGI_APPLICATION = 'covid.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {}
# DEPLOYMENT_MODE = env('DEPLOYMENT_MODE')
DEPLOYMENT_MODE = 'local'
if DEPLOYMENT_MODE == 'local':
DEBUG = True
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
elif DEPLOYMENT_MODE == 'staging':
DEBUG = False
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
That's because you aren't sending the token in your request (Authorization: Bearer+{{token}})
If you're trying to log in but you see that message it's because you put
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
In REST_FRAMEWORK so by default, all your endpoints are gonna check if the user is authenticated, you need to allow any in the login. You can see more information here. Link
I am learning django but i am stuck at Imagefield. I am trying to rename the file and save the image to my media directory where exactly i am going wrong i am not able to understand. It was working fine till worked with filefield. after changing the filefield to imagefield i am getting an page not found.
Not Found: /media/products/926045120/926045120.jpg
above is the error
from django.db import models
import random
import os
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
def upload_image_path(instance, filename):
# print(instance)
#print(filename)
new_filename = random.randint(1,3910209312)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)
return "products/{new_filename}/{final_filename}".format(
new_filename=new_filename,
final_filename=final_filename
)
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
model.py of product
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z45+z23#cgk-fem6x&6i9_n#tz8p3)f^l+f1#8$e^n7(hv&dgz'
# 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',
'products',
]
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 = 'ecommerce.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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 = 'ecommerce.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',
},
]
# 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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static_my_proj"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")
products/views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
# Create your views here.
from .models import Product
class ProductListView(ListView):
queryset = Product.objects.all()
template_name = "products/list.html"
# def get_context_data(self, *args, **kwargs):
# context = super(ProductListView, self).get_context_data(*args, **kwargs)
# print(context)
# return context
def product_list_view(request):
queryset = Product.objects.all()
context = {
'object_list': queryset
}
return render(request, "products/list.html", context)
class ProductDetailView(DetailView):
queryset = Product.objects.all()
template_name = "products/detail.html"
def get_context_data(self, *args, **kwargs):
context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
print(context)
#context['abc'] = 123
return context
def product_detail_view(request, pk=None, *args, **kwargs):
#instance = Product.objects.get(pk=pk)
instance = get_object_or_404(Product, pk=pk)
context = {
'object': instance
}
return render(request, "products/detail.html", context)
details.html
{{ object.title }}<br/>
{{ object.description }}<br/>
<img src="{{ object.image.url }}" class="img-fluid"/>
I am able see my images in media directory but it is not able view on page