How can add "templates " and "statics" folder in Django 3.1 - django-2.0

setting.py
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
#TEMPLATES_DIR = path.join(BASE_DIR, 'templates') #it dosen't work
#STATICS_DIR = path.join(BASE_DIR, 'statics') #it also dosen't work
# 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 = '0#nf#$8nm5jb0)meuq&j6kztt534#nhk)k&$zh=#emcxi7_7fo'
# 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',
'musicianapp',
]
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 = 'musicianList.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR,],
'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 = 'musicianList.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/'
STATICFILES_DIRS = [
STATICS_DIR,
]
Please consern on the top and 3rd top line where is the main difference from Djago2.7 version
In Djnago2.7 where imported os as below,
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__)))
and I used the below code for connecting templates and statics forlder
TEMPLATES_DIR =os.path.join(BASE_DIR,"templates")
STATICS_DIR =os.path.join(BASE_DIR,"statics")
But there is differece in form Djnago 3.1 from pathlib imported Path given below,
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
and the os techinques dosen't works as below
TEMPLATES_DIR =os.path.join(BASE_DIR,"templates")
STATICS_DIR =os.path.join(BASE_DIR,"statics")
How can I make connection with templates and statics folder, need help.
Note: I create templates and statics folders in main projects where already presented manage.py and db.sqlite3 file. below the screenshot of my projects direction,

If you look at the top of the settings.py file, you'll see BASE_DIR is using pathlib:
BASE_DIR = Path(__file__).resolve().parent.parent
Because of this, you no longer need os to join the paths, you can simply do:
STATICS_DIR = BASE_DIR / "statics"
This is new in 3.1 - you can read about it in the release notes here: https://docs.djangoproject.com/en/3.1/releases/3.1/

I would also recommend https://docs.djangoproject.com/en/4.0/howto/overriding-templates/, but if nothing happens then it should be the Refactoring problem especially when using PyCharm. So, you need to revert your changes. It worked for me.

Related

How to connect VUE 3.x frontend websocket to DJANGO 4.x consumer using DJANGOCHANNELSRESTFRAMEWORK?

