gpt4 book ai didi

python - Django 更新数据库中的对象

转载 作者:行者123 更新时间:2023-12-01 05:12:11 47 4
gpt4 key购买 nike

我正在尝试运行一个简单的更新表单,该表单应该更新从表单提交的数据库中的所有对象值。

这是我的更新 View ,除了重定向到“/”之外什么也不做。没有错误,但也没有更新。

def update(request, business_id):
if request.method == 'POST':
form = BusinessForm(request.POST)

if form.is_valid():
t = Business.objects.get(id=business_id)
t.save()
return HttpResponseRedirect("/")
else:
...

最佳答案

您没有更新任何字段,请使用 form.cleaned_data获取表单字段值:

Once is_valid() returns True, the successfully validated form data will be in the form.cleaned_data dictionary. This data will have been converted nicely into Python types for you.

if form.is_valid():
t = Business.objects.get(id=business_id)
t.my_field = form.cleaned_data['my_field']
t.save()

此外,请考虑使用 UpdateView基于类的通用 View 而不是基于函数的:

A view that displays a form for editing an existing object, redisplaying the form with validation errors (if there are any) and saving changes to the object. This uses a form automatically generated from the object’s model class (unless a form class is manually specified).

关于python - Django 更新数据库中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23959156/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com