2017-06-03 117 views
0

嘿家伙我的文件组织如下。如何将多个变量传递给我的模板在Django中?

urls.py:

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


urlpatterns = [ 
    url(r'^$', views.index, name='index'), 
    url(r'^contact/', views.eurusd, name='eur'), 
    url(r'^contact/', views.VaR, name='lol'), 


] 

views.py:

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

from yahoo_finance import Currency 

def eurusd (request): 
    eur_usd = Currency('EURUSD') 
    eur = ('EUR/USD Bid/Ask Price: ' +eur_usd.get_bid() +'/ '+eur_usd.get_ask()) 
    return render(request, 'personal/basic.html', {'eur': eur}) 

def VaR (request): 
    hallo = "this is a python sting" 
    return render(request, 'personal/basic.html', {'lol': hallo}) 

basic.html

{% extends "personal/header.html" %} 

{% block content %} 
<p>{{eur}}</p> 
<p>{{lol}}</p> 
{% endblock %} 

我现在的问题是:为什么 只能从欧元字典中的字符串在我的名为basic.html的模板中返回,而不是大声笑? 我怎样才能将多个变量传递给我的basic.html?

回答

0

你只需要一个URL模式,并在您的视图中的一个功能,你的代码更改为:

urls.py:

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


urlpatterns = [ 
    url(r'^$', views.index, name='index'), 
    url(r'^contact/', views.eurusd, name='eur'), 
] 

views.py:

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

from yahoo_finance import Currency 

def eurusd(request): 
    eur_usd = Currency('EURUSD') 
    eur = ('EUR/USD Bid/Ask Price: ' +eur_usd.get_bid() +'/ '+eur_usd.get_ask()) 
    hallo = "this is a python sting" 
    return render(request, 'personal/basic.html', {'eur': eur,'lol': hallo}) 
0

你不需要两个函数,因为你想用两个变量渲染模板,所以最简单的方法是编写一个函数,在上下文中返回两个wariables。一些这样的:

urls.py

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


urlpatterns = [ 
    url(r'^$', views.index, name='index'), 
    url(r'^contact/', views.eurusd, name='eur'), 
] 

views.py

eur_usd = Currency('EURUSD') 
    eur = ('EUR/USD Bid/Ask Price: ' +eur_usd.get_bid() +'/ '+eur_usd.get_ask()) 
hallo = 'This is the python string' 
    return render(request, 'personal/basic.html', {'eur': eur, 'hallo' : hallo}) 

有了这个代码,您tamplate将正常工作

在你的情况的Django的时候尽量找网址,找到看起来像您的网址的第一个网址,然后他们请求仅第一个功能。

相关问题