Problems with Database Update, how to Debug this?

Hi folks. I intended to do some minor changes to a part of my project and am encountering problems with a form-based Database-interaction.
It’s about making changes to an existing dataset. My problem is, that it seems i don’t get the form validated but i do not understand why.

Here is the code snippet in the views.py:

        elif 'alter_key' in request.POST:
            key = request.POST.get('alter_key')
            formdata = Keys.objects.get(key=key)
            form = SaveKeysForm(instance=formdata)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('keys.html?key_list=&success')
            else:
                context['error'] = 'Wrong data'

When i perform a print(form) before form-validation i get:

<tr>
    <th><label for="id_key">Key:</label></th>
    <td>
      
      <input type="text" name="key" value="0.18.05" id="id_key">
      
      
    </td>
  </tr>

  <tr>
    <th></th>
    <td>
      
      <textarea name="comment" cols="40" rows="2" class="form-control fw-bold border border-1 border-black m-1" title="Kommentar" placeholder="Kommentar" id="id_comment">
Defekt</textarea>
     
    </td>
  </tr>

What am I missing ?

here some more infos about the forms.py:

class ManageKeysForm(ModelForm):

    class Meta:
        model = Keys
        fields = ['key', 'comment']

    comment = forms.CharField(label='', required=False, widget=Textarea(attrs={
        'class': "form-control fw-bold border border-1 border-black m-1",
        'title': 'Kommentar',
        'rows': 2,
        'placeholder': 'Kommentar',
    }))

    def clean_key(self):
        key = self.cleaned_data['key'] if self.cleaned_data['key'] else None
        return key

    def clean_comment(self):
        comment = self.cleaned_data['comment'] if self.cleaned_data['comment'] else None
        return comment


class SaveKeysForm(ManageKeysForm):
    key = forms.CharField(required=False)

I think we’d need to see more of the view and template involved with this, because there doesn’t seem to be enough information to get a complete picture of what’s going on here.

For example:

Where is this “alter_key” coming from? You don’t show a field by that name in either the form or template you are showing here.

Also, when you say:

Are you saying that the form is returning False on the is_valid call? Or is it not even getting to that point in the code?

If is_valid is returning False, then the form would have the errors associated with it. (See the docs pages starting with How errors are displayed and Working with form templates for more details and examples of rendering errors in forms.

Side note:
This code

has the same result and is more commonly written as key = self.cleaned_data.get('key') - which also can be used when you’re referencing the data in cleaned_data instead of adding the key to cleaned_data in a clean_ method.

The code reaches the is_valid part but jumps to the context['error'] = 'Wrong data' section.
So despite of i can’t see an error in the print(form) command, i suspect the error to be in validation.

But NOT in validation itself, because You are right, the given information about what is supposed to be happen here is too small to navigate through it and find a solution being not a project insider.

So I will try to compilate the complete code cascade that leads to the already given lines, including what’s happening in template and so on. Will take me some time. But thank you for the moment :slight_smile:

You won’t. You’ll probably need to explicitly print(form.errors) in the else clause.

Sounded completely logic to me and I was totally happy about this hint…alas…it leads to NOTHING in the console…there is nothing printed out after adding this command. no matter if I place it in the else cluase or before the if statement…shouldn’t there be at last some white '' or something like that after a print command ?

Ok, I see one issue here:

This isn’t binding data to the form, this is creating an instance of the form using the Keys object. form.is_valid() is always going to be false here.

You need to bind the submitted data to the form for those tests to be valid.

Review the docs at The Forms API | Django documentation | Django for an understanding of Bound and Unbound forms.

I haven’t read your link to the Forms API in Django Documentation yet but i am a little confused now…i thought, that the ìnstance attribute within such a code line assures, that you can alter an existing db-entry? without it, i would get for unique entries the error “already existing” or would without unique simply generate a new dataset???

Yes, that creates an instance of the form with the values currently existing in the database. It sets the initial values for the form as it gets rendered and sent to the browser.

However, that does nothing relative to accepting data submitted from the HTML form on the page, and modifying that instance. That’s where binding the POST data comes into play.

This question then implies to me that you need to also review the Working with forms page - perhaps even before reading the Bound and Unbound forms docs.

ok my bad…it has of course simply to be

elif 'key' in request.POST:
            key = request.POST.get('key')
            formdata = Keys.objects.get(key=key)
            form = SaveKeysForm(request.POST, instance=formdata)

because the column in db is named “key” :stuck_out_tongue: and i forgot the request.POST to hand over data to the defined instance…