Django , with jQuery Basic help !
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 %}<di开发者_运维技巧v 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
class Search(models.Model):
user = models.ForeignKey(User)
search = models.CharField(max_length=255)
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
class SearchForm(forms.ModelForm):
class Meta:
model = Search
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
def save(request):
if request.method == 'POST':
form = SearchForm(request.POST):
if form.is_valid():
# Do some search with forms.cleaned_data['search'] and save it to result
result = #SomeSearchCode...
instance = form.save()
html = render_to_string('ajax_template.html', {'search':instance, 'result':result}, RequestContext(request))
if request.is_ajax():
response = {'result':"Success", 'html':html}
return HttpResponse(json.dumps(response), mimetype="application/json")
retrun render_to_response('full_template.html', {'html':html }, RequestContext(request)
templates
As for templates, full_template.html
is the one that shows the search form and includes ajax_template.html
to 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 data
to the view which will receive it as request.POST
. success
is what handles the data you return from your save view. In this example it appends html rendered in the view to some random div.
var dataString = 'search='+ $("search-field").val();;
$(function() {
$("#search-form").live("click", function() {
$.ajax({
type: "POST",
url: $("#search-form").attr("action"),
data: dataString,
dataType: "json",
success: function(data, textStatus, XMLHttpRequest) {
jQuery(data["html"]).appendTo(".some-div");
}
});
return false;
});
});
This is not tested but i hope it shed some light on the process.
You should to check out a JSON-RPC library, like rpc4django. That allows you to make python functions accessible from javascript via ajax. A good RPC library makes AJAX vastly simpler.
精彩评论