【问题标题】:Django "required" attribute/class not refreshingDjango“必需”属性/类不刷新
【发布时间】:2012-04-13 02:33:23
【问题描述】:

我有一个表单,我想打开和关闭字段的必填属性。我可以成功使用required attribute of the Form's CharField,但只能在页面刷新或发布表单时使用。当我尝试执行 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刷新类名呢?

【问题讨论】:

    标签: html django request


    【解决方案1】:

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

    解决方案是在这个特定视图的 HTTP 响应中添加以下标头:

    Cache-Control: no-cache
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-19
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      相关资源
      最近更新 更多