0

I was trying hard to prevent the creation of new row in the database table when I save the form in my view.

I have below code in my view

def checker(request):
  response_data=''
  if request.method == "POST":
    user_form1 = DocumentForm(request.POST, request.FILES) 
    if user_form1.is_valid(): 
        new_form = user_form1.save(commit=False)
        new_form.save()  # Image file gets uploaded in the server and new row gets created each time this gets executed
        user_form1.save_m2m()
        res=td_tab.objects.filter(id=request.session.get('proid')).update(profpicpath=new_form.profpicpath.url)
        response_data = 'Updated response'
else:
    form = DocumentForm() 
    response_data = 'Nothing to update!'
return HttpResponse(response_data, content_type="text/plain")

Form :

class DocumentForm(forms.ModelForm):
    profpicpath = forms.FileField()
    class Meta:
        model = td_tab
        fields = ('profpicpath',)

model has several fields apart from profpicpath.

The problem is, in my view when new_form.save() gets executed, it is creating new record in the database table :(

I want the existing record to be updated for specific proid.. surprisingly, below line doesn't work in view.. even if i make it work, new row gets created and only profpicpath field is getting populated in the database table with the latest entry :(

res=td_tab.objects.filter(id=request.session.get('proid')).update(profpicpath=new_form.profpicpath.url)

How can I prevent creation of new record in td_tab table on every request that is made for checker view ?

Or may be is there some trick to override save() method for form, such that it just updates the existing record rather creating new record for each of its execution ?

1 Answer 1

4

You should pass the model instance to update to the form object:

your_instance = Model.objects.get(some_data=some_data)
form = DocumentForm(request.POST or None, instance=your_instance)

if form.is_valid():
   ...
   ...
   form.save()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.