s3 bucket does not collect created pdfs in media folder django/aws - django

I just deployed my django application to a beanstalk server linked to an s3 bucket in the aws console.
In my application pdfs from each post are created and forwarded to the media folder in the subfolder "postings". However, in the bucket no such folder is created and the pdfs also don't show up anywhere else. only the uploaded images of the post is there.
How do I get the pdfs there?
also, I get an ValueError now for the Image in the PDF (which is the uploaded image, and which was working just fine before adding the bucket). How do I get it to work again? I think both problems are due to some connection missing... This is my first project deploying to aws. Please help me out with a little explanation.
Here is the code of the created upload and pdf:
views.py
def post_create(request):
if request.method == 'POST':
form = PostCreateForm(request.POST, request.FILES)
if form.is_valid():
form.cleaned_data['num_post'] = Post.objects.count() + 1
Post.objects.create(**form.cleaned_data)
else:
form = PostCreateForm()
return render(request, 'index.html', {'form': form})
def upload(request):
if request.method == 'POST':
image = request.FILES.get('image_upload')
caption = request.POST['caption']
num_post = Post.objects.count() + 1
new_post = Post.objects.create(image=image, caption=caption, num_post=num_post)
new_post.save()
# create pdf
buffer = io.BytesIO()
x_start = 100
y_start = 100
folder_path = f"media/postings/post{num_post}.pdf"
folder_name = os.path.join(BASE_DIR, folder_path)
p = canvas.Canvas(folder_name, pagesize=A4, )
if image is not None:
register_heif_opener()
pil_image = io.BytesIO()
PIL.Image.open(image.file).save(pil_image, 'PNG')
p.drawImage(ImageReader(PIL.Image.open(pil_image)), x_start, y_start, width=420, preserveAspectRatio=True,
mask='auto')
p.drawString(150, 650, new_post.caption)
p.drawString(100, 650, "caption:")
p.drawString(100, 170, str(new_post.created_at))
p.drawString(200, 700, str(num_post))
p.drawString(100, 700, "post no.:")
p.drawString(250, 700, "//")
p.drawString(100, 690, "===========================================================")
p.drawString(300, 700, str(new_post.id))
p.save()
buffer.seek(0)
return redirect('/')
else:
return redirect('/')
the Post Model
def post_images(instance, filename):
ext = filename.split('.')[-1]
filename = 'postimg{}.{}'.format(instance.num_post, ext)
return os.path.join('uploads', filename)
class Post(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
num_post = models.IntegerField(default=0)
image = models.ImageField(upload_to=post_images)
caption = models.TextField(max_length=300)
created_at = models.DateTimeField(auto_now_add=True)
number_of_likes = models.IntegerField(default=0)
number_of_dislikes = models.IntegerField(default=0)
likes_string = models.TextField(max_length=800, default="")
dislikes_string = models.TextField(max_length=800, default="")
interaction_count = models.IntegerField(default=0)
#property
def filename(self):
return os.path.basename(self.image.name).split('.')[0]
def __str__(self):
return self.caption
the media settings
from django.contrib import staticfiles
# 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 = "..."
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = getenv("IS_DEVELOPMENT", True)
ALLOWED_HOSTS = [
getenv("APP_HOST", "localhost"),
'127.0.0.1'
]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
'core.apps.CoreConfig',
'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 = "social_book.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 = "social_book.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "postgres",
"USER": "feedingcycle",
"PASSWORD": "...",
"HOST": "django-social-media.cuo1odqldl3u.us-east-1.rds.amazonaws.com",
"PORT": "5432"
}
}
# 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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = "static/"
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
AWS_STORAGE_BUCKET_NAME = "django-feeding-cycle"
AWS_S3_REGION_NAME = "us-east-1"
AWS_ACCESS_KEY_ID = "..."
AWS_SECRET_ACCESS_KEY = "..."
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com"
STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
MEDIAFILES_FOLDER = "media"
DEFAULT_FILE_STORAGE = "custom_storages.MediaFileStorage"
the storage
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class MediaFileStorage(S3Boto3Storage):
location = settings.MEDIAFILES_FOLDER
and the config
option_settings:
aws:elasticbeanstalk:environment:proxy:staticfiles:
/static: staticfiles
/media: media
So when I create an media folder like this, i get the error and no pdf is created. if i just use the default in the bucket I don't get the error but still no pdf is created... in the project preview server everything was working just fine. also without the bucket. But i need the bucket, so that I can sinc it with a local folder, to get the posted files directly...

Related

Django Files Upload from Form get CSRF Forbidden on production

