【发布时间】:2019-02-02 06:32:19
【问题描述】:
每个人。我从 Python 和 Django 开始,我想在我的代码中添加一些 Ajax。
我正在通过在模板上显示产品以及更改其价格的输入来练习。 我已经能够更改他在数据库上的值,但之后我想更新模板的上下文以查看新值。我要更新的字段是表格的最后一行。
{% csrf_token %}
<table>
<tr>
<th>Product</th>
<td>{{product.name}}</td>
</tr>
<tr>
<th>Price</th>
<td><input id="price" type="text" value="{{product.price}}" placeholder="Price" autocomplete="off"/></td>
</tr>
<tr>
<td colspan="2" style='background:none'><input id="send" type="button" value="Update"/></td>
</tr>
<tr>
<th>Current values:</th>
<td>{{product.name}} : ${{product.price}}</td>
</tr>
</table>
JS:
$("#send").click(function(){
$.post("/inicio/acciones/update/", {search: 1, price : $("#price").val()} ).done(function(res){
})
});
后台
def update(request):
"""backend changes
...
"""
t = loader.get_template('inicio/index.html')
product= Product.objects.get(pk=search)
context = {
'product' : product,
}
t.render(context)
return HttpResponse(product.price)
“产品”变量具有正确的值,但我的模板未更新。
如何更新上下文?
【问题讨论】:
-
欢迎来到 Stack Overflow。你能澄清你的问题吗?如果
product具有您想要的属性,是什么阻止您在模板中使用它们? -
你的 Ajax
done函数的其余部分在哪里? -
Daniel,done 函数什么都不做。我希望可以仅使用更新功能来更新模板。
-
谢谢,@Chris。好吧,模板已经加载,我正在寻找的是在整个上下文中发送产品。模板首先加载了一个产品变量。这可能吗?
-
页面会自动更新如果你没有使用Ajax。使用 Ajax 的全部意义在于防止这种情况发生,以便您可以在 JS 本身中以编程方式更新事物。既然您不想那样做,那么您究竟为什么要使用 Ajax?只是不要。
标签: python django templates render