I have a form for which I would like to toggle a field’s required attribute on and off. I can successfully use the required attribute of the Form’s CharField but only on a page refresh or when I POST the form. When I try to do a GET callback the ‘sometimes’ field will have required toggled on and off but the html class “required” will not be refreshed.
The html that doesn’t get refreshed, showing the “required” class. This is auto-generated by Django:
<dt class="required">
<label for="sometimes">Username</label>
</dt>
Simplified 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"),)
My 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");
});
});
});
So, how can I make the html refresh the class name?
I’d suspect the problem lies somewhere between the browser and the server. When you POST or explicitly reload a page, the browser will load the full page from the server, ignoring its cache. However, when you do a regular GET request, the browser may show the last cached version of the page.
The solution is to add the following header to the HTTP response to this specific view:
One way to go about this might be to decorate your view with a decorator similar to this one: http://djangosnippets.org/snippets/275/