Django + Python update and not insert

0

I'm using a filter to return some student and update their data, however when I try to save I get the following error:

  

Student with this CPF already exists and Student with this RA already exists.

My views.py :

from django.shortcuts import render, redirect
from .models import *

def create_student(request):
    form = StudentForm(request.POST or None)
    if form.is_valid():
        student = Student.objects.filter(cpf=form.cleaned_data['cpf']).filter(ra=form.cleaned_data['ra']) #<------ONDE FAÇO O FILTRO
        student.cpf = form.cleaned_data['cpf']
        student.ra = form.cleaned_data['ra']
        student.takeComputer = form.cleaned_data['takeComputer']
        student.computerType = form.cleaned_data['computerType']
        student.question = form.cleaned_data['queston']
        student.termAccepted = form.cleaned_data['termAccepted']
        student = form.save() #<------AQUI EU SALVO ELE
        return redirect('registrations:create_student')

    return render(request, 'student-form-registration.html', {'form': form})

My Models.py :

from django.db import models
from django import forms
from django.forms import ModelForm

class Student(models.Model):

    cpf = models.CharField(
        max_length=14, unique = True, verbose_name = 'CPF')
    ra = models.CharField(
        max_length=10, unique= True, verbose_name='RA')
    takeComputer = models.CharField(
        max_length=3, choices=TAKE_COMPUTER_CHOICES, verbose_name='Você levará seu computador pessoal?')
    computerType = models.CharField(
        max_length=7, choices=COMPUTER_TYPE_CHOICES, verbose_name='Qual o sistema operacional do seu notebook?:', blank=True)
    question = models.CharField(
        max_length=100, choices=QUESTI0N_CHOICES, verbose_name='Como a habilidade de saber programar pode ajudar minha carreira?'
    )

    registered = models.BooleanField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    termAccepted = models.BooleanField(default=1, verbose_name='Eu li e aceito o uso da minha imagem')

    def __str__(self):
        return self.ra

I want to update and not insert

    
asked by anonymous 03.09.2018 / 16:34

2 answers

3

It is not possible to know which form base class you are using if it is forms.Form or forms.ModelForm The question is if it is forms.Form it is trying to save an instance of Student that already has CPF which is impossible since you defined the field with unique=True . Now if you are using forms.ModelForm base, you only need to enter the construtor parameter in the instance class as follows:

form = StudentForm(request.POST or None, instance = <A instância que será atualizada>)
    
03.09.2018 / 19:27
2

form.save() saves the form , not the student . Since the form has all the data, it tries to create a new record.

Try changing the line

student = form.save()

by

student.save()
    
03.09.2018 / 18:57