I have a DJANGO project with the following files.
Basically I am using token authentication in my settings which works well for javascript fetch/axios since I can send the token in the headers. I use djoser to manage the token authentication; however when I try to run any custom action in my consumer.py file the user in self.scope.get('user') is always AnonymousUser and then it returns with an 'Not allowed' message.
Do I need to authenticate the user over websocket protocol?
Also worth noting. I am using DJANGOCHANNELSRESTFRAMEWORK and using DEMULTIPLEXER to handle the websocket/consumer routing.
UPDATE: I tried using using the 'list' action in my json data and in consumers.py I user permissions.AllowAny and it works as expected; however I still cannot use any of my own custom actions.
UPDATE 2: When using permissions.AllowAny I can actually use all my custom actions as well; however I'm not sure if this is safe. I would like for my user to be authenticated to do this through websocket in this DJANGO decoupled project.
SETTINGS.PY
from pathlib import Path
import os
# 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 = 'django-insecure-=1l1i2&3mw2!5^zhchewl#ziv1=ip0i$jc+8n7ikryjufwsh9e'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['http://127.0.0.1:8000','127.0.0.1:8000','127.0.0.1','http://localhost:8080','ws://localhost:8080']
CORS_ALLOWED_ORIGINS = (
'http://127.0.0.1:8000',
'http://localhost:8080'
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
# 'rest_framework.authentication.BasicAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication'
],
'DEFAULT_PERMISSION_CLASSES':[
'rest_framework.permissions.IsAuthenticated'
]
}
CSRF_TRUSTED_ORIGINS=['http://127.0.0.1:8000','http://localhost:8080']
AUTH_USER_MODEL='users.User'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'djoser',
'corsheaders',
'daphne',
'channels',
'users',
'students',
'instructors',
'groups',
'materials',
'operation',
'channels_demultiplexer',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
# 'middleware.websocket_auth.TokenAuthMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'InterAct.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'templates/'),
# os.path.join(BASE_DIR,'frontend/','dist/','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 = 'InterAct.wsgi.application'
ASGI_APPLICATION = 'InterAct.asgi.application'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
},
},
}
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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
MEDIA_URL='/media/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# 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,'publick/static/')
# STATICFILES_DIRS = [
# BASE_DIR / "static",
#
# ]
# CORS_ORIGIN_ALLOW_ALL = True
ASGI.PY
#ASGI config for InterAct project.
#It exposes the ASGI callable as a module-level variable named ``application``.
#For more information on this file, see
#https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
import os
from channels.auth import AuthMiddlewareStack
from middleware.websocket_auth import TokenAuthMiddleware
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
import operation.routing
from django.urls import re_path
from operation.consumers import DMultiplexer
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'InterAct.settings')
django_application = get_asgi_application()
application = ProtocolTypeRouter(
{
"http": django_application,
"websocket": AllowedHostsOriginValidator(
# TokenAuthMiddleware(URLRouter([
AuthMiddlewareStack(URLRouter([
# operation.routing.websocket_urlpatterns,
# re_path(r"^/$", DMultiplexer.as_asgi()),
re_path(r"^ws/$", DMultiplexer.as_asgi()),
]))
),
}
)
CONSUMERS.PY
from djangochannelsrestframework.generics import GenericAsyncAPIConsumer
from users.models import User
from users.serializers import UserSerializer
from channels.auth import login as channels_login
from django.contrib.auth import login
from instructors.models import Instructor
from instructors.serializers import InstructorSerializer
from groups.models import Group
from groups.serializers import GroupSerializer
from students.models import Student
from students.serializers import StudentSerializer
from djangochannelsrestframework.decorators import action
from djangochannelsrestframework.observer import model_observer
from djangochannelsrestframework import permissions
from djangochannelsrestframework.observer.generics import ObserverModelInstanceMixin
from djangochannelsrestframework.mixins import (
ListModelMixin,
RetrieveModelMixin,
PatchModelMixin,
UpdateModelMixin,
CreateModelMixin,
DeleteModelMixin,
)
from channels.db import database_sync_to_async
import secrets
class Instructors_Consumer(
ListModelMixin,
# RetrieveModelMixin,
PatchModelMixin,
UpdateModelMixin,
CreateModelMixin,
DeleteModelMixin,
ObserverModelInstanceMixin,
GenericAsyncAPIConsumer):
permission_classes = (permissions.AllowAny,)
queryset=Instructor.objects.all()
serializer_class=InstructorSerializer
#action()
async def subscribe_to_instructors_feed(self, request_id, **kwargs):
print('are we all getting called?')
await self.instructors_feed.subscribe(request_id=request_id)
#model_observer(Instructor,serializer_class=InstructorSerializer)
async def instructors_feed(self, data, action, subscribing_request_ids=[], **kwargs):
# print(data,action,subscribing_request_ids)
for request_id in subscribing_request_ids:
await self.reply(data=data, action=action, request_id=request_id)
#action()
async def create_model(self, *args, **kwargs):
data=kwargs.get('data')
object=await self.create_model_db(data)
return object,200
#database_sync_to_async
def create_model_db(self,data):
print(data)
email=f'{secrets.SystemRandom().randint(1,1000000)}#{secrets.SystemRandom().randint(1,1000000)}.com'
username=secrets.SystemRandom().randint(1,1000000)
new_user=User.objects.create(first_name='first_name',last_name='last_name',role="Instructor",email=email,username=username)
new_instructor=new_user.instructor_set.first()
new_instructor=InstructorSerializer(new_instructor).data
print(new_user)
print(new_instructor)
return new_instructor
class Groups_Consumer(
ListModelMixin,
# RetrieveModelMixin,
PatchModelMixin,
UpdateModelMixin,
CreateModelMixin,
DeleteModelMixin,
ObserverModelInstanceMixin,
GenericAsyncAPIConsumer):
permission_classes = [permissions.AllowAny]
queryset=Group.objects.all()
serializer_class=GroupSerializer
#action(detail=False)
async def subscribe_to_groups_feed(self, request_id, **kwargs):
print('hello from another domain2222')
print(request_id)
print(dir(self))
# [print(thing) for thing in dir(self)]
print(self.scope.get('user'))
# login(request, user) # <- This was missing
await self.groups_feed.subscribe(request_id=request_id)
#model_observer(Group,serializer_class=GroupSerializer)
async def groups_feed(self, data, action, subscribing_request_ids=[], **kwargs):
for request_id in subscribing_request_ids:
await self.reply(data=data, action=action, request_id=request_id)
#action()
async def create_and_add_student(self, *args, **kwargs):
data=kwargs.get('data')
new_group=await self.create_and_add_student_db(data)
return new_group,200
#database_sync_to_async
def create_and_add_student_db(self,data):
pk=int(data.get('pk'))
group=Group.objects.get(pk=pk)
email=f'{secrets.SystemRandom().randint(1,1000000)}#{secrets.SystemRandom().randint(1,1000000)}.com'
username=secrets.SystemRandom().randint(1,1000000)
first_name=secrets.SystemRandom().randint(1,1000000)
new_user=User.objects.create(first_name=first_name,role="Student",email=email,username=username)
new_student=new_user.student_set.first()
group.student.add(new_student)
group.save()
new_student=StudentSerializer(new_student).data
response={
'new_student':new_student,
'parent':pk,
}
return response
class Students_Consumer(
ListModelMixin,
# RetrieveModelMixin,
PatchModelMixin,
UpdateModelMixin,
CreateModelMixin,
DeleteModelMixin,
ObserverModelInstanceMixin,
GenericAsyncAPIConsumer):
permission_classes = (permissions.AllowAny,)
queryset=Student.objects.all()
serializer_class=StudentSerializer
#action()
async def subscribe_to_students_feed(self, request_id, **kwargs):
await self.students_feed.subscribe(request_id=request_id)
#model_observer(Student,serializer_class=StudentSerializer)
async def students_feed(self, data, action, subscribing_request_ids=[], **kwargs):
# print(data,action,subscribing_request_ids)
for request_id in subscribing_request_ids:
await self.reply(data=data, action=action, request_id=request_id)
class Users_Consumer(
ListModelMixin,
# RetrieveModelMixin,
PatchModelMixin,
UpdateModelMixin,
CreateModelMixin,
DeleteModelMixin,
ObserverModelInstanceMixin,
GenericAsyncAPIConsumer):
queryset=User.objects.all()
serializer_class=UserSerializer
permission_classes = (permissions.AllowAny,)
#action()
async def subscribe_to_users_feed(self, request_id, **kwargs):
print('hello from another domain')
await self.users_feed.subscribe(request_id=request_id)
#model_observer(User,serializer_class=UserSerializer)
async def users_feed(self, data, action, subscribing_request_ids=[], **kwargs):
# print(data,action,subscribing_request_ids)
for request_id in subscribing_request_ids:
await self.reply(data=data, action=action, request_id=request_id)
from channels_demultiplexer.demultiplexer import WebsocketDemultiplexer
class DMultiplexer(WebsocketDemultiplexer):
consumer_classes={
"users":Users_Consumer,
"groups":Groups_Consumer,
"instructors":Instructors_Consumer,
"students":Students_Consumer,
}
in my VUEX STORE index.js I have this action:
async openEndpoint(state,params){
console.log(params);
let ws=params.ws
let endpoint=params.endpoint
ws.onopen=async ()=>{
console.log('connection established');
console.log(endpoint);
let data={
stream:endpoint,
payload:{
action:'subscribe_to_groups_feed',
request_id: new Date().getTime()
}
}
console.log(ws);
ws.onmessage=(ws_event)=>{
let response=JSON.parse(ws_event.data)
console.log(response);
console.log(response.payload.errors);
}
ws.send(JSON.stringify(data))
}
}
After hours of researching it turns out that I can write middleware to incercept the websocket requests. I had to pass the token as a query_string parameter and then decode it in the middleware so that I could then get the user from the Token.objects provided by Djoser.
However now all my normal fetch requests are failing. I provide the Middleware for anyone trying to advance in this topic.
from channels.auth import AuthMiddleware
from channels.db import database_sync_to_async
from channels.sessions import CookieMiddleware, SessionMiddleware
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import AnonymousUser
#database_sync_to_async
def get_user(scope_token):
token = scope_token.decode('utf8')
token= token.split('=')[1]
print(token)
if not token:
return AnonymousUser()
try:
user = Token.objects.get(key=token).user
except Exception as exception:
return AnonymousUser()
if not user.is_active:
return AnonymousUser()
return user
class TokenAuthMiddleware(AuthMiddleware):
def __init__(self, app):
# Store the ASGI application we were passed
self.app = app
async def __call__(self, scope,receive,send,*args,**kwargs):
# Look up user from query string (you should also do things like
# checking if it is a valid user ID, or if scope["user"] is already
# populated).
print('MIDDLEWARING')
scope['user'] = await get_user(scope["query_string"])
return await self.app(scope,receive,send)
async def resolve_scope(self, scope,receive,send):
scope['user']._wrapped = await get_user(scope)
def TokenAuthMiddlewareStack(inner):
return CookieMiddleware(SessionMiddleware(TokenAuthMiddleware(inner)))
UPDATE:
On applying the above solution I stopped being able to get my axios/fetch requests to work. I suppose this has to do with the fact that I used the middleware to intercept websocket requests. When I undo all the middleware changes everything works normal. The 'trick' around this was to just disable the middleware in settings.py somehow this allows the axios/fetch requests to go through django application normally and still incercepts the websocket requests. This is how the settings look like now.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'middleware.websocket_auth.TokenAuthMiddleware',
'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',
]

