DEV Community

Coolmike890
Coolmike890

Posted on

Updating a Record Creates a new Record

I wish to update a record in Django using a form, but instead it creates a new record. I know it has to do with using get(), but I don't know how to fix it. Here is the relevant code:

my form:

class  AddRecordForm(forms.ModelForm):

    class Meta:
        model = Model2
        fields = ('field1', 'field2')
Enter fullscreen mode Exit fullscreen mode

my Models:

class Model2(models.Model):

    id = models.CharField(primary_key=True, max_length=12)
    created_at = models.DateTimeField(auto_now_add=True)
    field3 = models.ForeignKey(Model3,  on_delete=models.PROTECT, related_name='master')
    field4 = models.PositiveSmallIntegerField()

    class Meta:
        ordering = ['id']

    def __str__(self):
        return(f"{self.field3} ")
Enter fullscreen mode Exit fullscreen mode
class Model1(models.Model):

    field1 = models.ForeignKey(Model2,  on_delete=models.PROTECT, related_name='list')
    created_at = models.DateTimeField(auto_now_add=True)
    field2 =  models.PositiveSmallIntegerField(null=True, blank=True)
Enter fullscreen mode Exit fullscreen mode

and my view:

def update_record(request, pk):


    record = Model2.objects.get(field2=pk)
    form = AddRecordForm(instance=record)
    if request.method == 'POST':
            form = AddRecordForm(request.POST, instance=record)
        if form.is_valid():
            form.save()
            messages.success(request, "Record updated successfully!")
        return render(request, 'home', {})
        context = {'form':form}
    return render(request, 'update_record.html', context)
Enter fullscreen mode Exit fullscreen mode

Any help would be very much appreciated. Thanks.

Top comments (1)

Collapse
 
thaisavieira profile image
Thaísa Vieira

For more visibility of your post, try to add tags like #help, #django #python...
So it'll reach the right audience that can help you