如何在django中通过视图设置变量

时间:2014-09-26 10:28:51

标签: python django django-templates

如何在视图中设置任何变量,以便其值i将进入模板

home.html的

<html>
<head>
    <title>To-Do lists</title>
</head>
<body>
    <h1>Your To-Do list</h1>
    <form method="POST">
    <input id="id_new_item" name="item_text" placeholder="Enter a To-Do item"/>
    {% csrf_token %}
    </form>
    <table id="id_list_table">
        <tr><td>1 : {{new_item_text}}</td></tr>
    </table>
</body>

views.py

from django.shortcuts import render
from django.http import HttpResponse
from lists.models import Item

def home_page(request):
    if request.method == 'POST':
        new_item_text = request.POST['item_text'] #
        print new_item_text;
        Item.objects.create(text=new_item_text) #
    else:
        new_item_text = '' #
    item = Item()
    item.text = request.POST.get('item_text', 'A new list item')
    item.save()
    return render(request, 'home.html', {
        'new_item_text': new_item_text
    })

MODELS.PY

from django.db import models

class Item(models.Model):
    text = models.TextField(default='')

这是失败的测试 test.py

def test_home_page_returns_correct_html(self):
    request = HttpRequest() #
    response = home_page(request) #
    self.assertIn('A new list item', response.content.decode())
    expected_html = render_to_string('home.html',
        {'new_item_text': 'A new list item'}
    )
    self.assertEqual(response.content.decode(), expected_html)

错误是

AssertionError: 'A new list item' not found in u'<html>\n\t<head>\n\t\t<title>To-Do lists</title>\n\t</head>\n\t<body>\n\t\t<h1>Your To-Do list</h1>\n\t\t<form method="POST">\n\t\t<input id="id_new_item" name="item_text" placeholder="Enter a To-Do item"/>\n\t\t\n\t\t</form>\n\t\t<table id="id_list_table">\n\t\t\t<tr><td>1 : </td></tr>\n\t\t</table>\n\t</body>\n</html>\n'

请告诉我我提出的问题的解决方案或任何材料(任何链接)

2 个答案:

答案 0 :(得分:0)

使用一些上下文数据呈现模板,这是您可以传递变量的地方。对于基于类的视图,Imran建议您可以从

返回上下文

get_context_data method

在函数视图中,您可以将上下文传递给渲染快捷方式

return render(request, 'my-template.html', {"variable1": True, "variable3": foo})

答案 1 :(得分:-1)

你应该使用基于类的视图

class HomeView(TemplateView):
template_name = 'home.html'

def get_context_data(self, **kwargs):
    context = super(HomeView, self).get_context_data(**kwargs)
    context['user']= self.request.user.username
    return context

在视图中,您只需访问用户

即可
{{user}}