【问题标题】:Django Python Show functions in htmlDjango Python 在 html 中显示函数
【发布时间】:2019-08-11 22:04:18
【问题描述】:

models.py

from django.db import models

class SomeModel(models.Model):
    def show_something(self):
        return "Foo Bar"

views.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>

urls.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”,但它没有,我完成了迁移

我不知道是否足够解释自己,我希望你能帮助我,更新它以便你能看到更好的“ruddra”

我想在我的 html 页面上显示该功能,希望它如何

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

【问题讨论】:

  • 你能更具体地谈谈这个问题吗?你的意思是要从模板调用函数?
  • 是的,从html模板调用
  • 您可以为此任务使用模板过滤器。

标签: django python-3.x django-models django-rest-framework django-templates


【解决方案1】:

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

【讨论】:

  • 我把那个放在哪里了?
  • 把它放在views.py中,在你用来渲染你的模板的方法中。
【解决方案2】:

您可以按照@Kshitij 的建议从视图中调用它,也可以创建自定义模板过滤器来调用该方法。这是writing custom template filters 的文档。

在您的情况下,您可以创建一个自定义模板过滤器:

@register.filter
def call_method(obj):
    return obj.show

然后在您的模板中,您可以将过滤器用作:

{{ obj|call_method }}

其中 obj 是定义方法的指定模型的对象。

确保在模型内部定义了方法。使用模板过滤器可以更轻松地调用需要一些参数的方法。

如果您的方法接受以下参数:

class MyModel(models.Model):
    ...
    def some_function(self, var):
        return var

然后您可以使用以下方法轻松创建模板过滤器:

@register.filter
def get_method(obj, v):
    return obj.some_function(v)

然后在你的模板中:

{{ obj|get_method:'your parameter' }}

【讨论】:

  • 过滤器放在哪里?
  • 正如我在回答中提供的文档,它说您需要在应用程序目录(应用程序的模型、视图和模板所在的位置)中创建一个名为 templatetags 的文件夹。看看:docs.djangoproject.com/en/1.8/howto/custom-template-tags/… 以便更好地理解
【解决方案3】:

比方说,你有一个这样的模型:

# models.py

from django.db import models


class SomeModel(models.Model):
    # some fields

    def show_something(self):
        return "Foo Bar"

现在,当您拥有模型类的对象方法时,您需要通过模型实例来访问它。并且该实例/实例需要从视图发送到模板。像这样(我将发送单个模型实例和queryset 到模板):

# views.py

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)

最后在模板中,你可以像这样访问方法:

// your_template.html

{% for item in object_list %}  // accessing method through queryset
     {{ item.show_something }}
{% endfor %}


{{ object.show_something }}  // accessing method form a single object

【讨论】:

  • 我明白了; NameError at / name 'SomeModel' is not defined 我试着把它放在'urls'路径('',views.some_view,name="index")
  • 在此处标记:instances = SomeModel.objects.all() # queryset
  • @Alien69 在你的问题中,你说你在模型中有一个方法。这就是为什么我放了一个示例模型。你应该用你自己的模型和方法替换它。
  • 是的,但是,我想试试这个
  • @Alien69 在这种情况下,请确保将SomeModel 写入models.py,然后将其导入views.py。我还更新了我的答案以使事情更清楚。
猜你喜欢
  • 2016-08-24
  • 2015-04-15
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 2015-07-31
  • 2021-06-24
  • 2010-10-28
  • 1970-01-01
相关资源
最近更新 更多