zappa wagtail how to use s3 for media/images (server error 500)

Im using wagtail on an aws lambda with zappa.
Everything is working fine except the images i'm trying to upload in the blog posts.
That is to say when i try to upload an image in the /cms-admin in the images menu i get a server error 500 message.
I have configured the images to be stored on s3 following this post https://wagtail.org/blog/amazon-s3-for-media-files/ but it seems there is a problem.
Here is my models.py :
from django.db import models
from wagtail.core.models import Page
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.snippets.models import register_snippet
from taggit.models import Tag as TaggitTag
from modelcluster.fields import ParentalKey
from taggit.models import TaggedItemBase
from modelcluster.tags import ClusterTaggableManager
from wagtail.admin.edit_handlers import (FieldPanel,
FieldRowPanel,
InlinePanel,
MultiFieldPanel,
PageChooserPanel,
StreamFieldPanel,
)
from wagtail.snippets.edit_handlers import SnippetChooserPanel
from wagtail.core.fields import StreamField
from .blocks import BodyBlock
class BlogPage(Page):
description = models.CharField(max_length=255, blank=True,)
content_panels = Page.content_panels + [FieldPanel("description", classname="full")]
class PostPage(Page):
header_image = models.ForeignKey(
"wagtailimages.Image", null=True,
blank=True, on_delete=models.SET_NULL, related_name="+",)
body = StreamField(BodyBlock(), blank=True)
tags = ClusterTaggableManager(through="blog.PostPageTag", blank=True)
content_panels = Page.content_panels + [ ImageChooserPanel("header_image"), InlinePanel("categories", label="category"), FieldPanel("tags"),StreamFieldPanel("body"),]
#register_snippet
class BlogCategory(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True, max_length=80)
panels = [ FieldPanel("name"),
FieldPanel("slug"),]
def __str__(self):
return self.name
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
#register_snippet
class Tag(TaggitTag):
class Meta:
proxy = True
class PostPageBlogCategory(models.Model):
page = ParentalKey("blog.PostPage", on_delete=models.CASCADE, related_name="categories" )
blog_category = models.ForeignKey("blog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages")
panels = [ SnippetChooserPanel("blog_category"),]
class Meta:
unique_together = ("page", "blog_category")
class PostPageTag(TaggedItemBase):
content_object = ParentalKey("PostPage", related_name="post_tags")
Here is my settings.py
"""
Django settings for react_wagtail_app 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
# 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 = 'django-insecure-jvstu05lh1fp2ow26blj&5%x_7bb(e*qt#(urj+$(2n&1i&)ka'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['xwovkgc3f6.execute-api.eu-west-3.amazonaws.com']
# Application definition
INSTALLED_APPS = [ 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"wagtail.contrib.forms",
"wagtail.contrib.redirects",
"wagtail.embeds",
"wagtail.sites",
"wagtail.users",
"wagtail.snippets",
"wagtail.documents",
"wagtail.images",
"wagtail.search",
"wagtail.admin",
"wagtail.core",
"modelcluster",
"taggit",
"blog",
"storages"]
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',
"wagtail.contrib.redirects.middleware.RedirectMiddleware",
]
ROOT_URLCONF = 'react_wagtail_app.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 = 'react_wagtail_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'spa',
'USER': 'postgres',
'PASSWORD': 'password',
'HOST': '146.190.238.8',
'PORT': '5432',
}
}
# 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 = 'fr-FR'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
AWS_STORAGE_BUCKET_NAME = "zappa-pasvx3uig"
AWS_ACCESS_KEY_ID = 'secret'
AWS_SECRET_ACCESS_KEY = 'secret'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
#MEDIA_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = "/dev/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
WHITENOISE_STATIC_PREFIX = "/static/"
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#MEDIA_ROOT = str(BASE_DIR / 'media')
WAGTAIL_SITE_NAME = 'My Project'
I have seen in other posts here: Configuring Django/Wagtail media to use S3
that a special class is used inherited from S3BotoStorage. I was wondering if i didnt need to use that in my models.py for the Images?
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class MediaStorage(S3Boto3Storage):
location = settings.MEDIAFILES_LOCATION
Could you help me understand what is not properly configured so the images are properly uploaded to s3 and print on the screen normally
I ve tried to set AWS_DEFAULT_ACL='public-read' following another stackoverflow post but it is the same.
zappa tail gives me the following error :
botocore.exceptions.ClientError: An error occurred (InvalidToken) when calling the PutObject operation: The provided token is malformed or otherwise invalid.
I ve managed to overcome this error by providing two separate credentials
AWS_S3_ACCESS_KEY_ID
and AWS_ACCESS_KEY_ID
but i'm still having problems with the images
I'm considering giving up on aws lambda with zappa and switching to a container service
I am afraid I don't know anything about Zappa. We use ElasticContainerService running on EC2 instances we manage. We are considering going to ECS on Fargate but have not made the transition yet.
Looking at your settings file CHANGE YOUR AWS CREDENTIALS AT ONCE!!!!
After that, I am fairly sure you need the MEDIA_ROOT and MEDIA_URL settings. Ours are set to MEDIA_ROOT = '/media' and MEDIA_URL = '/media/'. And we do have AWS_DEFAULT_ACL = 'public-read' so that images can be served straight from S3 using the default for WAGTAILDOCS_SERVE_METHOD of 'redirect'
Until you get s3 storage working, I would remove the AWS_S3_CUSTOM_DOMAIN setting so you can debug one thing at a time.

Problem with the error * A server error occurred. Please contact the administrator * django rest framework

I am trying to test some basic backed fonctionnalities but I seem to have this error A server error occurred. Please contact the administrator while trying to connect to the localhost http://127.0.0.1:8000 or http://127.0.0.1:8000/sise/.
At first I had this error showing django.core.exceptions.ImproperlyConfigured: The included URLconf 'Dashboard_sise.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. but After I commented this line in the settings file ROOT_URLCONF = 'Dashboard_sise.urls' the error changed into A server error occurred. Please contact the administrator.
Can anyone please help me figure this problem out, I already tried changing the urlpatterns in the urls.py files but it didn't work, I also tried manipulating the MIDDLEWARE section in the settings file but nothing changed.
This is the Dashboard_sise.urls code
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.sites.urls),
path('sise/', include('Dashboard.urls')),
]
This is the Dashboard.urls code
from rest_framework.routers import DefaultRouter
from Dashboard.views import *
router = DefaultRouter()
router.register(r'accee', AcceeViewSet, basename='accee')
router.register(r'rapport', RapportViewSet, basename='rapport')
router.register(r'prise_fonction', PointageUtilisateurViewSet, basename='prise_fonction')
urlPatterns = router.urls
and finally the settings file
# 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 = '+f-#$j*(-8^*7ijk#6_hpki#)am4e%na6ttp)54#-ddcs0#fgy'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
PREPEND_WWW = False
# 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',
'Dashboard',
'frontend'
]
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',
]
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 = 'Dashboard_sise.wsgi.application'
'''ROOT_URLCONF = 'Dashboard_sise.urls'''
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'MainCourante',
'USER': 'postgres',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '5432',
}
}
# 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
APPEND_SLASH = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
'''REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.authentification.BasicAuthentification'
'rest_framework.authentification.SessionAuthentification'
# 'rest_framework.permissions.IsAuthentificated'
# 'rest_framework.permissions.AllowAny'
)
}'''
CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
Thank you in adavance
I will answer this in case someone faced the same bug. I had a problem with the database structure .. The models implemented in the models.py file and the database created didn't match so it kept showing me this error ... once I fixed the models.py file it all worked well
Maybe this was the cause.
urlPatterns = router.urls
its usually urlpatterns.

Export my CSS vars with my module using rollup?

I have a little module that I am sharing across a few projects. It is successfully exporting components, but now I'd like to get my global style vars, like $contoso-primary: #ff0000 to be exported as well so we can start sharing CSS vars in my consuming app, like background-color: $contoso-primary. I'm using the rollup.js, is this possible with this library or with its plugins? If so, what plugin am I looking for? I've tried postcss already but doesn't appear to work unless I'm missing something.
export default {
input: 'src/index.js',
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: true
},
{
file: pkg.module,
format: 'es',
sourcemap: true
}
],
plugins: [
external(),
postcss({
extract: true
}),
url(),
svgr(),
babel({
exclude: 'node_modules/**'
}),
resolve(),
commonjs()
],
onwarn(warning, warn) {
if (
warning.code === 'CIRCULAR_DEPENDENCY'
&& warning.importer.indexOf('node_modules/semantic-ui-react') > -1
) return;
warn(warning);
}
};
my scss file that has my vars looks something like:
$primary: #177757,
$secondary: #D50000
and in the consuming project I'd like to refer to these in my scss files like:
.button {
background: $primary
}
I can't get an .css file into my dist folder, and the documenation on rollup-plugin-postcss is a little light.
postcss-simple-var this plugin will able to share sass like variables.
plugins: [
postcss({
plugins: [
simplevars()
],
extensions: [ '.css' ],
}),
...
]
for more information read this article.
I was able to make this work by duplicating the variable declarations in both the postcss.config.js and rollup.config.js
Rollup config:
import postcss from "rollup-plugin-postcss";
import postcssSimpleVars from "postcss-simple-vars";
const variables = require("./pathTo/variableConfig.js");
...
const config = {
...
plugins: [
postcss({
postcssSimpleVars({
variables: function () {
return variables;
}
}),
})
]
postCSS config:
const variables = require("./variableConfig.js");
plugins: [
...
require("postcss-simple-vars")({
variables: variables
})
]
variableConfig.js:
const baseDir = "../src/utils/constants";
const { COLORS } = require(`${baseDir}/colors`);
const { MQ } = require(`${baseDir}/mediaQueries`);
const { BREAKPOINTS } = require(`${baseDir}/breakpoints`);
const cssVars = Object.assign(COLORS, MQ, BREAKPOINTS);
module.exports = cssVars;

Dajaxice 0.5.1 - Can't seem to make the tutorial work

I've checked over my stuff repeatedly and I cannot find the issue.
Here's the layout of my project:
project
allthings
init.py
admin.py
settings.py
models.py
views.py
tests.py
static
css
dajaxice
dajaxice.core.js
images
js
templates
testing.html
project
ajax.py
init.py
settings.py
urls.py
views.py
wsgi.py
manage.py
settings.py
DEBUG = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL =/static/
STATICFILES_DIRS = (
'C:/Python27/djcode/project/static',
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'dajaxice.finders.DajaxiceFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'project.urls'
WSGI_APPLICATION = 'project.wsgi.application'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages'
)
TEMPLATE_DIRS = (
"C:/Python27/djcode/project/templates"
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'allthings',
'dajaxice',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
)
urls.py
from django.conf.urls import patterns, include, url
from project.views import hello, testing
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
('^hello/$', hello),
('^testing/$', testing),
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
views.py
from django.shortcuts import render_to_response, HttpResponse
from django.template import RequestContext
from dajaxice.core import dajaxice_autodiscover
dajaxice_autodiscover()
def hello(request):
return HttpResponse("Hello world!")
def testing(request):
return render_to_response('testing.html', context_instance = RequestContext(request))
ajax.py
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def sayhello(request):
return simplejson.dumps({'message':'Hello World'})
testing.html
<!DOCTYPE html/>
{% load dajaxice_templatetags %}
<html>
<head><title></title>
{% dajaxice_js_import %}
<script>
function my_callback(data){
alert(data.message);
}
</script>
</head>
<body>
This is to test stuff
<input type="button" onclick="Dajaxice.project.sayhello(my_callback)" value="Get Message from Server"></input>
</body>
</html>
All it does it make a button that puts out an alert. It should be incredibly simple and yet I get nothing. What am I doing wrong?
Because dajaxice.core.js is a non-static template file, DajaxFinder will find it and 'render' to a temp folder as a static file.
So your STATICFILES_DIRS settings should not contain the file path to dajaxice.core.js otherwise the file will be found by FileSystemFinder rather than DajaxFinder.
You can run findstatic to check it is found correctly or not:
manage.py findstatic dajaxice\dajaxice.core.js
or maybe:
manage.py findstatic dajaxice/dajaxice.core.js
The output result should be in some temp folder (depending on your OS) and should not be in any folder of your app.

Resources