I am working on quick project , listing search results from bing and my goal is user can save searches they perform . however i manage to list the search results in the template , and right now want to save the result items to the database using AJAX ! well this is my first attempt with ajax ( jquery ) and django !
template
{% for result in results %}<div class="resimgb">
<a href="{{ result.MediaUrl }}"><img src="{{ result.Thumbnail.Url }}" /></a>
<br />
<input type="text" value="{{ result.MediaUrl }}" id="#urlink">
<input type="submit" id="#savethis" name="add"></span><a herf="#" id="">save</a></div>{% endfor %}
JS :
<script type="text/javascript">
$( document ).ready( function() {
$( '#savethis' ).click( function() { data =
$( '#urlink' ).val(); $.get("/save/", function(data) {
alert(data);
});
});
});
</script>
–
I don’t write the view , cause am stuck at there actually ! well its going complex for me from here , as am little confused in
- How to save the data to my model ?
- How to send a response into the template to confirm saving the result ?
- as am a newbie to jquery , i know this is very wrong to use id inside a loop , can anyone suggests how to fix this issue ?
There are many tutorials about Django / jQuery , but most of them i came through are mainly superficial enough to leave me with open questions as well !!
You obviously have to have a model for storing searches and a form for taking user input (search string).
This will create a database table which will hold the saved search terms and relate the search terms to specific user.
models.py
It is easiest to just create a model form which will have input field in which user can write his search term, and also validates posted data as all user input should be validated:
forms.py
When you post the form data with AJAX call from the form to the save view, post data will be validated, a instance with the search term will be save in the database after you do the search for the data.
All left to do then is send all the data in the context dict to you template and render it.
Once rendered you construct a dictionary with data, dump it to JSON and return it with simple HttpResponse with specific mimetype
mimetype="application/json".views.py
templates
As for templates,
full_template.htmlis the one that shows the search form and includesajax_template.htmlto show results so we can easily append this with JavaScript. This way everything works even without JavaScript.jQuery
AJAX call is also strait forward. You collect the data from the form and send it with
datato the view which will receive it asrequest.POST.successis what handles the data you return from your save view. In this example it appends html rendered in the view to some random div.This is not tested but i hope it shed some light on the process.