我有一个表单,我想打开和关闭字段的必需属性。我可以成功使用表单 CharField 的 required 属性,但只能在页面刷新或发布表单时使用。当我尝试执行 GET 回调时,“有时”字段将需要打开和关闭,但不会刷新 html 类“必需”。
未刷新的 html,显示“必需”类。这是由 Django 自动生成的:
<dt class="required">
<label for="sometimes">Username</label>
</dt>
简化的views.py:
form_validate(httpreq):
form = SetupForm()
if httpreq.GET.has_key('req'):
# In this case, it is not the initial call
if httpreq.GET['req'] == 'true':
print 'required is True'
form.fields['sometimes'].required = True
else:
print 'required is False'
form.fields['sometimes'].required = True
else:
# Here, required = True/False behaves as expected
# When the field is required, it has the class="required"
form.fields['sometimes'].required = True
# For forms.fields['sometimes'].required = False,
# class="required" is absent in the html
class SetupForm(forms.Form):
sometimes = forms.CharField(widget=forms.TextInput(attrs={'id':'sometimes','size':FIELD_LENGTHS['shorttext'],}), label=ugettext_lazy("Username"),)
我的 jQuery:
$(document).ready(function(){
$('#tog').click(function(){
var params = {}
if ($("#tog").is(":checked")) {
params = {"auth":true};
} else {
params = {"auth":false};
}
var url = "/url_for_form/?fmt=json";
$.getJSON(url, params, function(jsonrpc, xhrstatus, xhr) {
console.log("JSON callback");
});
});
});
那么,如何让 html 刷新类名呢?