Difference between saving the form directly and creating model instance

Asked

Viewed 67 times

-1

I have been having some problems when I will insert or modify some value that was not passed to the user in the form and then save it.

For example I have a Local model :

models.py

class Local(models.Model):
    nome = models.CharField(max_length=150)
    descricao = models.TextField()
    avaliado = models.BooleanField()

    def __str__(self):
        return self.nome

In the form contains :

forms.py

class FormLocal(ModelForm):
    class Meta:
        model = Local
        fields = ['nome', 'descricao']

And in the view when I do so wrong:

if request.method == 'POST':
        local = FormLocal(request.POST)

        if local.is_valid():
            local.save(commit=False)    
            local.avaliado = True 
            local.save()
            return redirect("listar_local")

Displays the following error :

IntegrityError: NOT NULL constraint failed

But when I do it right:

 if request.method == 'POST':
        local = FormLocal(request.POST)

        if local.is_valid():
            local.save(commit=False)    
            loc = Local(nome=local.cleaned_data.get('nome'),
                descricao = local.cleaned_data.get('descricao'),
                avaliado=True)
            loc.save()
            return redirect("listar_local")

Why can’t I change the value and save to the bank but when I create the model instance and save it right ?

This is still a little confusing for me: when to create the model instance and when to save with the form ?

1 answer

2


From what I understand your Modelform does not contemplate the field evaluated. And you are trying to change it manually, hence the error.

That would be right:

if request.method == 'POST':
    local = FormLocal(request.POST)

    if local.is_valid():
        local_novo = local.save(commit=False)    
        local_novo.avaliado = True 
        local_novo.save()
        return redirect("listar_local")

Browser other questions tagged

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