Django“必需”属性/类不刷新

时间:2012-04-12 18:19:45

标签: html django request

我有一个表单,我想打开和关闭字段的必需属性。我可以成功使用required attribute of the Form's CharField,但仅限于页面刷新或POST表单时。当我尝试进行GET回调时,'有时'字段将需要打开和关闭,但html类“required”将不会刷新。

未刷新的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刷新类名?

1 个答案:

答案 0 :(得分:0)

我怀疑问题出在浏览器和服务器之间。当您POST或显式重新加载页面时,浏览器将从服务器加载整个页面,忽略其缓存。但是,当您执行常规GET请求时,浏览器可能会显示该页面的最后一个缓存版本。

解决方案是将以下标头添加到此特定视图的HTTP响应中:

Cache-Control: no-cache

解决此问题的一种方法可能是使用类似于此的装饰器来装饰您的视图:http://djangosnippets.org/snippets/275/