2010-08-04 81 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