I have a simple Django FileForm for multiple files upload (basically txts with polygon coordinates). I don't want to save the uploaded files anywhere but only treat them on the fly (memory?) and return a leaflet map with the polygons and a new file of mine (which transforms and exports all the txts in a .dxf format file (CAD combatible)).
I have done all the logic and my programm seems to work fine on development but on production (Heroku) when i hit the submit button on my form I keep getting CSRF Forbidden 403 message. I am really frustrated. I have used csfr decorators (csrf_exempt, requires_csrf_token, ensure_csrf_cookie) on my views but none seems to work. I have included
enctype="multipart/form-data"> and {% csrf_token %} on my form template.
What's the problem? It's hard for me to test and try because on development everything is ok and I have to deploy everytime only to see if another approach works.
Is it because I am not saving the files on a model and on a disk (What's the logic here?), or is it because I'm missing something on the CSRF part on my settings?
settings.py (when deploying)
"""
Django settings for myKAEK project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
from decouple import config
from decouple import config, Csv
# 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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'mykaek-gr.herokuapp.com', 'myKAEK.gr', 'www.myKAEK.gr']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'djgeojson',
'storages',
'debug_toolbar',
'myKAEKapp',
]
MIDDLEWARE = [
"debug_toolbar.middleware.DebugToolbarMiddleware",
'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',
]
INTERNAL_IPS = [
"127.0.0.1",
]
ROOT_URLCONF = 'myKAEK.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 = 'myKAEK.wsgi.application'
GOOGLE_MAPS_API = config('GOOGLE_MAPS_API')
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'NAME': config('DB_NAME'),
# 'USER': config('DB_USER'),
# 'PASSWORD': config('DB_PASSWORD'),
# 'HOST': config('DB_HOST'),
# 'PORT': config('DB_PORT'),
# }
#}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
# STATIC_URL = 'static/'
# STATIC_ROOT = os.path.join(BASE_DIR)
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# MEDIA_URL = '/media/'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
USE_S3 = config('USE_S3') == 'TRUE'
if USE_S3:
# aws settings
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
AWS_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# s3 public media settings
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# 'myKAEKapp.storage_backends.PublicMediaStorage'
else:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# MEDIA_URL = '/mediafiles/'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=120)
DATABASES = { 'default': dj_database_url.config() }
DATABASES['default'].update(db_from_env)
DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis'
CSRF_TRUSTED_ORIGINS = ["https://mykaek-gr.herokuapp.com/", "https://mykaek.gr/"]
forms.py
class UploadFileForm(forms.Form):
files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
html
<div class="row justify-content-center align-items-center text-center" style="padding-top: 30px; width: 500px; margin: auto;">
<fieldset name="Multiple Files Upload">
<form method="post" action="/draw-polygons/" enctype="multipart/form-data">{% csrf_token %}
<dl><input class="form-control" type="file" id="formFileMultiple" name="files" required multiple></dl>
<button type="submit" class="btn btn-outline-dark" style="margin-top: 10px;">Φόρτωση</button>
</form>
</fieldset>
</div>
view.py
def upload_multiple_files(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
files_list = request.FILES.getlist('files')
if form.is_valid():
for f in files_list:
try:
'''my code here'''
except:
'''my code here'''
'''my code here'''
return render(request, "multiple/success.html", context)
else:
form = UploadFileForm()
return render(request, 'multiple/multiple.html', {'title': 'myKAEK.gr | Draw Polygons', 'form': form})
def txt_dxf(request):
topos = cache.get('topos')
doc = ezdxf.new("R2000")
msp = doc.modelspace()
doc.layers.add('POLYS_FROM_TXTS')
for i in topos:
msp.add_lwpolyline(i, dxfattribs={"layer": "POLYS_FROM_TXTS"})
out = io.BytesIO()
doc.write(out, fmt='bin')
out.seek(0)
return FileResponse(out, as_attachment=True, filename='polygons_from_txt.dxf')
urls
urlpatterns = [
path('draw-polygons/', views.upload_multiple_files, name='upload_multiple_files'),
path('draw-polygons/export_dxf/', views.txt_dxf, name='txt_dxf'),
]
If I may add something I saw after my original question was posted:
While my custom domain served through cloudflare returns
CSRF Forbidden 403, my herokuapp server returns for the same page
Bad request 400
I don't know if it's relevant but I thought I should add.
Also when I use #csrf_exempt on my view and delete {% csrf_token %} from template I get 400 Bad Request on my custom domain too.
Is it beacouse I use Cloudflare (with cache disabled) between my custom domain and herokuapp?
Please help I really need to get this function work.
Try doing this using Django Forms, it will save you from writing extra code and will handle such edge cases.
https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/#uploading-multiple-files

Django programming: cannot cast time without time zone to timestamp

I am newbie to django and was using SQLite during development, when i moved to postgres when trying to deploy to production i get the below error
Cannot cast type time without time zone to timestamp with time zone
settings.py
Django settings for todoBackend project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
from django.core.management.utils import get_random_secret_key
import os
import sys
import dj_database_url
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "False") == "True"
ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",")
# Application definition
INSTALLED_APPS = [
"rest_framework",
"corsheaders",
"api.apps.ApiConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"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",
]
CORS_ALLOW_ALL_ORIGINS = True
ROOT_URLCONF = "todoBackend.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 = "todoBackend.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True"
# DEVELOPMENT_MODE = True
if DEVELOPMENT_MODE is True:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
elif len(sys.argv) > 0 and sys.argv[1] != "collectstatic":
if os.getenv("DATABASE_URL", None) is None:
raise Exception("DATABASE_URL environment variable not defined")
DATABASES = {
"default": dj_database_url.parse(os.environ.get("DATABASE_URL")),
}
# 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 = "Asia/Kolkata"
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/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
models.py
from django.db import models
# Create your models here.
class Tasks(models.Model):
title = models.CharField(max_length=200, blank=False, null=False)
description = models.CharField(max_length=1000, blank=True)
start_time = models.DateTimeField(blank=True, null=True)
end_time = models.DateTimeField(blank=True, null=True)
duration = models.CharField(max_length=25, blank=True)
completed = models.BooleanField(default=False)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
I am not sure why i am getting the error, i did setup the timezone in settings.py
The above code was working perfectly with SQLite , It only throws the error in Postgres
As #Iain shelvington in the comments pointed out , I had a migration that converted the end_time field from Character field to Time Field, Hence i was getting this error
I reset all my migrations and created a single migration which resolved the issue

How to Encrypt the data of djanog.ckeditor Richtextfield?

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

Not able see the image after uploading on admin panel

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

Exception Value: 'AnonymousUser' object is not iterable

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