I have a basic django cms running with lots of localised content. I have been assigned to add few more languages before content can take over.
here is a sample english url:
<domain>/en/myhelp/
this is the sample menu which is supposed to render the menu dropdown:
<body>
{% cms_toolbar %}
<div class="container faq-main main-block">
<div class="select-wrapper">
<select name="language" id="faq-lang" class="lang-btn hide">
<option value="en">English</option>
<option value="hi">हिंदी</option>
<option value="mr">मराठी</option>
<option value="te">తెలుగు</option>
<option value="ta">தமிழ்</option>
<option value="kn">ಕನ್ನಡ</option>
<option value="bn">বাংলা</option>
<option value="ml">മലയാള൦</option>
<option value="gu">ગુજરાતી</option>
</select>
</div>
{% block content %}{% endblock content %}
{% block contact %}{% endblock contact %}
{% block actions %}{% endblock actions %}
</div>
{% render_bundle 'faq' 'js' %}
{% render_block "js" %}
</body>
any language selected from menu dropdown updates the url accordingly. for example on selecting mr, url mentioned above would change to:
<domain>/mr/myhelp/
All good so far.
Now i have added 2 more langs in this menu:
<option value="od">ଓଡିଆ</option>
<option value="as">অসমীয়া</option>
Problem is that when i select od / as from menu, url changes to:
<domain>/en/od/myhelp/
<domain>/en/as/myhelp/
basically, en is not removed from url locale causing page not found error. Any help or indication in right direction to correctly add this locale is appreciated.
version:
django-cms: 3.7.1
Django: 2.1
basic code:
urls.py
admin.autodiscover()
urlpatterns = [
url(r'^events/(?P<path>.*)$', EventsProxyView.as_view()),
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': {'cmspages': CMSSitemap}}),
url(r'^healthcheck/$', healthcheck)
]
urlpatterns += i18n_patterns(
url(r'^admin/login', home),
url(r'^admin/', admin.site.urls), # NOQA
url(r'^', include('cms.urls')),
)
urlpatterns += [
url('', include('social_django.urls', namespace='social')),
]
relevant part from settings.xml
import os # isort:skip
from urllib.parse import urljoin
gettext = lambda s: s
DATA_DIR = os.path.dirname(os.path.dirname(__file__))
import os
from django.conf import global_settings
import django.conf.locale
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
ALLOWED_HOSTS = [
'*',
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'cms', 'templates'),],
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.i18n',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.template.context_processors.csrf',
'django.template.context_processors.tz',
'sekizai.context_processors.sekizai',
'django.template.context_processors.static',
'cms.context_processors.cms_settings',
],
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
])],
},
},
]
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'redirection.middleware.MyHelpRedirectMiddleware',
'djangocms_redirect.middleware.RedirectMiddleware',
'django.middleware.security.SecurityMiddleware',
'cms.middleware.HostsPrinterMiddleware',
'cms.middleware.DisableCSRF',
'cms.middleware.utils.ApphookReloadMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.language.LanguageCookieMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'cms', 'scripts', 'dist', 'bundles', 'webpack-stats.json'),
}
}
INSTALLED_APPS = [
'djangocms_admin_style',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'django.contrib.messages',
'cms',
'menus',
'sekizai',
'treebeard',
'djangocms_text_ckeditor',
'filer',
'easy_thumbnails',
'djangocms_column',
'djangocms_file',
'djangocms_link',
'djangocms_picture',
'djangocms_style',
'djangocms_snippet',
'djangocms_googlemap',
'djangocms_video',
'social_django',
'revproxy',
'djangocms_redirect',
'redirection',
'webpack_loader',
'django_select2',
'accordion'
]
LANGUAGES = (
## Customize this
('en', gettext('en')),
('hi', gettext('hi')),
('mr', gettext('mr')),
('te', gettext('te')),
('ta', gettext('ta')),
('kn', gettext('kn')),
('gu', gettext('gu')),
('bn', gettext('bn')),
('ml', gettext('ml')),
('as', gettext('as')),
('od', gettext('od'))
)
CMS_LANGUAGES = {
## Customize this
1: [
{
'code': 'en',
'name': gettext('en'),
'redirect_on_fallback': True,
'public': True,
'hide_untranslated': False,
},
{
'code': 'hi',
'name': gettext('hi'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'mr',
'name': gettext('mr'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'te',
'name': gettext('te'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'ta',
'name': gettext('ta'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'kn',
'name': gettext('kn'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'gu',
'name': gettext('gu'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'bn',
'name': gettext('bn'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'ml',
'name': gettext('ml'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'od',
'name': gettext('od'),
'public': True,
'fallbacks': ['en'],
},
{
'code': 'as',
'name': gettext('as'),
'public': True,
'fallbacks': ['en'],
}
],
'default': {
'fallbacks': ['en', 'hi'],
'redirect_on_fallback': True,
'public': True,
'hide_untranslated': False,
},
}
CMS_TEMPLATES = (
## Customize this
('fullwidth.html', 'Fullwidth'),
('faq_fullwidth.html', 'FAQ Fullwidth'),
('faq_article.html', 'FAQ Article'),
('faq_article_with_feedback.html', 'FAQ Article with Feedback'),
)
CMS_PERMISSION = True
CMS_PLACEHOLDER_CONF = {}
MIGRATION_MODULES = {
}
THUMBNAIL_PROCESSORS = (
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
'filer.thumbnail_processors.scale_and_crop_with_subject_location',
'easy_thumbnails.processors.filters'
)
CMS_MYHELP_REDIRECT_USE_REQUEST = True
CMS_MYHELP_REDIRECT_ALLOWED_PATHS = {
'/myhelp',
'/myhelp/',
'/en/myhelp',
'/en/myhelp/',
}
Related
I am trying to have React upload an image via React DropZone. However, when I go to my blog manager page, the console promptly logs 404 Failed to load resource: the server responded with a status of 404 (Not Found). I am using Django Rest Framework for the backend, and in the terminal it states "GET /media/Upload%20image HTTP/1.1". The frontend, react, is able to get the image file on the page, but it will not upload.
Here is the settings.py in backend DRF:
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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'p%s-9w1l268#!b$p#92dj26q)pv7!&ln^3m(1j5#!k8pkc9#(u'
# 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',
'django.contrib.sites',
# 'allauth',
# 'allauth.account',
# 'allauth.socialaccount',
'corsheaders',
# 'rest_auth',
# 'rest_auth.registration',
'rest_framework',
# 'rest_framework.authtoken',
'menus',
'phlogfeeder',
'login'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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 = 'chefsBackEnd.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 = 'chefsBackEnd.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Here is where my static file settings are:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# STATICFILES_FINDERS = [
# 'django.contrib.staticfiles.finders.FileSystemFinder',
# 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# ]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
# SITE_ID = 1
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework.authentication.TokenAuthentication',
# 'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000'
]
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER': 'chefsBackEnd.utils.resp_handler',
# 'JWT_ENCODE_HANDLER':
# 'rest_framework_jwt.utils.jwt_encode_handler',
# 'JWT_DECODE_HANDLER':
# 'rest_framework_jwt.utils.jwt_decode_handler',
# 'JWT_PAYLOAD_HANDLER':
# 'rest_framework_jwt.utils.jwt_payload_handler',
# 'JWT_PAYLOAD_GET_USER_ID_HANDLER':
# 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
}
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 django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework_jwt.views import obtain_jwt_token
from rest_framework_jwt.views import verify_jwt_token
urlpatterns = [
path('api-auth/', include('rest_framework.urls')),
path('rest-auth/', include('rest_auth.urls')),
# path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('token-auth/', obtain_jwt_token),
path('api-token-verify/', verify_jwt_token),
path('login/', include('login.urls')),
path('admin/', admin.site.urls),
path('api/', include('menus.api.urls')),
path('phlogapi/', include('phlogfeeder.phlogapi.urls'))
]
here I add the url patterns to provide access to static and media files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The console keeps saying upload/%20/media.
The front end:
phlogEditor.js
import React, { Component } from 'react';
import axios from 'axios';
import DropzoneComponent from 'react-dropzone-component';
import "../../../node_modules/react-dropzone-component/styles/filepicker.css";
import "../../../node_modules/dropzone/dist/min/dropzone.min.css";
class PhlogEditor extends Component {
constructor(props) {
super(props);
this.state = {
id: '',
phlog_status: '',
phlog_image: '',
editMode: false,
position: '',
apiUrl: 'http://127.0.0.1:8000/phlogapi/phlog/create/',
apiAction: 'post'
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.componentConfig = this.componentConfig.bind(this);
this.djsConfig = this.djsConfig.bind(this);
this.handlePhlogImageDrop = this.handlePhlogImageDrop.bind(this);
this.deleteImage = this.deleteImage.bind(this);
this.phlogImageRef = React.createRef();
}
deleteImage(event) {
event.preventDefault();
axios
.delete(
`http://127.0.0.1:8000/phlogapi/phlog/${this.props.id}/delete`,
{ withCredentials: true }
)
.then(response => {
this.props.handlePhlogImageDelete();
})
.catch(error => {
console.log('deleteImage failed', error)
});
}
componentDidUpdate() {
if (Object.keys(this.props.phlogToEdit).length > 0) {
const {
id,
phlog_image,
phlog_status,
position
} = this.props.phlogToEdit;
this.props.clearPhlogsToEdit();
this.setState({
id: id,
phlog_image: phlog_image || '',
phlog_status: phlog_status || '',
position: position || '',
editMode: true,
apiUrl: `http://127.0.0.1:8000/phlogapi/phlog/${this.props.id}/update`,
apiAction: 'patch'
});
}
}
handlePhlogImageDrop() {
return {
addedfile: file => this.setState({ phlog_image: file })
};
}
componentConfig() {
return {
iconFiletypes: [".jpg", ".png"],
showFiletypeIcon: true,
postUrl: "https://httpbin.org/post"
};
}
djsConfig() {
return {
addRemoveLinks: true,
maxFiles: 3
};
}
buildForm() {
let formData = new FormData();
formData.append('phlog[phlog_status]', this.state.phlog_status);
formData.append('phlog[position]', this.state.position);
if (this.state.phlog_image) {
formData.append(
'phlog[phlog_image]',
this.state.phlog_image
);
}
return formData;
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
handleSubmit(event) {
axios({
method: this.state.apiAction,
url: this.state.apiUrl,
data: this.buildForm(),
withCredentials: true
})
.then(response => {
if (this.state.editMode) {
this.props.handlePhlogSubmission();
} else {
this.props.handleNewPhlogSubmission(response.data);
}
this.setState({
phlog_status: '',
phlog_image: '',
position: '',
editMode: false,
apiUrl:'http://127.0.0.1:8000/phlogapi/phlog/create/',
apiAction: 'post'
});
[this.phlogImageRef].forEach(ref => {
ref.current.dropzone.removeAllFiles();
});
})
.catch(error => {
console.log('handleSubmit phlogEditor error', error);
});
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit} className='phlog-editor-wrapper'>
<div className='two-column'>
<input
type='text'
name='position'
placeholder='Position'
value={this.state.position}
onChange={this.handleChange}
/>
<select
name='phlog status'
value={this.state.phlog_status}
onChange={this.handleChange}
className='select-element'
>
<option value='Draft'>Draft</option>
<option value='Published'>Published</option>
</select>
</div>
<div className='image-uploaders'>
{this.state.editMode && this.state.phlog_image_url ? (
<div className='phlog-manager-image-wrapper'>
<img src={this.state.phlog_image_url} />
<div className='remove-image-link'>
<a onClick={() => this.deleteImage('phlog_image')}>
Remove Photos
</a>
</div>
</div>
) : (
<DropzoneComponent
ref={this.phlogImageRef}
config={this.componentConfig()}
djsConfig={this.djsConfig()}
eventHandlers={this.handlePhlogImageDrop()}
>
<div className='phlog-msg'>Phlog Photo</div>
</DropzoneComponent>
)}
</div>
<button className='btn' type='submit'>Save</button>
</form>
);
}
}
export default PhlogEditor;
Add the Build folder to the INSTALLED_APPS in the settings.py file.
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')
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 have a problem with my Django Translations.
My Django doesn't translate my tags.
I use django-cms and in django-cms I have a plugin djangocms-blog.
Django == 1.6.5
Django-cms == 3.0.3
Djangocms-blog == 0.2b5
My transtags are not translated.
Example tag:
{% trans "read more" %}
I installed everything correctly, my settings.py contains this:
gettext = lambda s: s
# Internationalization
LANGUAGE_CODE = 'nl'
TIME_ZONE = 'Europe/Brussels'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGES = (
('nl', _(u'Dutch')),
('fr', _(u'French')),
('en', _(u'English')),
)
CMS_LANGUAGES = {
1: [
{
'code': 'nl',
'name': gettext('Dutch'),
'fallbacks': ['en', 'fr'],
'public': True,
'hide_untranslated': True,
'redirect_on_fallback':False,
},
{
'code': 'en',
'name': gettext('English'),
'fallbacks': ['nl'],
'public': False,
'hide_untranslated': True,
'redirect_on_fallback':False,
},
{
'code': 'fr',
'name': gettext('French'),
'public': False,
'hide_untranslated': True,
},
],
2: [
{
'code': 'nl',
'name': gettext('Dutch'),
'public': True,
'fallbacks': ['en'],
},
],
'default': {
'fallbacks': ['en', 'fr'],
'redirect_on_fallback': True,
'public': False,
'hide_untranslated': False,
}
}
In My Middleware classes:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.language.LanguageCookieMiddleware',
)
My urls.py:
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = i18n_patterns(
'',
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^admin/', include(admin.site.urls)),
url(r'^products/', include('catalog.urls')),
url(r'^contact/', 'contact.views.contact'),
url(r'^pages/', include('django.contrib.flatpages.urls')),
url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')),
url(r'^', include('cms.urls')),
)
if settings.DEBUG:
import debug_toolbar
urlpatterns = i18n_patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
url(r'^404/$', 'django.views.defaults.page_not_found'), # TODO MOET NOG VERPLAATST WORDEN
url(r'^500/$', 'django.views.defaults.server_error'), # TODO MOET NOG VERPLAATST WORDEN
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns
In my blog_items.html page (a page from the djangocms-blog plugin template that I override)
{% load i18n thumbnail cms_tags %}
{% load url from future %}
I created my languages within the virtual env by
Going to the virtual env by "workon app"
I run the command django-admin.py makemessages -l nl (the po files are created correctly)
I run the command django-admin.py compilemessages and everything seems fine
In the root of my program is the locale folder with 3 subfolders: en, fr and nl. They contain all the LC_MESSAGES folder with a django.mo and django.po file with the correct message strings.
#: .\templates\djangocms_blog\includes\blog_item.html:37 #, fuzzy
msgid "read more"
msgstr "lees meer"
This is solved.
First of all the fuzzy had to be removed.
I had to add the parler settings correct into my general settings:
In the documentation of Django-parler (https://pypi.python.org/pypi/django-parler ) they suggest the next settings:
PARLER_LANGUAGES = {
None: (
{'code': 'nl',},
{'code': 'en',},
{'code': 'fr',},
),
}
Instead of
PARLER_LANGUAGES = {
1: (
{'code': 'nl',},
{'code': 'en',},
{'code': 'fr',},
),
}
AFAIK translations marked as fuzzy are not compiled in the mo files and you must "unfuzzy" them before being available