在django表单中添加自定义复选框

时间:2014-03-16 05:55:07

标签: django forms

我正在构建一个工具,当用户通过标准表单提交新对象时,该工具会执行一些基本检查。

如果项目存在名称相似,则表单将被拒绝,并要求用户查看现有对象并确认他们要创建新对象。

现在,只有已存在的对象并且永远不会存储该值时,才需要显示下面的警告复选框。所以它不是模型的一部分,所以我把它添加到下面的表单模板中:

<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>

现在,每当我尝试访问form.userSwearsTheyKnowWhatTheyAreDoing时,都会出错。

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

得到错误:

KeyError at /create/objectclass/
'userSwearsTheyKnowWhatTheyAreDoing'

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您需要在ModelForm中添加一个字段,然后在forms.py中添加<:p>

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

   class Meta:
      model = MyObject

和你的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
...

答案 1 :(得分:0)

Django表单不会由您在模板中执行的任何操作创建和定义。相反,您必须通过执行类似

的操作来定义带有pyton的表单
class MyForm(forms.Form):
    userSwearsTheyKnowWhatTheyAreDoing = forms.BooleanField()
    ...

所以至少你需要在那里添加它。这是错误消息告诉你的内容。