2017-10-16 5 views
0

저는 여러 국가에서 지원되는 django에서 응용 프로그램을 개발 중입니다. 사이트에서 해당 하위 도메인에 따라 국가 플래그가 나타나야하지만 장고보기를 통해 필요한 플래그 이미지를 보낼 수있는 방법을 찾을 수 없습니다. 장고보기에서 사전을 통해 이미지 변경

내가 내 basetemplate.html

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

이 작동하지 않습니다에서 변수 "countryflag을"받아 봐하려는 내 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) 

의 예입니다. 전체 이미지를 countryflag 키로 전달하고 싶습니다. 이 작업을 수행 할 수있는 방법이 있습니까 아니면 basetemplate.html에 'if'를 작성해야합니까?

+0

출력이란 무엇입니까? 이 코드의? –

답변

1

"dic"을 index()에서 초기화하지 않고 업데이트하려고합니다. 선언 한 세 상황 중 하나라도 true가 아닌 경우를 대비하여 else 문을 추가하십시오.

1

먼저 DIC를 만드십시오 다음 템플릿, 나는이

{{ countryflag|safe }} 
0

이 대답은 몇 가지 가정 작동합니다 가정합니다.

  1. 당신은 당신의 STATIC_URL이는 = '/ 정적 /'settings.py 구성
  2. 장고 프로젝트에 대한
  3. 당신의 디렉토리 구조는 '이상적'인

디렉토리 설정 :

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