2017-10-16 42 views
0

我正在django中开发一个应用程序,并在多个国家/地区提供支持。在网站上应根据所在的子域显示国旗,但我找不到通过django视图发送必要的国旗图像的方法。通过django视图上的字典更改图像

这是我的views.py

def index(request): 
    subdomain = request.META['HTTP_HOST'].split('.')[0] 
    if subdomain == 'www': 
     dic.update({"countryflag": ''}) 
    elif subdomain == 'mx': 
     dic.update({"countryflag": '<img src="{% static "images/mxflag.png" %}" alt="img">'}) 
    elif subdomain == 'nz': 
     dic.update({"countryflag": '<img src="{% static "images/nzflag.png" %}" alt="img">'}) 
    return render(request, 'mysite/index.html', dic) 

的例子,我想recive变量 “countryflag” 在我basetemplate.html

<div id="cp_side-menu-btn" class="cp_side-menu"> 
    {{ countryflag }} 
</div> 

这不作品。我想将整个图像传递给countryflag键。有没有办法做到这一点,或者我必须在basetemplate.html中创建'if'?

+0

什么是输出这段代码? –

回答

1

您正在尝试更新“dic”而无需在index()中进行初始化。 如果您声明的三种情况都不正确,则还要添加一个else语句。

1

请首先创建一个DIC,然后为模板,我想这应该工作

{{ countryflag|safe }} 
0

这个回答假设的几件事情。

  1. 你有你的STATIC_URL = '/静态/' settings.py中配置
  2. 的Django项目,您的目录结构是 '理想'

目录设置:

djangoproject 
--djangoproject 
----__init__.py 
----settings.py 
----urls.py 
----wsgi.py 
--myapp 
----migrations 
------__init__.py 
----admin.py 
----apps.py 
----models.py 
----tests.py 
----views.py 
--static 
----css 
------main.cs 
----js 
------main.js 
--manage.py 

djangoproject/djangoproejct/urls.py:

from django.conf.urls import url, include # Add include to the imports here 
from django.contrib import admin 

urlpatterns = [ 
    url(r'^admin/', admin.site.urls), 
    url(r'^', include('myapp.urls')) 
] 

djangoproject/MYAPP/urls.py

from django.conf.urls import url 
from myapp import views 

urlpatterns = [ 
    url(r'^$', views.index, name='index'), 
] 

然后,您应该设置您的myapp结构,例如:

--myapp 
----migrations 
------__init__.py 
----templates 
------index.html 
----admin.py 
----apps.py 
----models.py 
----tests.py 
----urls.py 
----views.py 

你views.py

def index(self, request, **kwargs): 
     subdomain = request.META['HTTP_HOST'].split('.')[0] 
     if subdomain == 'www': 
      context = {'data' : [ {'countryflag': ''}]} 
     elif subdomain == 'mx': 
      context = { 'data' : [ { 'countryflag' : '<img src="{% static "images/mxflag.png" %}" alt="img">'}] } 
     elif subdomain == 'nz': 
      context = { 'data' : [ { 'countryflag' : '<img src="{% static "images/nzflag.png" %}" alt="img">'}] } 
     else: 
      context = {'data' : [ {'countryflag': ''}]} 
     return render(request, 'index.html', context) 

的index.html

<div id="cp_side-menu-btn" class="cp_side-menu"> 
    {% for i in data %} 
    {{i.countryflag}} 
    {% endfor %} 

</div> 
+0

2016年,Amos Omondi从[本教程](https://scotch.io/tutorials/working-with-django-templates-static-files)为您的用例修改了此方法。 – noes1s