Reputation: 233
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 upload a image in form then status should be change automaticly in my database.
here is my forms.py
file...
class UpdateForm(forms.ModelForm):
model = Product
fields = ['name', 'image', 'status']
here is my views.py
file...
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)
Default status
is 0
in my database, If a user upload image then status
should be 1
in my database, please let me guide how i can do it.
Upvotes: 0
Views: 1642
Reputation: 953
The best way would be to override the save()
method of your form class. A possible implementation could be:
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()
return m
Upvotes: 1