Default language via settings not respected during testing

前端 未结 2 1931
抹茶落季
抹茶落季 2021-01-18 11:25

Using Django 1.3, Python 2.6

Having a particularly weird problem to track down related to internationalization, and RequestFactory vs. TestClient for testing views

相关标签:
2条回答
  • 2021-01-18 11:46

    However if that same view is simply called with the result of RequestFactory's get or put methods, it will throw the error above.

    I imagine you are doing something like:

    from django.utils import translation
    from app.views import some_view
    
    # Using translation.activate is pretty well known, so I suppose you
    # also do this:
    translation.activate(<whatever language you want>)
    
    request_factory = RequestFactory()
    request = request_factory.get("/foo")
    
    response = some_view(request)
    

    Then the URLs produced by the request have None instead of the language you wanted. You can try using a URL with a language prefix. You can try setting a language cookie in your request. You can try fiddling with the session. Nothing works.

    The reason is does not work is because you are bypassing the entire middleware machinery. You are calling the view directly. Django won't intervene, take the request and pass it through the middlewares.

    What you can do is call whatever middleware you need, or you can replicate what the middleware does. In order to get a request produced with RequestFactory to honor the language settings, I chose the latter and I did this:

    translation.activate("en-us")
    request.LANGUAGE_CODE = "en-us"
    response = some_view(request)
    

    This was enough for me to get the language prefix added to my URLs.

    0 讨论(0)
  • 2021-01-18 12:06

    There are 2 possibilities :

    a) You have 'django.middleware.locale.LocaleMiddleware' in settings.MIDDLEWARE_CLASSES.

    In this case, the client use settings.LANGUAGE_CODE.

    b) You don't.

    In that case, you should set the language like that somewhere in your tests.py module:

    from django.utils.translation import activate
    ...
    activate('fr-fr')
    

    https://code.djangoproject.com/ticket/15143

    0 讨论(0)
提交回复
热议问题