Django Admin - save_model方法 - 如何检测字段是否已更改? [英] Django Admin - save_model method - How to detect if a field has changed?
问题描述
我试图覆盖 save_model方法在Django管理对象,以防止用户更改某个字段。然而,我找不到一个方法来确定这个方法是否已经改变了。
I'm trying to override the save_model method on a Django admin object to prevent a user from changing a certain field. However I can't find a way to find out if the field has changed within this method.
这是我的代码到目前为止:
Here's my code so far:
def save_model(self, request, obj, form, change):
if change:
if obj.parking_location == form.cleaned_data['parking_location']:
super(MyVehiclesAdmin, self).save_model(request, obj, form, change)
else:
messages.error(request,
"The Parking Location field cannot be changed.")
问题是obj.parking_location和form.cleaned_data [' parking_location']具有新值。 (这可能是Django中的一个bug吗?好像obj应该包含预先保存的值)。在任何情况下,是否有另一种方法来实现?
The problem is both obj.parking_location, and form.cleaned_data['parking_location'] have the new value. (Could this be a bug in Django? It really seems like the obj should contain the pre-save values). In any case, is there another way to accomplish this?
(我在Django 1.2上)
(I'm on Django 1.2)
推荐答案
首先,这不是一个bug,它是Django 1.2起的记录行为。
Firstly, this isn't a bug, it's the documented behaviour in Django 1.2 onwards.
第一次调用
ModelForm.is_valid()
,访问ModelForm.errors
或以其他方式触发表单验证,您的模型将被原位清理。此转换用于在保存模型时发生。如果您需要一个未修改的模型实例,则应将一个副本传递给ModelForm构造函数。
the first time you call
ModelForm.is_valid()
, accessModelForm.errors
or otherwise trigger form validation, your model will be cleaned in-place. This conversion used to happen when the model was saved. If you need an unmodified instance of your model, you should pass a copy to the ModelForm constructor.
如果要防止用户从编辑一个关键字段,更好的方法可能是使用 ModelAdmin.readonly_fields
选项。
If you want to prevent the user from editing a paticular field, a better approach might be to use the ModelAdmin.readonly_fields
option.
class VehicleRegistrationAdmin(admin.ModelAdmin):
readonly_fields = ('parking_location',)
或者,你可以将 ModelAdmin.form
替换为排除该字段的自定义表单。
Or, you could replace the ModelAdmin.form
with a custom form that excludes that field.
class VehicleRegistrationForm(forms.ModelForm):
class Meta:
exclude = ('parking_location',)
class VehicleRegistrationAdmin(ModelAdmin):
form = VehicleRegistrationForm
最后,直接回答你的问题,你c通过检查 form.changed_data
来检查 save_model
方法中字段是否已更改。这是一个更改字段名称的列表。
Finally, to answer your question more directly, you can check whether a field has changed in the save_model
method by inspecting form.changed_data
. This is a list of the names of the fields which have changed.
def save_model(self, request, obj, form, change):
if 'parking_location' in form.changed_data:
messages.info(request, "Parking location has changed")
else:
messages.info(request, "Parking location has not changed")
super(MyVehiclesAdmin, self).save_model(request, obj, form, change)
这篇关于Django Admin - save_model方法 - 如何检测字段是否已更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!