user3281114
user3281114

Reputation: 187

Django creating new record instead of updating

Im building a template where a form is populated with data from the DB and the user can update changes. Problem is, my code is creating a new record instead of updating the existing one.

Models:

class Users(models.Model):  
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=100)

class Event(models.Model):
    event_admin = models.ForeignKey(Users)
    event_name = models.CharField(max_length=50)
    event_location = models.CharField(max_length=50)
    event_date = models.DateField()
    event_time = models.TimeField()
    event_notes = models.CharField(max_length=200) 

View:

def edit_event(request, id):     
if request.method == 'POST': 
    e1 = CreateEventForm(request.POST)
    if e1.is_valid(): 
        e1 = e1.save(commit=False)   
        temp = get_object_or_404(Event, id = id)
        admin = temp.event_admin
        e1.event_admin = admin
        e1.save()

        eventID = e1.id
        return HttpResponseRedirect('/app/' + str(eventID))        
else:            
    event = CreateEventForm(instance=get_object_or_404(Event, id=id))
    return render(request, 'edit_event.html', {'event':event})

I believe my problem is that im not updating the current object, but building a new one. However, when working with the existing record i have issues assigning the foreign key which is needed in event_admin.

Upvotes: 1

Views: 1362

Answers (1)

catavaran
catavaran

Reputation: 45595

You should pass the instance argument to the constructor form:

event = get_object_or_404(Event, id=id)
form = CreateEventForm(request.POST, instance=event)
if form.is_valid():
    form.save()
    return HttpResponseRedirect('/app/' + str(event.id))

And why do you reassign the event_admin field in the Event instance?

Upvotes: 3

Related Questions