【发布时间】: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