如何在django html文件中返回简单的函数?

时间:2015-12-23 17:21:53

标签: python html django

我需要在html中返回calculate_c值

urls.py

from django.conf.urls import include, url
from . import views

urlpatterns = [
    url(r'^$', views.my_view, name='my_view'),

]

views.py

from django.shortcuts import render
from django.http import HttpResponse

def abc():
    a = 1
    b = 3
    calculate_c = a + b
    return calculate_c

def my_view(request):
    context = {'calculated_value': 0}
    context['calculated_value'] = abc()
    return HttpResponse(request, 'blog/post_list.html', context)

post_list.html

{% extends 'blog/base.html' %}

{% block content %}

<h2>{{calculated_value}}</h2>
<h2>Test</h2>

{% endblock %}

内部服务器错误:/ Traceback(最近一次调用最后一次):   在get_response中输入文件“/home/v1/newproject/newenv/lib/python3.4/site-packages/django/core/handlers/base.py”,第242行     response = self.apply_response_fixes(请求,响应)   在apply_response_fixes中输入文件“/home/v1/newproject/newenv/lib/python3.4/site-packages/django/core/handlers/base.py”,第305行     response = func(请求,响应)   在conditional_content_removal中输入文件“/home/v1/newproject/newenv/lib/python3.4/site-packages/django/http/utils.py”,第17行     如果100&lt; = response.status_code&lt; (204,304)中的200或response.status_code: TypeError:unorderable类型:int()&lt; = dict()

2 个答案:

答案 0 :(得分:1)

如果您需要模板中adc()返回的值,则可以通过context传递:

def my_view(request):

    ...
    context = {...}
    context['calculated_value'] = abc()
    return render(request, 'blog/post_list.html', context)

然后在您的模板中,您可以使用:

{{ calculated_value }}

答案 1 :(得分:0)

def abc():
  return (lambda a, b: a+b)

calculate_c = abc()
calculate_c(1,3)
4