2010-08-04 117 views
1

如果我想給一個變量%S插入此Django的字符串格式

<p><img src= %s alt="tetris"/></p> 

我,如果我用"%s",它不會將其識別爲placholder這是問題。 但如果只是使用%s它不會鏈接到我的形象。

有沒有辦法解決這個問題? 我試圖在數據庫''/url/''中插入像這樣插入的url。 但是,這也不會做伎倆。 有什麼建議嗎?

@thomas:

from django.http import HttpResponse 
from django.contrib.auth.models import User 
from favorites.models import * 

def main_page_favorites(request): 
    title = Favorite.objects.get(id=1).title.upper() 
    email = User.objects.get(username='Me').email 
    image = Hyperlink.objects.get(id=3).url 
    output = ''' 
     <html> 
      <head> 
       <title> 
        Connecting to the model 
       </title> 
      </head> 
      <body> 
       <h1> 
       Connecting to the model 
       </h1> 
       We will use this model to connect to the model! 

       <p>Here is the title of the first favorite: %s</p> 
           <p>Here is your email: %s </p> 
           <p>Here is the url: %s </p> 
           <p>Here is the url embedded in an image: <p><img src= %s alt="tetris"/></p> 

      </body> 
     </html>''' % ( 
      title, email, image, image 
     ) 
    return HttpResponse(output) 
+0

你可以舉例代碼? ''

tetris

'%「foo.jpg」'很好。 – 2010-08-04 10:07:57

+0

對不起。忘了說我從數據庫中檢索這個變量。 所以%s被圖像替換。 而圖像的肺癌這樣的: 圖像= Hyperlink.objects.get(ID = 3).URL – MacPython 2010-08-04 10:38:28

+1

仍然不應該有任何問題。你能從你的腳本粘貼確切的代碼嗎? – 2010-08-04 10:44:54

回答

1

也許你應該考慮附帶Django的模板。他們使代碼更容易維護。

from django.shortcuts import render_to_response 
from django.template import RequestContext 

def view(request): 
    user = request.user 
    return render_to_response('template.html', { 
     'user':user, 
    }, context_instance=RequestContext(request) 

,然後在template.html文件在您templates目錄:

<html> 
    <!-- snip --> 
    <body> 
    Here is your email: {{ user.email }} 
    </body> 
</html> 

獎勵:你的文本編輯器可能會突出你的HTML語法。

+0

謝謝!我知道模板系統。但是因爲我正在學習如何寫入數據庫,所以最好從基礎入手。 – MacPython 2010-08-04 13:03:35