I am naive in Django. Trying out a few pieces of stuff here. I was working with static files and have got stuck here. Please help me out here.
I am very much confused about static_root and static_dirs. I am following an online tutorial where the static root has not been used and their project is working fine. If am trying that I facing lots of errors and exceptions.
Here is my view:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
my_dict={'insert_me':"Hello I am from views.py"}
return render(request,'first_app/index.html',context=my_dict)
Here is my projects urls:
from django.contrib import admin
from django.conf.urls import url
from django.conf.urls import include
from first_app import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^first_app/',include('first_app.urls')),
url(r'^admin/', admin.site.urls),]
urlpatterns += staticfiles_urlpatterns()
Here is my apps url:
from django.conf.urls import url
from first_app import views
from django.contrib import admin
urlpatterns= [
url(r'', views.index, name='index'),]
the index.html:
{% load staticfiles%}
<html>
<head>
<meta charset="utf-8">
<title>DJ Page</title>
</head>
<body>
<h1>Hello this is index.html!</h1>
<img src="{% static 'images/dj.jpg'%}" alt='oh oh! did not show'>
</body>
</html>
and here is my setting:
"""
Django settings for Twenty3rdMrach project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
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__)))
TEMPLATES_DIR=os.path.join(BASE_DIR,'templates')
#TEMPLATES_DIR=os.path.join(TEMPLATES_DIR,'first_app')
print(TEMPLATES_DIR)
STATIC_DIR=os.path.join(BASE_DIR,'static')
print (STATIC_DIR )
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mz^^exko#!2czk35u$w-qr&v8u(46(fp7#u41ctabvwf=mz9m&'
# 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',
'first_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 = 'Twenty3rdMrach.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 = 'Twenty3rdMrach.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'udemy1',
'USER':'root',
'PASSWORD':'Ravi#go123',
'HOST':'localhost',
'PORT':'3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static/'),)
STATIC_ROOT=os.path.join(BASE_DIR,'static_media/')
While hitting the url:
http://127.0.0.1:8000/static/images/dj.jpg
am facing the below error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/images/dj.jpg
Raised by: django.contrib.staticfiles.views.serve
'images\dj.jpg' could not be found
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
STATICFILES_DIR - Setting is to tell Django which directories to be scanned for static files.
STATIC_ROOT - Setting is to tell Django where to put all the static files when python manage.py collectstatic command is executed.
I think you should remove the trailing slash in STATICFILES_DIR and STATIC_ROOT
STATIC_URL = '/static/'
STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),)
STATIC_ROOT=os.path.join(BASE_DIR,'static_media')
Related
I am using VueJS for fronend and Django for backend. I changed the conf of Vuejs such that when we run npm run build the compiled files goes to static/dist directory of Django. I also added the urls in urls.py as shown
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.views.generic import TemplateView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('users/',include('users.urls')),
path('accounts/',include('django.contrib.auth.urls')),
path('',TemplateView.as_view(template_name='index.html')),
]
urlpatterns = urlpatterns + staticfiles_urlpatterns()
when I go to http://127.0.0.1:8000 index .js is returned which contains the VueJS index file. So the above url goes to http://127.0.0.1:8000/static/dist and the server runs normally. But when I reload the page I am getting the below error.
Page not found (404)
Directory indexes are not allowed here.
Request Method: GET
Request URL: http://127.0.0.1:8000/static/
Raised by: django.contrib.staticfiles.views.serve
Any idea on how to resolve this error?
settings.py:
"""
Django settings for e_cell_server 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
# 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 = 'django-insecure-xbdu73yg0k)p%5$yx2%xa$bqsske-x&e!pljzdgvgeffr+dh+0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS=[]
CORS_ORIGIN_ALLOW_ALL = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#3rd-party
'corsheaders',
'rest_framework',
# Own Apps
'users',
]
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',
]
ROOT_URLCONF = 'e_cell_server.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR.joinpath('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 = 'e_cell_server.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/etc/mysql/my.cnf',
},
}
}
# 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.joinpath('static')
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Python == 3.6.5
Django == 1.8
Recently purchased domain name, http://www.favourite.uz. And placed my Django project to my hosting in cPanel. When I browse domain http://www.favourite.uz, it throws to default page of cPanel. But when try http://www.favourite.uz/news it opens my django app. I wanted to browse this http://www.favourite.uz/news page within the domain name, without /news.
I placed used server's namespaces in Domain registrator's page. Tried to create another simple project from this tutorial,https://www.youtube.com/watch?v=ffqMZ5IcmSY. But it still opens default page of cPanel.
Main favourite/urls.py
# from django.urls import path
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^news/', include('news.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
]
if settings.DEBUG is False:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root' : settings.MEDIA_ROOT,}),
]
(news)app url, news/urls.py
from . import views
urlpatterns =[
url(r'^$', views.NewsView.as_view(), name='posts'),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^index', views.search, name="search"),
url(r'^chaining/', include('smart_selects.urls')),
url(r'^league/(?P<pk>[0-9]+)/$', views.league_detail, name='league_detail'),
]
settings, favourite/settings.py
Django settings for futbik_version_7 project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
from django.utils.translation import ugettext_lazy as _
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
STATIC_URL = '/static/'
STATIC_ROOT = 'news/static/'
STATICFILES_DIRS =(
os.path.join(BASE_DIR,'news/static/images'),
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'az=5ur80-1ge#!951w3(bxaqg1zwo1+a#6+*s*dw(sgkywhb3z'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'www.favourite.uz', 'favourite.uz']
# Application definition
INSTALLED_APPS = [
'modeltranslation',
'news.apps.NewsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_userforeignkey',
'simplesearch',
'smart_selects',
]
MIDDLEWARE_CLASSES = [
'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',
'django_userforeignkey.middleware.UserForeignKeyMiddleware',
'django.middleware.locale.LocaleMiddleware',
]
LANGUAGES = (
('en', _('Uzbek')),
('ru', _('Русский')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
# MODELTRANSLATION_TRANSLATION_REGISTRY = 'news.translation'
ROOT_URLCONF = 'futbik_version_7.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
# os.path.join(BASE_DIR, 'news/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',
'news.context_processors.add_variable_to_context',
],
},
},
]
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.i18n',
)
WSGI_APPLICATION = 'futbik_version_7.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# SOUTH_DATABASE_ADAPTERS = {
# 'default': 'south.db.sqlite3'
# }
# Password validation
# https://docs.djangoproject.com/en/2.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/2.0/topics/i18n/
LANGUAGE_CODE = 'en'
TIME_ZONE = 'Asia/Tashkent'
USE_I18N = True
USE_L10N = True
USE_TZ = True
USE_DJANGO_JQUERY = False
# MODELTRANSLATION_DEBUG = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
I really appreciate, if someone encountered such situation and helps me to solve this little problem.
P.s. I am beginner in Django!
Try adding a redirect URL to your urls, so that / redirects to /news. In favourite/urls.py, add this:
from django.views.generic import RedirectView
url_patterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^news/', include('news.urls')),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^$', RedirectView.as_view(pattern_name='posts', permanent=True)) # <—- add this line
]
This should work.
I just find it strange that instead of showing a 404 not found, cPanel seems to hijack the missing page. If my method doesn't work, you should contact cPanel support and ask how to enable the default domain to be routed to your app.
I'm totally new to Django, and I'm having a problem adding a Django "app" to a created Django "project". I'm using Docker and Docker-Compose and when I try to build and spin up my instance with the "documents" app added it throws maximum recursion errors.
This problem is NOT present if I remove the documents app from the project, so there's obviously something misconfigured with my app.
Does anyone see what I'm doing wrong to set my default URL ('') to the Index view in documents?
Directory Structure
app/
|-django_nlp/
|-settings.py
|-urls.py
|-wsgi.py
|-documents/
|-templates/
|-index.html
|-apps.py
|-views.py
|-Dockerfile
|-docker-compose.yml
|-manage.py
django_nlp/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__)))
# /usr/src/app
# 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 = 'ixoz#2d4=m#k#%1#!hhr2ei82t4x$$e)n9oxrq66mzq556k59#'
# 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',
'documents'
]
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 = 'django_nlp.urls'
#Get the absolute path of the settings.py file's directory
BASE_PATH = os.path.dirname(os.path.realpath(__file__ ))
# /usr/src/app/django_nlp
TEMPLATE_DIRS = (
# 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.
#Add Templates to the absolute directory
# os.path.join(BASE_PATH, "templates")
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR,
BASE_PATH
],
'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 = 'django_nlp.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'),
}
}
# 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/'
django_nlp/urls.py
from django.conf.urls import url
from django.contrib import admin
# from documents import views
# import documents
from documents.views import Index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', Index.as_view())
# url(r'$^', documents.views.index, name='index')
]
documents/views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import TemplateView
# def index(request):
# return HttpResponse('Hello, welcome to the index page.')
class Index(TemplateView):
template_name = "text-form.html"
data = {'text': ''}
def get(self, request, *args, **kwargs):
form = self.form_class(data=self.data)
return render(request, self.template_name, data)
Thanks for your time!
If you working on Django 2.0, you should read this docs: https://docs.djangoproject.com/en/2.0/ref/urls/, the url configuration in this version has changes. But, if you realy want to use regex in Django 2.0, you can change:
from django.conf.urls import url
to;
from django.urls import re_path
example in your case;
from django.conf.urls import url
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', Index.as_view())
# url(r'$^', documents.views.index, name='index')
]
to;
from django.urls import re_path
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^$', Index.as_view()),
]
My application sits at the server path /home/myapp/.
The static assets sit at /home/myapp/src/static/ when a python manage.py collectstatic is performed.
It copies assets from /home/myapp/src/assets/.
I have tried with DEBUG both True and False.
When I navigate to the web application at https://test.example.com, it tells me that all of the assets that reside at /home/mpapp/src/assets/ are 404 (Not Found) despite the files being there.
Also, my web server setup is Apache with a reverse proxy to Gunicorn. I'm serving the application with gunicorn wsgi which serves the application at 127.0.0.1:8000, which is where Apache is ProxyPass to. I've tested against a brand new Django application and this setup serves it properly, so it shouldn't be how Apache and Gunicorn are configured.
What I have been doing is:
1) npm start to compile the React front-end assets
2) python manage.py collectstatic to move the assets to /static/
3) Run gunicorn wsgi where the manage.py and wsgi.py reside
Some code would be helpful. Here is my settings.py:
import os
import sys
import json
import datetime
from unipath import Path
from django.core.exceptions import ImproperlyConfigured
# Import JSON file
print(Path(__file__))
with open('./config/config.json') as f:
s = json.loads(f.read())
def get_settings(settings, s=s):
try:
return s[settings]
except KeyError:
error_msg = 'Set the {0} environment vaiable'.format(settings)
raise ImproperlyConfigured(error_msg)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).ancestor(2)
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_settings('SECRET_KEY')
ALLOWED_HOSTS = [
'*',
]
# Application definition
INSTALLED_APPS = [
# Base packages
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party packages
'rest_framework',
'rest_framework_jwt',
'webpack_loader',
'tinymce',
# Local packages
'authentication',
'documents',
'contact',
'home',
'results',
'users'
]
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 = 'config.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',
],
},
},
]
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_settings('DEBUG')
WSGI_APPLICATION = 'wsgi.application'
# Password validation
AUTH_USER_MODEL = 'authentication.User'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# REST Framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
# DRF JWT token settings
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_ALLOW_REFRESH': True,
}
# Webpack settings
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, './config/webpack-stats.json'),
}
}
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# EMAIL SETTINGS
EMAIL_HOST = get_settings('EMAIL_HOST')
EMAIL_HOST_USER = get_settings('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = get_settings('EMAIL_HOST_PASSWORD')
EMAIL_PORT = get_settings('EMAIL_PORT')
EMAIL_USE_TLS = True
My directory structure looks like the following which is based on Two Scoops:
testapp
assets
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
scss
config
config.json
settings.py
urls.py
webpack.config.js
react
index.jsx
static
admin
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
rest_framework
scss
templates
index.html
manage.py
wsgi.py
Also, my urls.py if that might be relevant:
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import TemplateView
from home.views import GetHomeAPIView
urlpatterns = [
# Admin URL
url(r'^admin', admin.site.urls),
# API authentication entry point
url(r'^api/auth/', include('authentication.urls', namespace='signin')),
# API /home entry point
url(r'^api/home/', GetHomeAPIView.as_view(), name='home'),
# API /contact entry point
url(r'^api/contact/', include('contact.urls', namespace='contact')),
# API /contact entry point
url(r'^api/users/', include('users.urls', namespace='users')),
# Any requets that come through serve the index.html
url(r'^$', TemplateView.as_view(template_name='index.html')),
]
So not sure 100% what to do.
I have tried changing both STATIC_ROOT and STATIC_URL to the actual path /home/myapp/src/static/ which didn't do anything.
A bit stumped as to how to resolve this and the SO questions I have reviewed have not fixed the issue.
Well, I got things to start loading by doing the following in urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Also can be read about here.
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development
It is working, but that being said, the sections is called "Serving static files during development"... I'm doing this for production.
I'm using django 1.8 and having trouble with it. I am trying to import tinymce in my project. When I render it caught
AttributeError: tuple' object has no attribute 'regex'
When I remove the url in url.py it is working. Here is my codes.
url.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^$', 'hizlinot.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
]
settings.py
"""
Django settings for hizlinot project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
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.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'b-4jipu5t(+)g(2-7g#s=1rs19dhpj-1-!x1b-*v7s85f-m%&q'
# 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',
'edebiyat',
'tinymce',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'hizlinot.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 = 'hizlinot.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/
STATIC_URL = '/static/'
You forgot the 'url'
url(r'^admin/', include(admin.site.urls)),
url(r'^tinymce/', include('tinymce.urls')),
urlpatterns should be a list of url() instances
url returns RegexURLPattern but instead a tuple is found in your list.
https://docs.djangoproject.com/en/1.8/_modules/django/conf/urls/#url
I know it's not absolutely related to the question, but sometimes this error can be a little deeper than directly in a urls.py file.
I got this error and the cause of the problem wasn't in the error stack trace.
I had this problem while browsing the Admin with a custom Admin Class, and the problem was with the method get_urls() of this class, which was returning something like:
def get_urls(self):
from django.conf.urls import patterns
return ['',
(r'^(\d+)/password/$',
self.admin_site.admin_view(self.user_change_password))] + super(CompanyUserAdmin, self).get_urls()
To fix it:
def get_urls(self):
from django.conf.urls import patterns
return [
url(r'^(\d+)/password/$',
self.admin_site.admin_view(self.user_change_password))] + \
super(CompanyUserAdmin, self).get_urls()
Don't forget the import of 'url':
from django.conf.urls import url