首页 > 解决方案 > 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 页面上显示该功能,它会如何

空间 空间 空间 空间 空间 空间 空间 空间 空间 空间 空间 空间

标签: djangopython-3.xdjango-modelsdjango-rest-frameworkdjango-templates

解决方案


如果您的方法在模型类中,请在 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()

推荐阅读