[Django]-Django save form – overwrite old row

2👍

Problem is in your model. You’ve explictly set ID field, as below:

    id = models.IntegerField(default=1,null=False,primary_key=True)

But you’re not setting it in form. That way django will each time create row with ID = 1 (because that’s default value).

When you’re creating field with ID that already exists in database, django will update existing field because it can’t create new (there can’t be more than one field with same primary key).

You should change type of ID to AutoField or remove it’s definition, django will then create default ID field that will be an AutoField.

4👍

The model was relevant. Look this:

class student(models.Model):
    id = models.IntegerField(default=1,null=False,primary_key=True)

You are always creating student number 1.

You should to set a new id by hand for each student:

def add_student(request):
    if request.method == "POST":
        form = StudentForm(request.POST)
        if form.is_valid():
            new_student = form.save(commit=False)
            id = a_function_to_take_another_id_for_a_student()
            new_student.id = id
            new_student = form.save(commit=True)
            new_student.author = request.user

Another approach is to can change type id to auto increment field:

id = models.AutoField(primary_key=True)

Leave a comment