ScottOrwig
ScottOrwig

Reputation: 95

Django form INSERTs when I want it to UPDATE

I'm new to Django but I seem to have nearly identical code working on another site. I can update a record in the Django shell, but in view.py the same code insists on INSERTing a new record when I run this form.

So the relevant part of the view.py is this:

if request.method == 'POST':
    incidentId = request.POST['id']
    editedEvent = DisciplineEvent.objects.get(pk=int(incidentId))
    form = DisciplineEventEntryForm(request.POST, instance=editedEvent)
    form.save()
    variables = Context({
        'account': account,
        'date': request.POST['event_date'],
        'description': request.POST['incident_description'],
        'incident_id':incidentId,
         })
     template = get_template('disciplineform_confirm_entry.html')
     output = template.render(variables)
     response = HttpResponse(output)
     return response

I thought this would pull the record in question, save the new form data into it, and UPDATE the record. Instead it creates a new record with all the data and an incremented primary key.

Upvotes: 0

Views: 4968

Answers (1)

lprsd
lprsd

Reputation: 87077

What you are trying to do is unconventional and a possible security hole.

You should not get the instance of the object from the hidden id key you populated in the form. Users can easily change this one and get your code to overwrite some other model instance that they may not even have permission for.

The standard way to do it is to obtain the object based on the url.

def view_function(request,id):
    object_to_edit = get_object_or_404(Model,id=id) #Or slug=slug
    form = ModelForm(data = request.POST or None, instance=object_to_edit)
    if form.is_valid():
        form.save()
        redirect()
    return render_to_response('template_name',{},RequestContext(request))

Hope it helps!

Upvotes: 9

Related Questions