Django Logout Changes Language to Default Language - django

Am Working on Arabic-English Translation using 'Model Translation'.Once i login and change to arabic and then logout language changes to english.
This is my logout code:,I have activated language after logout and it prints language as 'ar' but it displays english.Please help me
def profile_logout(request,mode=None, **kwars):
lang = request.LANGUAGE_CODE
response = logout(request, **kwars)
translation.activate(lang)
print "langggggggggggggggggggggggggggggggggg",request.LANGUAGE_CODE
return response

I made some changes to my views by creating sessions.Hope someone will find use with this.This Worked for me.
def profile_logout(request,mode=None, **kwars):
lang = request.LANGUAGE_CODE
translation.activate(lang)
language=request.session.get('django_language')
print "languageeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",language
response = logout(request, **kwars)
if language is not None:
request.session['django_language'] = language
print
"request.session['django_language']request.session['django_language']request.session['django_language']",request.session['django_language']
return response
Or Refer:
``https://github.com/ludwiktrammer/django/commit/adfb2c114f94df4a77a9424001e300f0552c6e20

You should activate the translation before processing the template, e.g. before calling logout. something like:
def profile_logout(request,mode=None, **kwars):
lang = request.LANGUAGE_CODE
translation.activate(lang)
response = logout(request, **kwars)
print "langggggggggggggggggggggggggggggggggg",request.LANGUAGE_CODE
return response

Related

How do I change the local path of a language in Django?

I have a web set up with 3 languages (['es', 'en', 'it']) ​​in Angular that works with the Django server.
Django by default has the English local path defined as /en, I want the url of the English configuration to be '/us' (by default it is '/ en'), I just want to change it for English, for 'es' or 'it' as it comes by default is fine.
I want the URL to look like this myurl.com/us in English, how would you recommend me to make this change?
The structure is the following:
-apps
--webapp
---templates
----webapp
-----en (inside index.html)
-----es (inside index.html)
-----it (inside index.html)
-conf
--settings.py
-middleware
--locale.py
conf.settings.py have this language configuration
LANGUAGES = (
('es', _('Spanish')),
('it', _('Italian')),
('en', _('English')),
)
LANGUAGE_CODE = 'es'
LANGUAGE_CODES = [language[0] for language in LANGUAGES]
Additionally I have configured a middleware to recognize the user's location and place the corresponding language code in the URL
from django.conf import settings
from .utils.geolocation import get_language_by_ip
cookie_name = settings.LANGUAGE_COOKIE_NAME
class LocalizationMiddleware(object):
def get_language_cookie(self, request):
return request.COOKIES.get(cookie_name)
def set_language_cookie(self, request, value):
request.COOKIES[cookie_name] = value
def get_i18n_url_language(self, request):
url = request.path.split('/')
if len(url) > 1 and len(url[1].split('-')[0]) == 2:
return url[1]
return None
def process_request(self, request):
language = self.get_i18n_url_language(request)
if language is not None and language not in settings.LANGUAGE_CODES:
return
if language is None:
language = self.get_language_cookie(request)
if language is None:
language = get_language_by_ip(request)
if language is None:
language = settings.LANGUAGE_CODE
self.set_language_cookie(request, language)
return None
def process_response(self, request, response):
response.set_cookie(cookie_name, request.COOKIES.get(cookie_name, settings.LANGUAGE_CODE))
return response
This all works fine, however I want the url for the English language to change from .../en to .../us

How to redirect to previous page after language changing?

