使用 Form.has_changed() 验证 Django UpdateView
Use Form.has_changed() validation with Django UpdateView
我正在尝试 post 当 UpdateView 中的一个或多个值发生更改时发送消息。这可能与 Form.has_changed() 与此通用视图有关吗?例如:
class MyUpdateView(UpdateView):
model = MyModel
form = MyModelForm
fields = "__all__"
template_name = "mymodel_form.html"
if form.has_changed():
logger.info("Some values have changed")
您可以为此覆盖 .form_valid(…)
method [Django-doc]:
class MyUpdateView(UpdateView):
model = MyModel
form_class = MyModelForm
fields = '__all__'
template_name = 'mymodel_form.html'
def <strong>form_valid</strong>(self, form):
if form.has_changed():
logger.info('Some values have changed')
return super().form_valid(form)
或者如果您想要在表单可能无效的情况下记录更改,您可以使用 .get_form(…)
[Django-doc]:
class MyUpdateView(UpdateView):
model = MyModel
form_class = MyModelForm
fields = '__all__'
template_name = 'mymodel_form.html'
def <strong>get_form</strong>(self, form_class=None):
form = super().get_form(form_class=form_class)
if form.has_changed():
logger.info('Some values have changed')
return form
我正在尝试 post 当 UpdateView 中的一个或多个值发生更改时发送消息。这可能与 Form.has_changed() 与此通用视图有关吗?例如:
class MyUpdateView(UpdateView):
model = MyModel
form = MyModelForm
fields = "__all__"
template_name = "mymodel_form.html"
if form.has_changed():
logger.info("Some values have changed")
您可以为此覆盖 .form_valid(…)
method [Django-doc]:
class MyUpdateView(UpdateView):
model = MyModel
form_class = MyModelForm
fields = '__all__'
template_name = 'mymodel_form.html'
def <strong>form_valid</strong>(self, form):
if form.has_changed():
logger.info('Some values have changed')
return super().form_valid(form)
或者如果您想要在表单可能无效的情况下记录更改,您可以使用 .get_form(…)
[Django-doc]:
class MyUpdateView(UpdateView):
model = MyModel
form_class = MyModelForm
fields = '__all__'
template_name = 'mymodel_form.html'
def <strong>get_form</strong>(self, form_class=None):
form = super().get_form(form_class=form_class)
if form.has_changed():
logger.info('Some values have changed')
return form