在Django中清除时如何更改另一个字段值? [英] How to change another field value when Clear in Django?
问题描述
我正在使用Django表单更新,但面临一个小问题,我在表单更新中有3个字段,名称
,图像
,状态
,现在,如果用户上传表单中的图像,则状态
会自动更改为数据库中的 1
。
I am working with Django form Updation, but I am facing a small issue, I have 3 fields in form updating, name
, image
, status
, Now if a user uploads an image in the form then the status
is automatically changing to 1
in the database.
但是现在,如果我使用复选框$ c清除表单,图片的$ c>,则此
状态
应该在我的数据库中更新为 0
but now if I clear the form using checkbox
of the image then this status
should be updated 0
in my database
这是我的 forms.py
文件...
class UpdateForm(forms.ModelForm):
...
def save(self, commit=True):
instance = super(UpdateForm, self).save(commit=False)
# Set status if saving picture
if instance.image:
instance.status = 1
if commit:
instance.save()
这是我的 views.py
文件...
def myview(request, id):
datas=Product.objects..get(pk=id)
form = UpdateForm(instance=datas)
if request.method === 'POST'
form = UpdateForm(request.POST or None, request.FILES or None, instance=datas)
if form.is_valid():
edit = form.save(commit=False)
edit.save()
return HttpResponse('Success')
else:
return HttpResponse('Fail')
template_name='test.html'
context={'datas':datas}
return render(request, template_name, context)
这是我的 site.html
文件...
<form method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
<a href="/media/{{datas.image}}"/>{{datas.image}}</a>
<input type="checkbox" name="image-clear" id="image-clear_id"/> Clear
<input type="submit" value="submit">
当我更新此表单时,它会更新状态中的 1
字段,但如果我从表单
中清除,则 status
的状态应为 0
在我的数据库中
When I update this form then it updates 1
in the status field, but if I clear from form
then status
should be 0
in my database
推荐答案
通过取消选中复选框运行代码时,将跳过以下行:
When you run the code by unchecking the checkbox, the following line will be skipped:
if instance.image:
instance.status = 1 # This will be skipped since instance.image is now False
尝试为instance.image条件为false时添加操作。
Try adding an action for when the condition for instance.image is false.
if instance.image:
instance.status = 1
else:
instance.status = 0
您当然可以对其进行重构,使其更加优美,但是清楚地表明了逻辑。
You can of course refactor that to write it more elegantly but that clearly shows the logic.
这篇关于在Django中清除时如何更改另一个字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!