我正在尝试运行一个简单的更新表单,该表单应该更新从表单提交的数据库中的所有对象值。
这是我的更新 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/