我尝试编写一个mixin,用于根据用户个人资料模型中设置的语言设置翻译语言。 当get请求进入时,mixin应该将语言设置为用户语言,从添加mixin的视图中获取响应,然后将语言设置回原来的语言。我编写了以下mixin,它被调用,但是它的get方法没有被调用。我究竟做错了什么?
class SetUserLanguageMixin(object):
def get(self, request):
current_language = translation.get_language()
try:
translation.activate(request.user.profile.language)
response = super(SetUserLanguageMixin, self).get(request)
finally:
translation.activate(current_language)
return response
class SomeView(LoggingMixin, APIView, SetUserLanguageMixin):
def get(self, request):
...
return Response(data, status=status.HTTP_200_OK)
答案 0 :(得分:0)
如果您的SomeView
覆盖get()
,则除非您致电get()
,否则不会调用mixin的super()
方法。您可以尝试在mixin中覆盖dispatch
。
请注意,如果重写的get / dispatch方法接受args和kwargs,您的视图将更加健壮:
def dispatch(self, request, *args, **kwargs):
...
response = super(SetUserLanguageMixin, self).dispatch(request, *args, **kwargs)
...