dynamic forms in django with ajax/dajax
I have this simple form with a queryset to display job objects and allow the user to select one. Now, i would like to have a group of two radio buttons that would allow the user to select a 'filtering option'. If the user selects a group filter with the radio buttons, i would a drop down to appear that allows them to select which group they would like to filter on. I want to do this without having to reload the page, so i'm attempting to use dajax.
I was able to find an example on the dajax website that does something similiar, however, i was not able to get it to work. The radio buttons appear and the drop down appears(empty). When i click on the "Group" radio button, the drop-down should populate with all my Group objects, but it doesnt.
I've been stuck on this for awhile, so any help would be greatly appreciated.
forms.py
filters = (('0', 'Group'),
('1', 'Host'),
)
class JobSelectForm(forms.Form):
def __init__(self, *args, **kwargs):
super(JobSelectForm, self).__init__(*args, **kwargs)
self.fields['jobs'].widget.attrs["size"] = 20
jobs = forms.ModelChoiceField(queryset=Job.objects.all().order_by('name'), empty_label=None,)
filter = forms.ChoiceField(choices=filters,
widget=forms.RadioSelect(attrs={'onchange': "Dajaxice.tdportal.updatefilter(Dajax.process,{'option':this.value})", 'name':'combo1', 'id':'combo1', },
renderer=HorizRadioRenderer),
ajax.py
def updatefilter(request, option):
dajax = Dajax()
options = [Group.objects.all(),
Host.objects.all(),
]
out = ""
for o in options[int(opti开发者_C百科on)]:
out = "%s<option value='#'>%s" % (out,o,)
dajax.assign('#combo2','innerHTML',out)
return dajax.json()
dajaxice_functions.register(updatefilter)
template
{{selectForm.filter.label}}: {{selectForm.filter}}
<br>
<select name="combo2" id="combo2" onchange="" size="1"></select>
<br><br>
<form method="post" action="/tdportal/jobs/">{% csrf_token %}
{{selectForm.jobs}}
<br><br>
<input type="submit" value="Edit" /> <a href="/tdportal/jobs/new/"><input type="button" name="new" value="New" /></a>
</form>
You need to add your dajaxice function to the select onchange
to reference your function in the template.
Something like:
<select name="combo2" id="combo2" onchange="Dajaxice.your_project.your_appname.updatefilter(Dajax.process,{'option':this.value}" size="1"></select>
(Replace your_project with your project name, your_app with your appname).
Also make sure in your template you have all the necessary headers (and that they actually are there; e.g., if you view the source that you can click to them).
Be sure to debug using google chrome inspector (Ctrl-Shift-I) or firebug (in firefox).
EDIT: I now noticed that you have something similar that's in your form. How does it render in the HTML when you view the source? Is it improperly escaped?
I think you forgot a %
sign (value='#'
) and a closing </option>
in here:
out = "%s<option value='%s'>%s</option>" % (out,o,o)
精彩评论