简体   繁体   English

django form.is_valid()总是返回false

[英]django form.is_valid() always returns false

My is valid function in my view always seems to be returning false even though the post seems to be sending the right data (I think). 我认为我的有效函数似乎总是返回false,即使该帖子似乎发送了正确的数据(我认为)。 I'm pretty new to django and python and I'm using the Django Docs as a guide. 我对django和python相当陌生,并且使用Django Docs作为指南。 I am also trying to implement my form using the django form example in dajax (I have already installed and used dajax successfully in the same project). 我还尝试使用dajax中的django表单示例来实现我的表单(我已经在同一项目中成功安装并使用了dajax)。 My other Dajax methods are get methods and I'm sure they don't interfere with my post. 我的其他Dajax方法是get方法,我确定它们不会干扰我的帖子。

Each time I hit post, the "form is not valid" error alert I have shows up and I am not sure why it doesn't enter the if block. 每次我点击帖子时,都会显示“表单无效”错误警报,我不确定为什么它没有进入if块。

I have read similar questions on here and have double checked everything I could think of. 我在这里阅读过类似的问题,并仔细检查了我能想到的所有内容。 I would be so grateful if anyone could help point out where the problem is. 如果有人可以指出问题所在,我将非常感激。 I am pasting the required code below. 我在下面粘贴所需的代码。

forms.py forms.py

class BedSelectForm(forms.Form):
Branch = forms.ModelChoiceField(
    label = u'Branch',
    queryset = Result.objects.values_list('branch', flat =True).distinct(),
    empty_label = 'Not Specified',
    widget = forms.Select(attrs = {'onchange' : "Dajaxice.modmap.updatecomboE(Dajax.process, {'optionB':this.value})"})
    )
Env = forms.ModelChoiceField(
    label = u'Environment',
    queryset = Result.objects.values_list('environment', flat =True).distinct(),
    empty_label = 'Not Specified',
    widget = forms.Select(attrs = {'onchange' : "Dajaxice.modmap.updatecomboD(Dajax.process, {'optionE':this.value})"})
    )
Disc = forms.ModelChoiceField(
    label = u'Discipline',
    queryset = Result.objects.values_list('discipline', flat =True).distinct(),
    empty_label = 'Not Specified'

    )

template.html template.html

<form action="" method="post" id = "select_form">
        <div style = "color :white" class="field_wrapper">
             {{ form.as_p }}
        </div>        
        <input type="button" value="Display Table" onclick="send_form();"/>
</form>

<script type="text/javascript">
    function send_form(){
        Dajaxice.modmap.dispTable(Dajax.process,{'form':$('#select_form').serialize(true)});
    }
 </script>

ajax.py ajax.py

@dajaxice_register
def dispTable(request, form):
    dajax = Dajax()
    form = BedSelectForm(deserialize_form(form))

    if form.is_valid():
        dajax.remove_css_class('#select_form input', 'error')
        dajax.alert("Form is_valid(), your username is: %s" % form.cleaned_data.get('Branch'))
    else:
        dajax.remove_css_class('#select_form input', 'error')
        for error in form.errors:
            dajax.add_css_class('#id_%s' % error, 'error')
        dajax.alert("Form is_notvalid()")

    return dajax.json()

This is what my post looks like.. 这就是我的帖子。

argv    {"form":"Branch=Master&Env=ProdCoursera&Disc=ChemistryMOOC"}

Try adding {{ form.non_field_errors }} to your template. 尝试将{{ form.non_field_errors }}添加到模板中。 This will show you errors not related to fields. 这将向您显示与字段无关的错误。

Also, if you can, for the sake of debugging, do this instead of {{ form.as_p }} 另外,如果可以的话,为了进行调试,请执行此操作,而不要使用{{ form.as_p }}

{% for field in form.fields %}
    <div>{{ field }}</div>
    {% if field.errors %}
            <div class="alert alert-danger">
                {{ field.errors }}
            </div>
    {% endif %}
{% endfor %}

See if that shows some errors on POST ing. 查看在POST上是否显示一些错误。

I found the solution to my problem. 我找到了解决我问题的方法。 I was trying to pick tuples using a ModelChoiceField which is a very hacky way of doing things because a ModelChoiceField expects model objects not arbitrary strings. 我试图使用ModelChoiceField来选择元组,这是一种非常棘手的处理方式,因为ModelChoiceField期望模型对象不是任意字符串。

I replaced my forms with Choice Fields and populated them by overriding the init function. 我用Choice Fields替换了表单,并通过覆盖init函数来填充它们。 Below are the changes I made to my form for reference. 以下是我对表单所做的更改,以供参考。 I hope this helps someone! 我希望这可以帮助别人!

class BedSelectForm(forms.Form):
Branch = forms.ChoiceField(
    choices = [],)

Env = forms.ChoiceField(
    choices = [],)

Disc = forms.ChoiceField(
    choices = [],)

def __init__(self, *args, **kwargs):
    super(BedSelectForm, self).__init__(*args, **kwargs)
    self.fields['Branch'].choices = [(x.pk, x.branch) for x in Result.objects.distinct()]
    self.fields['Env'].choices = [(x.pk, x.environment) for x in Result.objects.distinct()]
    self.fields['Disc'].choices = [(x.pk, x.discipline) for x in Result.objects.distinct()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM