I have asked another question about the issue of displaying images from models. and It was because I didn't add media url to urlpatterns. But it turns out that it only works when I set debug=true in settings file, when I set debug=false, I got 404 error again, any expert here to help ? I need to set debug=false for production
here my urls.py file
from django.contrib import admin
from django.urls import path
from home import views as HomeViews
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
import os
urlpatterns = [
path('admin/', admin.site.urls),
path('',HomeViews.index,name='home')
]
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my settings file
from pathlib import Path
import os
import django_heroku
import django
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc#13'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home',
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'testimage.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 = 'testimage.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 = [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/'
django_heroku.settings(locals())
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
my models.py
from django.db import models
# Create your models here.
class Images(models.Model):
photo = models.ImageField(blank=True, null=True, default=None)
title = models.CharField(max_length=250)
def __str__(self):
return self.title
views and template
from django.shortcuts import render
from home.models import Images
# Create your views here.
def index(request):
images = Images.objects.all()
context = {
'images':images
}
return render(request,'home.html',context)
template
{%for i in images %}
<img src="{{MEDIA_URL}}{{i.photo.url}}" alt="">
{%endfor%}
Here's the error when set debug=false:
[15/Feb/2021 13:17:05] "GET /media/20210129_205930.jpg HTTP/1.1" 404 179
[15/Feb/2021 13:17:05] "GET /media/20201227_111422.jpg HTTP/1.1" 404 179
Please help me out. Many thanks !
I face the same problem
but I solve this problem using this code
pip install whitenoise
in settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / "media"
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
In urls.py
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
urlpatterns = [
path('user_area/', admin.site.urls),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('', include('main.urls')),
path('', include('user_area.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), ]
python manage.py collectstatic
Follow this code you will solve your problems
You should insert some ALLOWED_HOSTS in settings.py like :-
ALLOWED_HOSTS = ['*']
or Your website name :-
ALLOWED_HOSTS = ['your_website_name']
Related
I am a newbie to Django and trying to deploy my Django app on Heroku. I followed a tutorial and did everything, but when I was finally ready to deploy my app, I get the error "Page not found."
I have tried removing the include() around my admin.site.urls because it worked for someone else, but it didn't work for me.
this is my urls.py file:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from profiles.views import delete
urlpatterns = [
path(r'^profiles/', include('profiles.urls')),
path(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
this is my settings.py file:
import os
import django_heroku
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'firstDjango.settings'
from django.core.wsgi import get_wsgi_application
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY="bb33e5a618aa4f6e549b8207ad1d8fa7cd8d1015e13c8780"
DEBUG = True
ALLOWED_HOSTS = ['ewuradjango.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#third party
#own
# 'pages'
'profiles',
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'firstDjango.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',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'firstDjango.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATIC_TMP = os.path.join(BASE_DIR, 'static')
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
django_heroku.settings(locals())
This is the verbose error:
Page not found (404)
Request Method: GET
Request URL: https://ewuradjango.herokuapp.com/
Using the URLconf defined in firstDjango.urls, Django tried these URL patterns, in this order:
^profiles/
^admin/
^media/(?P<path>.*)$
The empty path didn't match any of these.
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.
Looks like you haven't got a route set up for your root path '/'. Try accessing https://ewuradjango.herokuapp.com/admin or https://ewuradjango.herokuapp.com/profiles as you've got paths for them set up in your first code block.
To add a root path try something like:
urlpatterns = [
path(r'', admin.site.urls),
path(r'^profiles/', include('profiles.urls')),
path(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
which should direct your root path to your admin page.
i have django website that require authentication and user login in order to use some functions and view templates.
i used the decorator #login_required but nothing is change and anyone still able to view html page and use any function.
what am i missing in my code ??
views.py
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required(login_url="/login/")
def create(request):
...
return render(request,'blog/create.html')
urls.py
"""ABdatabase URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from blog.views import *
from .views import *
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path("usr/logMeIn", logMeIn),
path("usr/logMeOut", logMeOut),
path('mainpage',mainpage,name="main"),
path('blog/', include('blog.urls')),
]
blog.urls.py
# from django.contrib import admin
from django.urls import path
from .views import *
# from django.conf.urls.static import static
# from django.conf import settings
urlpatterns = [
path('create/', create),
path('list/', listANDsearch,name="list"),
path('details/<int:pk>/',get_details,name= 'result'),# using <int:id> in order to display the id
path('listdd',homeInputlineBottom),
]
settings.py
"""
Django settings for ABdatabase project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5(%xarj8+c73-jmn*666gsmj1w5ix%vha8-c1vocevb=2#(()e'
# 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',
'blog',
]
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 = 'ABdatabase.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',
# 'blog.context_processors.home',
],
},
},
]
WSGI_APPLICATION = 'ABdatabase.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'canada'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS= [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
even after i used the decorator nothing it change.
try this
def create(request):
user = request.user
if not user.is_authenticated:
return redirect('/') # Redirect whatever you want
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')
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()),
]