Opened 3 years ago
Closed 3 years ago
#32922 closed New feature (wontfix)
Adding "preferred_language" property to "HttpRequest" object
Reported by: | Ruslan Semagin | Owned by: | nobody |
---|---|---|---|
Component: | HTTP handling | Version: | 3.2 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
Sometimes it is useful to get the client's preferred language from the request and then pass it somewhere, for example, apply a filter to fetch data.
Therefore, it is useful to access this property in the object.
@property def preferred_language(self): """Returns the client's language in order of priority from the "Accept-Language" header""" languages = [_.strip() for _ in self.headers.get('Accept-Language', '*').split(',')] return languages[0].split(';')[0]
Change History (2)
comment:1 by , 3 years ago
Description: | modified (diff) |
---|
comment:2 by , 3 years ago
Resolution: | → wontfix |
---|---|
Status: | new → closed |
Note:
See TracTickets
for help on using tickets.
So unfortunately this is not as simple as what you have proposed for a number of reasons:
q
value for the priority of entries in the header should be taken into account as mentioned by Keryn.*
value shouldn't be returned as it isn't a valid language.Accept-Language
may not be the user's "preferred" language. It is just the languages that the client is configured to accept.See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language for more details.
The good news is that Django has already implemented this and taken everything into consideration. Check out get_language_from_request().
Obviously this restricts the returned languages to those that are available in
settings.LANGUAGES
.If you really need to have the "preferred" and unadulterated value from the
Accept-Language
header, you could use theparse_accept_lang_header()
function, but beware that this is an undocumented, private function.