问题
I am manually resetting passwords but wonder how to set the language to the user's language instead of my own. I see there are many extra context fields but which one needs to be set?
for user in qs:
reset_form = PasswordResetForm({'email': user.email})
# reset_form.language?
assert reset_form.is_valid()
reset_form.save(request=request)
I have added a field CustomUser.language
which would be available in user.language
above.
(While phrasing my question and looking for possibilities I found a working solution.)
回答1:
I came to the following solution, by setting the current language (session-wise) temporarily to the user's language:
from django.utils import translation
temp_language = translation.get_language_from_request(request)
for user in qs:
translation.activate(user.language)
request.LANGUAGE_CODE = translation.get_language()
reset_form = PasswordResetForm({'email': user.email})
assert reset_form.is_valid()
reset_form.save(request=request)
# https://stackoverflow.com/questions/2336785/set-language-within-a-django-view/2336889#comment12481631_2336889
translation.deactivate()
translation.activate(temp_language)
request.LANGUAGE_CODE = translation.get_language()
来源:https://stackoverflow.com/questions/62123897/set-language-of-passwordresetform-in-django