我正在使用 django-hvad 进行模型翻译,并不是所有的模型都会有翻译。我希望默认为en-us
.
如果针对特定语言提出请求,并且模型具有可用的翻译,则响应应该使用该语言。如果翻译不可用,我想en-us
被退回。
现在发生的事情是我收到错误 500: 'HttpResponse' object has no attribute '_meta'
。当翻译不可用和语言代码未在LANGUAGES
.
例如,当我提出以下请求时,我得到了状态为 200 的正确响应en-us
:
GET http://localhost:5000/survey/surveys/2/?language=en-us
如果我提出请求,en-US
我会收到 500 错误(注意大写从en-us
到的变化en-US
):
GET http://localhost:5000/survey/surveys/2/?language=en-US
请求定义LANGUAGES
但没有翻译的语言时,我收到相同的 500 错误:
GET http://localhost:5000/survey/surveys/2/?language=af
这是我的 settings.py 文件的语言部分:
设置.py
from django.utils.translation import ugettext_lazy as _
...
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
('en-us', _('English')),
('af', _('Afrikaans')),
('ar', _('Arabic')),
...
]
如果您想知道如何处理此请求,请查看该 URL 的视图:
视图.py
class SurveyDetail(APIView):
def get_object(self, pk):
try:
user_language = self.request.GET.get('language')
return models.Survey.objects.language(user_language).get(pk=pk)
except models.Survey.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
def get_related_questions(self, pk):
try:
user_language = self.request.GET.get('language')
return models.SurveyQuestion.objects.language(user_language).all().filter(survey=pk)
except models.SurveyAnswer.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
def get_related_answers(self, pk):
try:
user_language = self.request.GET.get('language')
return models.SurveyAnswer.objects.language(user_language).all().filter(question=pk)
except models.SurveyAnswer.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
def get(self, request, pk, format=None):
survey = self.get_object(pk)
questions = self.get_related_questions(pk)
questions_serialized = []
for q in questions:
questions_serialized.append(SurveyQuestionSerializer(q).data)
questions_serialized[-1]['answers'] = SurveyAnswerSerializer(self.get_related_answers(q.pk), many=True).data
resp_obj = SurveySerializer(survey).data
resp_obj['questions'] = questions_serialized
return JSONResponse(resp_obj)