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

标签 python django django-forms django-views

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

这是我的更新 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/

相关文章:

python - 使用 Python Eve 添加 mongoDB 文档数组元素

python - 类型错误 : save() missing 1 required positional argument: 'self'

django - 替代 django 表单处理样板?

django - 将参数传递给 Django 中的表单

django-forms - ChoiceField.choices 可调用项如何知道要返回哪些选项?

python - 2.7.10 和 2.7.13 之间 dict.viewkeys() 和元组之间交集行为的差异

python - 元数据收集

python - Django - 网站主页

python - 参数 'on_delete' 没有值

Python:如何使用存储在变量中的值来决定启动哪个类实例?