When I am trying to use next it doesn't work because in next-url there are old language code so language doesn't change.
my template:
en
ru
my url:
path('language-change/<user_language>/', views.set_language_from_url, name="set_language_from_url"),
my view:
def set_language_from_url(request, user_language):
translation.activate(user_language)
request.session[translation.LANGUAGE_SESSION_KEY] = user_language
redirect_to = request.POST.get('next', request.GET.get('next', '/'))
return redirect(redirect_to)
Use redirect_to = request. META.get('HTTP_REFERER','')
You can use Django's built in set_language_view.
This is a view that can be used to change the language of the user, and when passing redirect_to, it will automatically build the correct url for the next page to go to.
You can check out the example provided in the docs.
You can also simply change your code to not include the path of the request, but the name of the url to redirect to, like this (Assuming you have a url in you url_patterns with the name 'view_page':
en
ru
Your view:
def set_language_from_url(request, user_language):
translation.activate(user_language)
request.session[translation.LANGUAGE_SESSION_KEY] = user_language
redirect_to = request.POST.get('next', request.GET.get('next', '/'))
return redirect(reverse(redirect_to))
Edit:
For returning to the current request instead of predefined request (I have not tested this, so I don't know if it will work):
You could try resolving the path of the current request, and reversing it again, passing in the correct arguments. This should return the exact url as before, only with a different language prefix.
en
ru
def set_language_from_url(request, user_language):
translation.activate(user_language)
request.session[translation.LANGUAGE_SESSION_KEY] = user_language
redirect_to = request.POST.get('next', request.GET.get('next', '/'))
resolved_url = resolve(redirect_to)
if resolved_url.kwargs:
return redirect(reverse(resolved_url.url_name, **resolved_url.kwargs))
else:
return redirect(reverse(resolved_url.redirect_to, *resolved_url.args))

django-nocaptcha-recaptcha always shows additional verification box

I installed django-nocaptcha-recaptcha and integrated it into my form:
from nocaptcha_recaptcha.fields import NoReCaptchaField
class ClientForm(forms.ModelForm):
captcha = NoReCaptchaField()
It shows up fine on the form, but whenever I click on it an additional dialog pops up asking to enter some text and verify. It happens every time. I tested it from another computer on another network and it still asks for additional verification after clicking the box.
This is what it looks like: additional verification dialog box
Here's how I'm handling the form:
#xframe_options_exempt
def registration(request):
if request.method == 'POST':
clientform = ClientForm(request.POST)
# check whether it's valid:
if clientform.is_valid():
new_client = clientform.save()
...
What am I doing wrong? Is it a problem with django-nocaptcha-recaptcha? Should I use something else?
P.S. I'm using django 1.7.1 with python 3.4
Another alternative: Minimalist and non framework dependant.
This is the code, in case you want to rewrite it.
'''
NO-CAPTCHA VERSION: 1.0
PYTHON VERSION: 3.x
'''
import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode
VERIFY_SERVER = "www.google.com"
class RecaptchaResponse(object):
def __init__(self, is_valid, error_code=None):
self.is_valid = is_valid
self.error_code = error_code
def __repr__(self):
return "Recaptcha response: %s %s" % (
self.is_valid, self.error_code)
def __str__(self):
return self.__repr__()
def displayhtml(site_key, language=''):
"""Gets the HTML to display for reCAPTCHA
site_key -- The site key
language -- The language code for the widget.
"""
return """<script src="https://www.google.com/recaptcha/api.js?hl=%(LanguageCode)s" async="async" defer="defer"></script>
<div class="g-recaptcha" data-sitekey="%(SiteKey)s"></div>
""" % {
'LanguageCode': language,
'SiteKey': site_key,
}
def submit(response,
secret_key,
remote_ip,
verify_server=VERIFY_SERVER):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
response -- The value of response from the form
secret_key -- your reCAPTCHA secret key
remote_ip -- the user's ip address
"""
if not(response and len(response)):
return RecaptchaResponse(is_valid=False, error_code='incorrect-captcha-sol')
def encode_if_necessary(s):
if isinstance(s, str):
return s.encode('utf-8')
return s
params = urlencode({
'secret': encode_if_necessary(secret_key),
'remoteip': encode_if_necessary(remote_ip),
'response': encode_if_necessary(response),
})
params = params.encode('utf-8')
request = Request(
url="https://%s/recaptcha/api/siteverify" % verify_server,
data=params,
headers={
"Content-type": "application/x-www-form-urlencoded",
"User-agent": "reCAPTCHA Python"
}
)
httpresp = urlopen(request)
return_values = json.loads(httpresp.read().decode('utf-8'))
httpresp.close()
return_code = return_values['success']
if return_code:
return RecaptchaResponse(is_valid=True)
else:
return RecaptchaResponse(is_valid=False, error_code=return_values['error-codes'])
Restart the server and don't forget to clear your browser's cache. Hope this helps.

Take language code from session in Django

I use i18n_patterns
What should I do so that http://localhost:8000 didn't redirect to url prefixed with language code?
In addition, I want to supply language, taken from session, not request.LANGUAGE_CODE
I found following code:
class NoPrefixLocaleRegexURLResolver(LocaleRegexURLResolver):
#property
def regex(self):
language_code = get_language()
if language_code not in self._regex_dict:
regex_compiled = (re.compile('' % language_code, re.UNICODE)
if language_code == settings.LANGUAGE_CODE
else re.compile('^%s/' % language_code, re.UNICODE))
self._regex_dict[language_code] = regex_compiled
return self._regex_dict[language_code]
However, there is problem with that code in checking if language_code == settings.LANGUAGE_CODE. If I enter http://localchost:8000, it will not redirect, but supply a page with translation from settings.LANGUAGE_CODE instead of request.session.get('django_language'). As I understood, I can't access request, so what should be done?

Issues with multiple languages

I want my app will be available in multiple languages (let say two,one is default english and one more).
And these both options available in my home page and there must be a link shown which makes user able to select his choice of language.
I am reading the Django official documentation for this
so any one can let me know the general idea how I can do that.
and one more thing......in settings.py there is default LANGUAGE_CODE = 'en-us' given,BUT as I want my app in more then one language so How i can specify that country code here.
like this works LANGUAGE_CODE = 'en-us','es-MX (Spanish)' or I have to do it in some way.
And what is the purpose of this .po extension in this.
settings.py
LANGUAGE_CODE='en_us'
gettext = lambda s: s
LANGUAGES = (
('en', gettext('English')),
('de', gettext('German')),
)
MIDDLEWARE_CLASSES = (
...
'lang.SessionBasedLocaleMiddleware',
)
lang.py
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils import translation
class SessionBasedLocaleMiddleware(object):
"""
This Middleware saves the desired content language in the user session.
The SessionMiddleware has to be activated.
"""
def process_request(self, request):
if request.method == 'GET' and 'lang' in request.GET:
language = request.GET['lang']
request.session['language'] = language
elif 'language' in request.session:
language = request.session['language']
else:
language = translation.get_language_from_request(request)
for lang in settings.LANGUAGES:
if lang[0] == language:
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
if 'Content-Language' not in response:
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
Access different languages http://example.com/?lang=de
And finaly let django create your .po files. Heres the documentation for that.
You want internationalization (or localization) of your software. With C it is often done thru gettext (which is related to .po files). Probably django uses these things.