Django + Python update and do not insert

Asked

Viewed 408 times

0

I am using a filter to return some student and update their data, but 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

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 whether it is forms.Form the same is trying to save an instance of Student who already owns a CPF registered which is impossible since you set the field with unique=True. Now if you’re using it as a base forms.ModelForm just you in the construtor of the class inform the parameter instance as follows:

form = StudentForm(request.POST or None, instance = <A instância que será atualizada>)
  • Hello @Thiagoluizs, I’m using forms.ModelForm then I even saw something like this that you suggested, but when I do this form = StudentForm(request.POST or None , instance=student) I receive the following message: local variable 'student' referenced before assignment' I’m new to Dan and Python maybe I’m getting lost at some point

  • 1

    @Raphaelmelodelima to use the solution proposed by Thiago, you should put the command form = StudentForm(...) after setting the student variable - the error you are referring to happens when trying to use a variable before setting it - change the order of your commands

2

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

Try to change the line

student = form.save()

for

student.save()
  • Hello nosklo even changing the line, returns me the same error

  • @Raphaelmelodelima has how to put the complete error with traceback? Must be some other problem since using student.save() there is no way to be creating new record, the error should have at least changed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.