Django- 从通用CBV发送的数据更新?(刷新视图的变量)

2024-10-01 07:50:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力做到以下几点:

class PurchaseCreate(CreateView):
    template_name = "generic_create.html"
    model = Purchase
    form_class = PurchaseForm
    try:
        latest_tag = Purchase.objects.latest('tag').tag
        print(latest_tag)
        next_tag = latest_tag + 1
    except:
        next_tag = 1
    initial = {'tag': next_tag}

“tag”字段应以输入的上一个值的+1开始。当我在djangoapi中测试它时,它工作得很好。但是,当从视图中调用时,它在第一次正常工作,但似乎会“卡住”返回第一个值,即使创建了应该更新该值的新对象

事实上,try/except部分在第一页加载之后从未执行,因为打印顺序从未在终端中显示,即使在浏览器硬刷新的情况下也是如此。如何设置此视图以在每次加载页面时发送更新的结果


Tags: name视图htmltagcreatetemplatepurchaselatest
1条回答
网友
1楼 · 发布于 2024-10-01 07:50:48

如前所述,我将逻辑移到get_initial()方法中,如下所示:

def get_initial(self):
    super(PurchaseCreate, self).get_initial()
    try:
        latest_tag = Purchase.objects.latest('tag').tag
        print(latest_tag)
        next_tag = latest_tag + 1
    except:
        next_tag = 1
    initial = {'tag': next_tag}
    return initial

相关问题 更多 >