【问题标题】:convert database object to string in django在 django 中将数据库对象转换为字符串
【发布时间】:2013-07-22 13:34:14
【问题描述】:

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    security_question = models.CharField('Question', max_length=255, null=True, blank=True)
    security_answer = models.CharField('Answer', max_length=255, null=True, blank=True)
    phone_daytime = models.CharField('Phone daytime', max_length=50, null=True, blank=True)
    phone_mobile = models.CharField('Phone mobile', max_length=50, null=True, blank=True)
    work_street = models.CharField('Street', max_length=255, null=True, blank=True)
    work_suburb = models.CharField('Suburb', max_length=200, null=True, blank=True)
    work_state = models.CharField('State', max_length=100, null=True, blank=True)
    work_postcode = models.CharField('Postcode', max_length=20, null=True, blank=True)
    work_country = models.CharField('Country', max_length=200, null=True, blank=True)

views.py

def method(request):
    ''''
    profile = UserProfile.objects.get(user=user)
    '''''
    return render(request,'index.html',{'profile':profile})

如何将数据库字段的work_street、work_suburb、work_state、work_postcode、work_country转换成字符串并在模板中渲染。

【问题讨论】:

  • 您不必这样做。 {{ profile.work_street }} 将在您的模板中完美呈现。
  • @limelights 我提到的第 4 个字段是工作地点的地址,我想将其作为字符串在 javascript 中传递以将标记固定在位置上,这样我就可以这样做来提及地址 var address = “{{ profile.work_street }}{{profile.work_suburb}}{{profile.work_postcode}}”;如果不是,这是正确的方法吗,请纠正我如何做到这一点。

标签: python django django-models django-templates


【解决方案1】:

您可以像这样创建 index.html 以将其呈现为 html

index.html

<body>
<p>{{ profile.user.username }}</p>
<p>{{ profile.security_question }}</p>
<p>{{ profile.work_street}}</p>
<p>{{ profile.work_suburb}}</p>
<p>{{ profile.work_state}}</p>
<p>{{ profile.work_postcode}}</p>
<p>{{ profile.work_country }}</p>
..... etc

<script>
 var address = "{{ profile.work_street }}{{profile.work_suburb}}{{profile.work_postcode}}";
 alert(address);
</script>
</body>

【讨论】:

  • 想要在 javascript 中将其作为字符串传递以将标记固定在位置上,因此我可以这样做以提及地址 var address = "{{ profile.work_street }}{{profile.work_suburb}}{{ profile.work_postcode}}";如果不正确,请纠正我。
  • @Royal 是的,您绝对可以这样做。这是正确的方法。当页面加载时,字符串将存储在address
猜你喜欢
  • 2019-03-05
  • 1970-01-01
  • 2023-04-01
  • 2014-01-14
  • 2011-08-02
  • 2016-06-10
相关资源
最近更新 更多