Directory structure -> https://i.stack.imgur.com/oNtk6.png
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__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '...xxx...'
# 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',
'personal'
]
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 = 'mysite.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 = 'mysite.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/'
views.py
from django.shortcuts import render
def index(request):
return render(request, 'personal/mainx.html')
mainx.html (mysite\personal\templates\personal\mainx.html)
...
<body>
<h1>Hello There</h1>
<div>
{% block content %}
{% endblock %}
</div>
</body>
...
home2.html (mysite\personal\templates\personal\home2.html)
{% extends "personal/mainx.html" %}
{% block content %}
<p>Hey! Welcome to my website! Well, I wasn't expecting guests. Um, my name is Harrison. I am a programmer.</p>
{% endblock %}
Setup : Installed Django using pip install > created project > created app > configured n wrote html files
Output https://i.stack.imgur.com/iLQ2s.png
Why it is not rendering the template paragraph text?
In templates we have to render the file having filling content for template & use the file having template content as 'extends' parameter in file having filling content for template.
For example, in above situation "mainx.html" is the template file and "home2.html" is the file having content that is to be rendered on webpage in the structure provided by "mainx.html".
That's why when we render file in "views.py", we will render the "home2.html".
The correct definition of function "index" in "views.py" will be this :
def index(request):
return render(request, 'personal/home2.html')
Related
Not able to load image from static dir in Django. Below is the picture of my file structure.
In settings.py S
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
When I try to load the image file from STATIC_URL, it is producing this error:
it is just not loading images but the text from my home-view.html is loading file thus django is not able to locate the image files. Could you please advise why are images not loading?
home-view.html
{% load static %}
<html>
<head>
{{time}}
<img src="{% static 'myproject/images/test.png' %}" alt="My image">
</head>
</html>
My complete settings.py file :
"""
Django settings for myproject 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
print("Path is : ", os.path.join(BASE_DIR, 'myproject/template'))
# 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-(ep(j)h+$(zro2!9r3bm0fj^!84-1c9d+)$be4hgrq4_#6d^r-'
# 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',
'myproject'
]
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 = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'myproject/template')],
'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 = 'myproject.wsgi.application'
# 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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
]
print("static path" , STATICFILES_DIR)
print(STATIC_URL)
# print("static file : ", (os.path.join(BASE_DIR, '/static')), )
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
instead of this:
STATICFILES_DIR = [os.path.join(BASE_DIR,'static'),]
Do this and try:
STATICFILES_DIRS = [os.path.join(BASE_DIR,'appname/static'),]
and also add this:
os.path.join(BASE_DIR, 'appname', 'templates')
{% load static %}
<html>
<head>
{{time}}
<img src="{% static '/myproject/images/test.png' %}" alt="My image">
</head>
</html>
and make sure you create folder called templates instead of template
I hope this may be help you
In my django project i want to use google authentication for user login. i followed some articles but now stuck at point, where i'm getting error like: Error: redirect_uri_mismatch. i searched allot but could not resolved this issue. plz help
I'm sharing my code here:
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xnph^f^z=wq^(njfp*#40^wran3'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
'core',
]
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',
'social_django.middleware.SocialAuthExceptionMiddleware', # <--
]
ROOT_URLCONF = 'simple.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',
'social_django.context_processors.backends', # <--
'social_django.context_processors.login_redirect',
],
},
},
]
AUTHENTICATION_BACKENDS = (
'social_core.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
LOGIN_URL = 'login'
LOGOUT_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
WSGI_APPLICATION = 'simple.wsgi.application'
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxxxxx my key xXXXXXX'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxx my secrete XXXX'
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/'
urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^logout/$', auth_views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'),
url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
path('^oauth/', include('social_django.urls', namespace='social')), # <--
url(r'^admin/', admin.site.urls),
]
{% extends 'base.html' %}
{% block contents %}
<h2>Login</h2>
<br>
Login with Google<br>
{% endblock %}
link of my Google App settings
https://drive.google.com/open?id=1rX8JEcTSQU8IXubkxWkbAPsG_ka0t76s
try with this,
SOCIAL_AUTH_LOGIN_REDIRECT_URL ='/complete/google-oauth2/'
SOCIAL_AUTH_REDIRECT_IS_HTTPS = True ,
ALLOWED_HOSTS = ['mypage.com', 'localhost', '127.0.0.1']
this works for me
google need to know if you are using a a https and the address after login and yo must allow your domain access
Im trying to load a PDF
My .html
<div class="container">
<div class="row">
<div class="col-lg-12">
<embed src="{{ documento.adjunto.url }}" type="application/pdf" width="100%" height="600px" />
</div>>
</div>
</div>
Where documento.adjunto its the url where the document its saved (in my case "curriculums/CV_2017.pdf")
It throws me Failed to load resourse: 404 not found http://127.0.0.1:8000/INTRANET/uploads/curriculums/CV_2017.pdf
But there is where the PDF is saved
Model:
UPLOAD_CVS = "curriculums/"
class Curriculum(models.Model):
rut_candidato = models.ForeignKey(Candidato, on_delete=models.CASCADE)
adjunto = models.FileField(upload_to=UPLOAD_CVS)
fecha_ingreso_cv = models.DateField(_("Date"), auto_now_add=True)
def get_ultima_actualizacion(self):
actual = datetime.now().date()
return int(round((actual - self.fecha_ingreso_cv).days / 365,0))
def get_cv_name(self):
return
"CV_"+self.rut_candidato.nombre+"_"+self.rut_candidato.apellido+"_"+ str(self.fecha_ingreso_cv)
Settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'INTRANET.apps.IntranetConfig',
'localflavor',
]
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 = 'etalentNET.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['./templates',],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.media',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'etalentNET.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'
#Cambiar a chile
TIME_ZONE = 'Chile/Continental'
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_URL = '/INTRANET/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'INTRANET/uploads')
STATIC_URL = '/static/'
# Por ahora, mientras no se configure envio email https://docs.djangoproject.com/en/2.0/topics/email/
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Redirect to home URL after login (Default redirects to /accounts/profile/)
LOGIN_REDIRECT_URL = '/'
If you don't have this line in your root urls.py, add it
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Note: This, WORKS ONLY IN DEVELOPMENT
Your MEDIA_URL should start with a /.
So instead of MEDIA_URL = 'INTRANET/uploads/', add this:
MEDIA_URL = '/INTRANET/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'INTRANET/uploads') # no Slash before and after
In templates, you don't even need to add the path, Django will generate it:
instead of ../uploads/{{ documento.adjunto }}, add {{ documento.adjunto.url }}
<embed src="{{ documento.adjunto.url }}"
type="application/pdf" width="100%" height="600px" />
you can also use
doc = doc_models.objects.all()
Pdf
I run the code last it's well,but taday when i input http://127.0.0.1:8000/,it show A server error occurred. Please contact the administrator.but I can't find anyerror in settings.py,and i revised the urls.py,then it show
enter image description here
it seems like there are two question
my urls.py
from django.conf.urls import url,include,patterns
from django.contrib import admin
from blog.views import *
#admin.autodiscover()
urlpatterns = patterns('',
url(r'^archive/$',archive),
url(r'^admin/',include(admin.site.urls)),
)
my setting.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'zzwayk(+k0m-+docu%uigkuymxlde34fx3$=syx#*3-i)8hlel'
# 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_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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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.9/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.9/topics/i18n/
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'CCT'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
archive.html
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.timestamp }}</p>
<p>{{ post.body }}</p>
{% endfor %}
{% endblock %}
It seems there is no default (also called root, index or home) url in your urls.py
If you add something like this to your urls.py:
url("^$", views.index),
and also add a function named index in your views.py, you should have home page.
Alternatively, visit http://127.0.0.1:8000/archive/ or http://127.0.0.1:8000/admin/ because those are the urls you have something for.
I want to display and audio stored in filefield but the links comes up dead even though when i upload files to through admin they are showing up in the media directory but are giving dead links in when page loads i even tried to change it from audio to an image with appropriate data still nothing
#template
{% for audios in Audios %}
<audio controls>
<source src="{{ audios.Audio_File.url }}" type="audio/mpeg">
</audio>
{% endfor %}
#settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
#urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
dja
Also here is the entire settings file just incase
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'kv=%#$g8bjbu+b6)#(z#5kp2*-40rz6e6&3h$6dpt$&55+jep#'
ALLOWED_HOSTS = []
STATIC_URL = '/static/'
INSTALLED_APPS = [
'speak.apps.SpeakConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'speakEnglish.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 = 'speakEnglish.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/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
i missed the $ in one of my urls.py
what i had
url(r'^', views.index, name='index'),
what i changed to
url(r'^$', views.index, name='index'),
It took me more than 24 hours to figure it out but i still dont know why only the files that i wanted to get were affected