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
Related
When I want to "python manage.py makemigrations", it returns the following.
System check identified some issues:
WARNINGS
?: (staticfiles.W004) The directory '/static/' in the STATICFILES_DIRS setting does not exist.
How should I solve this issue?
from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'orders', ]
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 = ‘rtu_server.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 = ‘rtu_server.wsgi.application'
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 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 = 'Asia/Hong_Kong' USE_I18N = True USE_TZ = True STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
It just says that you created STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] in your settings.py, but you didn't have any static folder in your project.
It is not a big issue right now because you might not be using external CSS or JS. But if you want to solve the issue, you can just create a static folder in your project.
So what you need to do here to make it easier for you is to navigate to the location where you have your project created and create a FOLDER called static. Don't try to do it for your IDE editor as you might end up getting confused. I am assuming you are trying to link up files such as CSS to your Django project. Do this and your problem will be solved.
Also, remember to load your static statement at the header of your HTML page.
As an example:
<link rel='stylesheet' href='{% static 'style.css' %}' type='text/css'>
{% load static %}
Create a folder "static" in root directory if you still see error, then.
The problem is with this i believe,
BASE_DIR = Path(__file__).resolve().parent.parent
Let's say this is tree of folder where your "settings.py" is:
E:\\Project>Project>mySettings>settings.py
Then you have to modify BASE_DIR little bit like below,
BASE_DIR = Path(__file__).resolve().parent.parent.parent
one .parent for each folder
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
I am not able to show the images saved in the database, all other data appears, the only problem is in the images, in the html put the 3 commanders I tried to load the images.
I am very beginner in python and django any help would be very welcome
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
models.py:
class Usuario(models.Model):
foto = models.ImageField( blank=False, verbose_name="Foto para seu perfil", upload_to='sistema/img')
settings.py:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$n+6cd+9w+44=z*0o=8b#t&9*i!_ay%&6+kl=_cbq0%*sm0)c('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['.127.0.0.1',]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sistema',
'PetAqui',
'bootstrapform',
'widget_tweaks',
'crispy_forms',
'multiselectfield',
'django.contrib.sites',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
SITE_ID=1
CRISPY_TEMPLATE_PACK = 'bootstrap4'
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 = 'PetAqui.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 = 'PetAqui.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'petaqui',
'USER': 'postgres',
'PASSWORD': 'gt1utff7st3re',
'HOST': 'localhost',
'PORT': '5432',
}
}
# 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 = 'pt-br'
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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'estacioneaqui24#gmail.com'
EMAIL_HOST_PASSWORD = '10038561003856'
EMAIL_PORT = 587
LOGIN_REDIRECT_URL = 'sistema_index'
LOGOUT_REDIRECT_URL = 'sistema_index'
LOGIN_URL = 'sistema_index'
MEDIA_ROOT='/sistema/img/'
MEDIA_URL='/img/'
html:
<img src="{{MEDIA_URL}}/{{ user.usuario.foto }}" >
{{ user.usuario.foto }}
{{ user.usuario.foto.url }}
urls.py
from django.conf.urls import url
from django.urls import include, path
from . import views
from .views import (
index,
cadastro,
cadastro_novo,
cadastro_negocio,
activate,
account_activation_sent,
perfil
)
urlpatterns = [
url(r'^index/$', index, name='sistema_index'),
url(r'^cadastro/$', cadastro, name='sistema_cadastro'),
url(r'perfil/$', perfil, name='sistema_perfil'),
url(r'^cadastro-novo/$', cadastro_novo, name='sistema_cadastro_novo'),
url(r'^cadastro-negocio/$', cadastro_negocio, name='sistema_cadastro_negocio'),
url(r'^account_activation_sent/$', views.account_activation_sent, name='account_activation_sent'),
path('activate/<uidb64>/<token>/', views.activate, name='activate'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Try using
<img src="{{ user.usuario.foto.url }}" />
If that doesn't work, then include your urls.py file, what url you're browsing to and what response is returned.
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 use django-ckeditor module in my blog as WYSIWYG editor for create and edit articles in the administration. It work pretty well but I can't upload image to my server. When I click on the image button, the button "browse the server" and "upload image" doesn't appear as they supposed to (I saw it somewhere). I can only add externals images providing their urls.
I use Django 1.8 with Python 3.4
The module django-ckeditor and ckeditor_uploader are correctly installed and added in the INSTALLED_APP.
This is my settings.py file :
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'ckeditor',
'ckeditor_uploader',
)
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 = 'django-mini-blog.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',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'django-mini-blog.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"
Thanks in advance for your help.
Sincerely,
Did you add the following code to your urls.py file?
urlpatterns = patterns(
'',
....
(r'^ckeditor/', include('ckeditor.urls')),
)