从视图发送变量到模板django

时间:2014-02-27 17:51:34

标签: django django-templates django-views

def total_rent(request):
    context = RequestContext(request)
    venues = Venue.objects.all()
    decorations = Decoration.objects.all()
    context1 = ({'venues': venues, 'decorations': decorations})
    if request.method == 'GET':
        rent1 = request.GET.get('venue')
        rate1 = request.GET.get('decor')
        if rent1 and rate1:
            total = int(rent1)+int(rate1)
            return render_to_response("test.html", context1, {'total':total})
        else:
            return render_to_response("test.html", context1)

    return render_to_response("test.html", context1, context)

尝试将总回传给template.html,但得到错误“pop期望至少有1个参数,得到0”

template.html

<form action="" method="get">
{% for venue in venues %}
<input type="radio" name= "venue" id="venue{{ forloop.counter }}" value="{{venue.rent }}"/>
<label for="venue{{ forloop.counter }}">{{  venue.venue_Name}}</label><br />
<img src="{{  venue.picture.url }}" alt="" width="200">
{% endfor %}
{% for decoration in decorations %}
<input type="radio" name="decor"id="decor{{ forloop.counter }}" value="{{ decoration.rate }}" />
<label for="decor{{ forloop.counter }}">{{  decoration.rating }}</label><br />
{% endfor %}
<input type="submit" value="service" />
{% if total %}
    <p>Total cost for venue and decoration: {{ total }}</p>
{% endif %}
</form>

1 个答案:

答案 0 :(得分:0)

保持上下文和context1一致。试试这个:

def total_rent(request):
    context = RequestContext(request)
    venues = Venue.objects.all()
    decorations = Decoration.objects.all()
    context1 = ({'venues': venues, 'decorations': decorations})

    if request.method == 'GET':
        rent1 = request.GET.get('venue')
        rate1 = request.GET.get('decor')
        if rent1 and rate1:
            total = int(rent1)+int(rate1)
            context1.update({'total': total})
            return render_to_response("test.html", context1, context)
        else:
            return render_to_response("test.html", context1, context)

    return render_to_response("test.html", context1, context)

或者只是:

def total_rent(request):
    context = RequestContext(request)
    venues = Venue.objects.all()
    decorations = Decoration.objects.all()
    context1 = ({'venues': venues, 'decorations': decorations})

    rent1 = request.GET.get('venue')
    rate1 = request.GET.get('decor')
    if rent1 and rate1:
        total = int(rent1)+int(rate1)
        context1.update({'total': total})

    return render_to_response("test.html", context1, context)

请注意,request.method默认为GET