运行Django应用程序时遇到“解析变量'redirect_to'时出现异常”

时间:2019-10-04 15:24:34

标签: django python-3.x nginx gunicorn ubuntu-18.04

我做了一个带有本地化的简单应用程序(Django 2.2.4)。我建立了一种更改语言的方法,并在https://docs.djangoproject.com/en/2.2/topics/i18n/translation/中使用了确切的代码 当我使用

在本地运行时
python manage.py runserver 

它工作正常,但是当我在其他ubuntu服务器上通过nginx和gunicorn运行它时,我会得到

Exception while resolving variable 'redirect_to' in template 'home/index.html'.
Traceback (most recent call last):
  File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
    current = current[bit]
  File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__
    raise KeyError(key)
KeyError: 'redirect_to'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup
    if isinstance(current, BaseContext) and getattr(type(current), bit):
AttributeError: type object 'RequestContext' has no attribute 'redirect_to'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
    current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'redirect_to'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/administrator/environments/website/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
    (bit, current))  # missing attribute
django.template.base.VariableDoesNotExist: <unprintable VariableDoesNotExist object>

存在python版本差异,但升级到相同的python(python3.7)相同版本后,会发生相同错误。

引发异常的代码

{% load i18n %}

<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}">
    <select name="language">
        {% get_current_language as LANGUAGE_CODE %}
        {% get_available_languages as LANGUAGES %}
        {% get_language_info_list for LANGUAGES as languages %}
        {% for language in languages %}
            <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
                {{ language.name_local }} ({{ language.code }})
            </option>
        {% endfor %}
    </select>
    <input type="submit" value="Go">
</form>

我只是希望django能够识别redirect_to变量,因为它可以完美地在我的开发服务器(python manage.py runserver)本地工作,我使用本指南https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04设置了生产服务器

编辑:这是视图(非常简单)

class HomeView(TemplateView):
    template_name = 'home/index.html'

    def get(self, request):
        sections = Section.objects.all()
        return render(request, self.template_name, {'sections': sections })

1 个答案:

答案 0 :(得分:0)

您可以在这里找到您的解决方案: https://dev.to/levivm/django-app-internationalization-lj9

我解决了以下问题:

请记住,您必须被添加

'django.middleware.locale.LocaleMiddleware',

在MIDDLEWARE中是

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
   'django.middleware.locale.LocaleMiddleware',

]

还必须添加语言列表

_ = lambda s: s
LANGUAGES = (
    ('en', _('English')),
    ('ar', _('Arabic')),  

)

在url.py中,您的行为必须是这样的:

from django.conf.urls.i18n import i18n_patterns 
urlpatterns = [
url('admin/', admin.site.urls),
                path('', include('document_control.urls')),
            ] + static(settings.STATIC_ROOT
                        ,document_root=settings.MEDIA_ROOT)

urlpatterns += i18n_patterns( 
#url('admin/', admin.site.urls), 

url('', include('document_control.urls')), 

prefix_default_language=True, ) + static(settings.STATIC_ROOT
        ,document_root=settings.MEDIA_ROOT) #for active static files

在模板中,您的代码必须是这样

{% load i18n %}
<ul class="nav navbar-nav navbar-right language menu">
    {% get_current_language as LANGUAGE_CODE %}
    {% get_available_languages as LANGUAGES %}
    {% get_language_info_list for LANGUAGES as languages %}
    {% for language in languages %}
        <li>
            <a href="/{{ language.code }}{{ request.get_full_path|slice:'3:' }}"
               class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}"
               lang="{{ language.code }}">
                {{ language.name_local }}
            </a>
        </li>
    {% endfor %}
</ul>    




{% if   LANGUAGE_CODE  == "ar" %}
your code by arabic language
{% else %}
you code by english language


{% endif %}

我希望它将对您有用