django - Django Python 在 html 中显示函数
问题描述
模型.py
from django.db import models
class SomeModel(models.Model):
def show_something(self):
return "Foo Bar"
视图.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import SomeModel
def some_view(request):
instances = SomeModel.objects.all() # queryset
single_instance = instances.first() # single object
context = {
'object_list' : instances, # queryset
'object' : single_instance # single object
}
return render(request, 'your_template.html', context)
模板
{% load static %}
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
<link rel="icon" type="image/png" href="{% static 'img/logo.ico' %}" />
<link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="{% static "js/jquery-1.11.1.js" %}"></script>
<script src="{% static "js/rango-jquery.js" %}"></script>
<script type="text/javascript">
document.oncontextmenu = function(){return false;}
</script>
<style>
{% block style %}{% endblock style %}
</style>
</head>
<body bgcolor="" oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
<div id="bar"></div>
{% for item in object_list %} // accessing method through queryset
{{ item.show_something }}
{% endfor %}
{{ object.show_something }}
{% block content %}{% endblock %}
</body>
</html>
网址.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from page import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.some_view, name="index")
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
这就是现在的代码,但它没有在屏幕上显示任何内容,它说要在屏幕上返回“Foo Bar”,但它没有,我完成了迁移
我不知道是否足够解释自己,我希望你能帮助我,更新它以便你能看到更好的“地壳”
我想在我的 html 页面上显示该功能,它会如何
空间 空间 空间 空间 空间 空间 空间 空间 空间 空间 空间 空间
解决方案
如果您的方法在模型类中,请在 HttpResponse 中传递您的模型实例并使用 Ginga 调用该方法。
from django.template import Template, Context
context = Context({‘my_model’: model_instance})
template = Template(“The method show prints {{my_model.show()}}”)
template.render(context)
如果是在模型外定义的方法,
from django.template import Template, Context
from models import show
template = Template(“The method show prints {{show()}}”)
template.render()
推荐阅读
- django - 将原始 sql 表达为 Django 符号对象过滤器
- google-apps-script - 使用谷歌脚本将 HTML 电子邮件签名添加到 gsuite 中的所有外发电子邮件
- javascript - 为什么要更改我的轴(moment.js)的时间值?
- sql - 使用 Hive 从字符串中提取带图案的文本
- pentaho - 厨房出口问题:空过滤器真/假标签
- node.js - 在 GET 请求中发送查询参数的最佳实践?
- python - 使用 twitter api 使用 python 发送直接消息
- asp.net-core - Asp.net core 向用户标识多个角色
- boto3 - 调用 boto3.client() 时是否有开销?
- virtual-machine - USRP N210 在使用 GnuRadio 的虚拟机中溢出