Set language of PasswordResetForm in Django?

限于喜欢 提交于 2020-06-27 04:07:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!