0

I'm building a tool that performs some basic checking when a user goes to submit a new object via a standard form.

If an item exists with a similar name, the form is rejected and the user is asked to review the existing objects and confirm that they want to make a new one.

Now the warning checkbox below only needs to show up if there are already existing objects and the value is never stored. So its not part of the model, so I've added it into the form template below:

<form action="/createItem/" method="post">
    {% if similarObjects %}
    <div class="message warning">
        <strong>The following public objects were found with a title similar to "<em>{{form.name.value}}</em>".
        </strong>
        <ul>
            {% for obj in similarObjects %}
            <li>{{ obj.name }}</li>
            {% endfor %}
        </ul>
        <input type="checkbox" name="userSwearsTheyKnowWhatTheyAreDoing"/>
        <label for="userSwearsTheyKnowWhatTheyAreDoing">
            I've reviewed these items, and none of them meet my needs. Make me a new one.
        </label>
    </div>
    {% endif %}

    {{ form.as_p }}

    <input type="submit" value="Submit" />
</form>

Now, whenever I try and access form.userSwearsTheyKnowWhatTheyAreDoing it gives an error.

if len(similar) == 0 or form.cleaned_data['userSwearsTheyKnowWhatTheyAreDoing']:
    newObj = MyObject(**form.cleaned_data)
    newObj.save() 
    messages.success(request,"New Object Saved")
    return HttpResponseRedirect('/object/%d'% newObj.pk) # Redirect after POST

And get the error:

KeyError at /create/objectclass/
'userSwearsTheyKnowWhatTheyAreDoing'

What am I doing wrong?

2 Answers 2

1

You need to add a field to a ModelForm, then you have in forms.py:

class MyForm(forms.ModelForm):
   userSwearsTheyKnowWhatTheyAreDoing = forms.BooleanField()

   class Meta:
      model = MyObject

and in your views.py:

...
myform = MyForm(request.POST)
if len(similar) == 0 or myform.cleaned_data['userSwearsTheyKnowWhatTheyAreDoing']:
   newObj = myforms.save() 
   messages.success(request,"New Object Saved")
   return HttpResponseRedirect('/object/%d'% newObj.pk) # Redirect after POST
...
Sign up to request clarification or add additional context in comments.

1 Comment

@Lego Stormtroopr ... does my answer solve your problem?
0

The Django form does not get created and defined by whatever you are doing in the template. Instead you have to define your form with pyton by doing something like

class MyForm(forms.Form):
    userSwearsTheyKnowWhatTheyAreDoing = forms.BooleanField()
    ...

So at lease you need to add it there. That is exaclty what the error message is telling you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.