Shagun Raghav
Shagun Raghav

Reputation: 57

How to update a record in django?

I try to update my record but in place of updating it displays a message saying the record already exists.

here is the logic I m executing :

@login_required
def cylinderUpdateView(request,pk):
    if not request.user.is_superuser:
        return redirect('index')
    obj=CylinderEntry.objects.get(id=pk)
    form=CylinderEntryForm(instance=obj)

    if request.method=='POST':
        form=CylinderEntryForm(data=request.POST)
        if form.is_valid():
            
            obj=form.save(commit=False)

            obj=form.save()
            return redirect(cylinderListView)
    return render(request,'entry/cylinderentry_form.html',locals())

Upvotes: 1

Views: 72

Answers (2)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

In case of a POST request you have initialized the form as:

if request.method=='POST':
    form=CylinderEntryForm(data=request.POST)

Here you haven't specified the instance like you did in case of a GET request so only the data submitted from the form is considered you need to specify the instance in this case too:

if request.method=='POST':
    form=CylinderEntryForm(data=request.POST, instance=obj)

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

If you want to update an object with a ModelForm, you should pass that instance with the instance=… parameter:

@login_required
def cylinderUpdateView(request,pk):
    if not request.user.is_superuser:
        return redirect('index')
    
    obj = CylinderEntry.objects.get(id=pk)

    if request.method=='POST':
        #                                 pass the instance ↓
        form = CylinderEntryForm(data=request.POST, instance=obj)
        if form.is_valid():
            form.save()
            return redirect(cylinderListView)
    else:
        form = CylinderEntryForm(instance=obj)
    return render(request,'entry/cylinderentry_form.html',locals())

Upvotes: 2

Related Questions