簡體   English   中英

django form.is_valid()總是返回false

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

我認為我的有效函數似乎總是返回false,即使該帖子似乎發送了正確的數據(我認為)。 我對django和python相當陌生,並且使用Django Docs作為指南。 我還嘗試使用dajax中的django表單示例來實現我的表單(我已經在同一項目中成功安裝並使用了dajax)。 我的其他Dajax方法是get方法,我確定它們不會干擾我的帖子。

每次我點擊帖子時,都會顯示“表單無效”錯誤警報,我不確定為什么它沒有進入if塊。

我在這里閱讀過類似的問題,並仔細檢查了我能想到的所有內容。 如果有人可以指出問題所在,我將非常感激。 我在下面粘貼所需的代碼。

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

<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

@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()

這就是我的帖子。

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

嘗試將{{ form.non_field_errors }}添加到模板中。 這將向您顯示與字段無關的錯誤。

另外,如果可以的話,為了進行調試,請執行此操作,而不要使用{{ form.as_p }}

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

查看在POST上是否顯示一些錯誤。

我找到了解決我問題的方法。 我試圖使用ModelChoiceField來選擇元組,這是一種非常棘手的處理方式,因為ModelChoiceField期望模型對象不是任意字符串。

我用Choice Fields替換了表單,並通過覆蓋init函數來填充它們。 以下是我對表單所做的更改,以供參考。 我希望這可以幫助別人!

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