[Answer]-Django pre-populated form that updates record on submit

1👍

Your problem is that you are converting your locations objects into a list of dictionaries. And then passing a dictionary into the form as instance.

This is happening because you are calling the .values() method on the queryset. That method returns a special ValuesQuerySet which basically looks like a list of dictionaries. Not a list of locations objects.

The instance parameter on the form needs to be an object, not a dictionary. So just simply remove the .values() calls, and it should work. Like this:

def locations(request):
    locations = locations.objects.filter(id=request.session['location'])
    first_location=locations[0]
    if request.method == 'GET':
        if request.session['Manager']== True:
            form = locationsForm(instance=first_location)
        context = {'locations': locations, 'form': form}
        return render(request, 'locations/locations.html', context)
    elif request.method == 'POST':
        form=locationsForm(request.POST, instance=first_location)
        if form.is_valid():
            cd=form.cleaned_data
            form.save()
            form = locationsForm()
            locations= locations.objects.values().filter(id=request.session['depot'])
            context = {'locations': locations}
            return render(request, 'locations/locations.html', context)
        else:
            context = {'locations': locations, 'form': form}
            return render(request, 'locations/locations.html', context)

Leave a comment