Django REST视图更新对象时意外创建新对象求助
问题原因及修复方案
核心问题:表单提交路径错误
你的thingcurrentclass_detail.html中,表单的action属性设置为/instructables/,这个路径对应ThingCurrentClassList视图(列表创建视图),该视图的POST方法是创建新对象的逻辑,所以点击提交后,请求会走到创建接口,而非更新接口,导致每次提交都生成新对象。
修复步骤
- 修改
thingcurrentclass_detail.html中的表单action,改为指向当前详情页的路由:
<form action="{% url 'thingcurrentclass_detail' pk=thingcurrentclass.id %}" method="post">
这样提交请求会发送到ThingCurrentClassDetail视图的POST方法,该方法中已经正确传入了要更新的实例,执行serializer.save()时就会触发更新逻辑,而非创建。
- 可选优化:序列化器添加主键字段(非必需,但更规范)
在ThingCurrentClassSerializer的fields中加入主键字段(比如id),这样表单会携带主键信息(虽然视图已经通过URL pk获取,但显式包含更符合REST规范):
class Meta: model = ThingCurrentClass fields = ['id', 'title', 'active', 'description_short', 'description_long', 'length_in_minutes', 'adult_only', 'adult_only_reason', 'handout_fee', 'handout_limit', 'material_fee', 'material_limit', 'fee_itemization', 'scheduling_notes', 'special_needs_notes', 'heat_source', 'topic', 'track', 'tags', 'private_camp']
验证逻辑
修改后,提交表单时:
- 请求会发送到对应详情页的路由(如
/instructables/<pk>/) ThingCurrentClassDetail.post方法会获取到对应pk的实例并传入序列化器serializer.save()会更新该实例,而非创建新对象
内容的提问来源于stack exchange,提问作者JJ Ryan
相关产品推荐
相关产品推荐

