how to set up Django translation on Heroku - django

help me, where am doing wrong
my settings.py
LANGUAGE_CODE = 'fr'
# LANGUAGE_COOKIE_NAME = 'LANGUAGES'
LOCALE_PATHS = (os.path.join(BASE_DIR, 'authentication/locale'),)
LANGUAGES = (
('fr', _('France')),
('en-us', _('English (US)')),
)
my views.py
def set_language(request):
language = request.POST.get('language', settings.LANGUAGE_CODE)
next_link = request.POST.get('next', "/")
user_language = 'fr'
translation.activate(user_language)
request.session[translation.LANGUAGE_SESSION_KEY] = "fr"
return redirect(next_link)
on local environment it works fine but not working on heroku, please help.

Related

Django PDF media files are not displayed on my web page

I have been looking on the internet all over the place for this
and it seems that everything is in check, also media images are very well displayed
so I have a django web app that has a FileField where you can upload pdfs and now I am trying to display thouse pdfs but they get displayed with the error as the image below shows.
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
X_FRAME_OPTIONS = 'SAMEORIGIN'
show_pdf.html
<iframe
src="{{pdf.url}}"
frameBorder="0"
scrolling="auto"
height="1200px"
width="1200px"
></iframe>
models.py
class File_pdf(models.Model):
title = models.CharField(max_length=50)
pdf = models.FileField(upload_to='portfolio/pdfs')
main_resume = models.BooleanField(default=False,help_text="set only one pdf as the main pdf for the main page")
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('portfolio.urls')),
path('blog/',include('blog.urls'))
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
views.py
def pdf_view(request,pdf_id,resume):
dic = {}
if resume == "yes":
pdf_files = File_pdf.objects.filter(main_resume=True)
pdf_file = pdf_files[0]
dic['pdf'] = pdf_file.pdf
dic['title'] = pdf_file.title
else:
pdf_files = get_object_or_404(File_pdf,pk=pdf_id)
pdf_file = pdf_files[0]
dic['pdf'] = pdf_file.pdf
dic['title'] = pdf_file.title
The error looks like this:
this is actually the correct link
In your settings.py add the following code:
X_FRAME_OPTIONS = 'ALLOW-FROM <your localhost URL>'
for example
X_FRAME_OPTIONS = 'ALLOW-FROM http://127.0.0.1:8000/'
it turns out that everything was correct but the brave cache somehow was in conflict with the X_FRAME_OPTIONS updating itself. so after deleting brave's cache it was enough :)

Change language in custom middleware

I would like to change language in my custom middleware. For some reason code below doesn't work.
class LanguageMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print('set language to spanish...')
translation.activate("es")
request.LANGUAGE_CODE = "es"
response = self.get_response(request)
translation.deactivate()
return response
settings.py
LANGUAGES = (
("en", "English"),
("es", "Spanish"),
)
LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),)
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = "en"
if I change LANGUAGE_CODE is settings to "es" I get spanish API responses but I would like to be able to change it programmatically in my middleware.
This works for me:
def set_lang_middleware(get_response):
def middleware(request):
translation.activate("es")
response = get_response(request)
return response
return middleware
Do not forget to add your middleware in settings.MIDDLEWARE.

django internationalization is not translated to English on the server. Local is normal

python: 3.6 / 3.8
django: 3.2.3
django internationalization is not translated to English on the server. But LanguageCode is correct.
Local is normal.
settings.py
# 国际化语言种类
from django.utils.translation import gettext_lazy as _
LANGUAGES = (
('en-us', _('English')),
('zh-Hans', _('中文简体')),
)
DEFAULT_LANGUAGE = 1
# 国际化翻译文件目录
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
views.py
def ocr(request):
translateWords = {}
translateWords["title"] = _("图片转文字")
translateWords["clickButtonWord"] = _("一键转文字")
translateWords["txtareaPlaceholder"] = _("输出内容...")
translateWords["clickCopy"] = _("点击复制")
translateWords["numberOfRrecognizedCharacters"] = _("识别输出文字数:")
translateWords["copied"] = _("已复制")
translateWords["notes"] = _("注意事项:上传图片最大4兆本应用永久免费使用!")
translateWords["aboutUs"] = _("联系我们")
print(get_language())
return render(request, 'ocr.html', {"translateWords":translateWords,
})
xxx.html
{% load i18n %}
<h4>OCR {%trans "图片转文字" %}</h4>
I tried compiling the mo file on the server's direct command line, but it didn't work.
Command is :
python manage.py makemessages -l en_us
python manage.py makemessages -l zh_Hans
python manage.py compilemessages
screenshot

Django Internationalization and localization instead of /en use a specific domain for each language

