2017-10-16 45 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