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

loading...


-1

我需要在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(最近一次调用最后一次):文件“/home/v1/newproject/newenv/lib/python3.4/site-packages/django/core/handlers/base.py”,第242行,在get_response中response = self.apply_response_fixes(request,response)文件“/home/v1/newproject/newenv/lib/python3.4/site-packages/django/core/handlers/base.py”,第305行,在apply_response_fixes response = func (请求,响应)文件“/home/v1/newproject/newenv/lib/python3.4/site-packages/django/http/utils.py”,第17行,在conditional_content_removal中,如果100 <= response.status_code <200或response.status_code in(204,304):TypeError:unorderable types:int()<= dict()

2回答

  • 1

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

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

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

    {{ calculated_value }}
    

  • 0
    def abc():
      return (lambda a, b: a+b)
    
    calculate_c = abc()
    calculate_c(1,3)
    4
    

loading...

评论

暂时没有评论!