i have 3 domains, which will be one website, just that each one will serve a language
ej: (right now i am in dev mode so i only have localhost to test)
drenglish.com for 'en'
drspanish.com for 'es_ES'
drportugueses for 'pt_BR'
automatically Internationalization and localization works with /lang added to the urls, but i dont want that
i tried transurlvania but cant figure it out, is there an easy way to use my translated po file and tie it to a domain ?
site framework seem to maybe be the answer, but i get lost when they tell to create different settings and urls files for each domain so you can add the right SITE_ID
i am starting to use i18n for the internationalization and localization
settings;
middleware: 'django.contrib.sites.middleware.CurrentSiteMiddleware'
USE_I18N = True
#drspanish.com = ID 5
#drportugueses = ID 4
#drenglish.com = ID 1
SITE_ID = 1
from django.utils.translation import ugettext_lazy as _ LANGUAGES = (
('en', _('English')),
('pt_BR', _('Portuguese')),
('es_ES', _('Spanish')), )
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'), )
urls(main);
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
#urls for english + global
path('admin/', admin.site.urls),
path('users/', include('users.urls')), #for allauth
path('accounts/', include('allauth.urls')), #for allauth
url(r'^ckeditor/', include('ckeditor_uploader.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # comment out this line from the +... if the website is live, its only to serve image in debug mode
urlpatterns += i18n_patterns(
url('', include('home.urls')), #for allauth
url('contact', include('contact.urls')),
url(r'^videos/', include('video.urls')),
url(r'^dash/', include('UDash.urls')),
url(r'^appointment/', include('appointment.urls')),
url(r'^blog/', include('blog.urls')),
url(r'^cart/', include('cart.urls')),
url(r'^shop/', include('shop.urls')), )
You can use a middleware to set your language depending on the domain you are accessing. For example, create a middleware SetLanguageToDomain which will look like this,
from django.utils import translation
from django.contrib.sites.shortcuts import get_current_site
class SetLanguageToDomain:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
current_site = get_current_site(request).domain
if current_site == 'drenglish':
user_language = 'en'
elif current_site == 'drspanish':
user_language = 'es_ES'
else:
user_language = 'pt_BR'
translation.activate(user_language)
request.session[translation.LANGUAGE_SESSION_KEY] = user_language
response = self.get_response(request)
return response
Then add this to your middlewares after the locale middleware.
Hope this helps!

django-auth-ldap failed authentication

I'm trying to use Django-Auth-Ldap in my project (Django 1.6, Python 2.7) but it is not working.
My active Directory shema is:
I've tested the connection on the cmd line by installing the ldap-utils package
sudo apt-get install ldap-utils
ldapsearch -H ldap://domain.com -D "ou=Resources,ou=Company, dc=domain,dc=com" -U "user_name" -w "user_password" -v -d 1
The connection test works fine.
I am using below code to test python-ldap connection from the shell:
import ldap
con = ldap.initialize('ldap://domain.com')
con.simple_bind_s('User_mail', 'User_password')
results = con.search_s('ou=Users,ou=Resources,ou=Company,dc=domain,dc=com', ldap.SCOPE_SUBTREE, "(cn=User_name)")
python-ldap connection works fine.
My problem is how to authenticate AD users from my django login interface?
settings.py:
import ldap
from django_auth_ldap.config import LDAPSearch
# The URL of the LDAP server.
AUTH_LDAP_SERVER_URI = "ldap://domain.com"
AUTH_LDAP_BIND_DN = "cn='User_name',ou=Resources,ou=Company,dc=domain,dc=com"
AUTH_LDAP_BIND_PASSWORD = "User_password"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=Users,ou=Resources,ou=Company,dc=domain,dc=com",ldap.SCOPE_SUBTREE, "(cn=%(user)s)")
AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_REFERRALS : False }
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
views.py:
from django_auth_ldap.backend import LDAPBackend
auth = LDAPBackend()
user = auth.authenticate(username="User_name", password="User_password")
In the file django-ldap-debug.log I have this error:
Caught LDAPError while authenticating User_name: INVALID_CREDENTIALS({'info': '80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1', 'desc': 'Invalid credentials'},)
I found the answer.
I changed the AUTH_LDAP_BIND_DN by adding (OU=Users)
I must use samAccountName instead of CN in AUTH_LDAP_USER_SEARCH
My new settings.py :
import ldap, logging
from django_auth_ldap.config import LDAPSearch
logger = logging.getLogger('django_auth_ldap')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
AUTH_LDAP_SERVER_URI = "ldap://domain.com"
AUTH_LDAP_BIND_DN = "CN=User_name,OU=Users,OU=Resources,OU=Company,DC=domain,DC=com"
AUTH_LDAP_BIND_PASSWORD = "User_password"
AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=Users,OU=Resources,OU=Company,DC=domain,DC=com",ldap.SCOPE_SUBTREE, "(samAccountName=%(user)s)")
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
My views.py
from django_auth_ldap.backend import LDAPBackend
def login(request):
if request.method == 'POST':
form = MyLoginForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
auth = LDAPBackend()
user = auth.authenticate(username=username, password=password)
if user is not None:
....
else:
form = MyLoginForm()
....
Hope this help all :)
I had similar problem but I have solved it other way around. Under AUTH_LDAP_BIND_DN have just put the user and domain and password. After that this was working like charm...
While I was investigating my ldaps issues I found above solution somehow useful, maybe also someone will benefit with my solution
LDAP_IGNORE_CERT_ERRORS = True
AUTH_LDAP_START_TLS = False
AUTH_LDAP_SERVER_URI = "ldaps://domain.com:636"
AUTH_LDAP_BIND_DN = "serviceaccount#domain.com"
AUTH_LDAP_BIND_PASSWORD = "superPass"
AUTH_LDAP_USER_SEARCH = LDAPSearch(
"OU=Company,DC=domain,DC=com",ldap.SCOPE_SUBTREE,"(sAMAccountName=%(user)s)"
)
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail"
}