I am practicing from a tutorial where I have reached to create a search box with jquery and ajax. Every thing is going good, except, when i press any key in the search, I get an error,
RuntimeError at /articles/search You called this URL via POST, but the
URL doesn't end in a slash and you have APPEND_SLASH set. Django can't
redirect to the slash URL while maintaining POST data. Change your
form to point to localhost:8000/articles/search/ (note the trailing
slash), or set APPEND_SLASH=False in your Django settings.
I checked for "/" in my code, but its there. Don't know what's going on. Please help.
application's urls.py:
url(r'^search/$', 'article.views.search_title'),
)
views.py:
def search_title(request):
if request.method == "POST":
search_text = request.POST['search_text']
else:
search_text = ''
articles = Article.objects.filter(title__contains=search_text)
return render_to_response('ajax_search.html', {'article': article})
I'm using jquery version:
jquery-2.0.0.min.js
ajax.js:
$(function(){
$('#search').keyup(function() {
$.ajax({
type: "POST",
url: '/articles/search/',
data: {
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
And even when I inspect the ajax.js, in the last line
$('#search-results').html(data);
It reads it as:
$('#search-results').html(date);
My main url:
(r'^articles/', include('article.urls')),
Sorry, I had a typo. In my views.py:
def search_titles(request):
if request.method == "POST":
search_text = request.POST['search_text']
else:
search_text = ''
articles = Article.objects.filter(title__contains=search_text)
return render_to_response('ajax_search.html', **{'article': article})**
It should have been:
return render_to_response('ajax_search.html', **{'articles':articles})**
Related
I am coding a small Django project where an user can select an object and save it in a database. I am trying to implement an Ajax call on a button to delete this object if necessary.
I am doing it step by step, debugging with the console.
my urls:
app_name = 'register'
urlpatterns = [
path('<int:user_id>/', views.account, name='account'),
path('/delete/', views.delete, name='delete'),
]
my view.py:
def delete(request):
data = {'success': False}
if request.method=='POST':
product = request.POST.get('product')
print(product)
data['success'] = True
return JsonResponse(data)
my ajax.js:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
console.log('ok till this point')
$.ajax({
url: '{% url "register/delete" %}',
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
My view isn't doing much for now but I haven't any knowledge about Ajax and I am doing it one step at a time.
This is the error I get in the console:
jquery.min.js:2 POST http://127.0.0.1:8000/register/6/%7B%%20url%20%22register/delete%22%20%%7D 404 (Not Found)
As far as I understand, Ajax can't find my url: '{% url "register/delete" %}'.
I have tried '{% url "register:delete" %}' with no luck either.
I found an answer after some tweaking, I defined my url before the Ajax call and then pass it in it:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
var url = '/register/delete/'
console.log( url)
$.ajax({
url: url,
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
Also you can add just the string of url to "url" parameter without characters {% url %}. Maybe you copied the code from pattern Django and added it to JS-file. So it does not work.
I am trying to make a simple ajax request to a view but keep having a not Found error for the given url:
Not Found: /myapp/start_session/1/scan_ports/
"POST /myapp/start_session/1/scan_ports/ HTTP/1.1" 404 5711
js
$(document).ready(function() {
$.ajax({
method: 'POST',
url: 'scan_ports/',
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
success: function (data) {
alert("OK!");
},
error: function (data) {
alert("NOT OK!");
}
});
});
url
url(r'^scan_ports/$',views.ScanPorts,name='scan_ports'),
view
#login_required
def ScanPorts(request):
user = request.user
if request.method == 'POST':
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
return HttpResponse('')
Is the ajax request not set properly?
Assuming you are in the "myapp" app, replace:
method: 'POST',
url: 'scan_ports/',
for this:
method: 'POST',
url: '/myapp/scan_ports/',
First check your urls, the url on which you posted is incorrect hence 404 not found error.
Try to define your url in your JS as: {% url 'scan_ports' %} which will search your urls with the name your provided in urls.py
In addition, this may not be a good approach to submit a form via ajax.
Your JS should be something like this:
$('.form-class-name').on('submit', function (e) {
e.preventDefault();
console.log("ajax is called");
$.ajax({
type: $(this).attr('method'),
url: "/url-name/",
data: $(this).serialize(),
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(data) {
alert("Failure");
}
})
}
e.preventDefault() prevents the natural/default action, and prevents from submitting the form twice.
.serialize(), serializes the form data in a json format.
append a "/" before and after your action url.
Your view must return a dictionary as ajax deals with JSON format.
Edit your view like this:
if request.method == "POST":
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
a = {'data':'success'}
return HttpResponse(json.dumps(a))
This will return a dictionary required by the ajax.
I am trying to figure out how I can make an ajax request (with jquery) from my template in order to execute a view on a button click. I don't want to redirect to another page. I just need to execute the code in the view.
This is my on button click event:
$(document.body).on("click", "#download_xls",function(e) {
selected_country = ($("#button-countries").val())
selected_subareas = $('#_all_values').val();
id = "?country=" + selected_country + "&" + "regions=" + selected_subareas
whole_url = "{% url 'test_download' %}" + id
$("#download_xls").attr("href", whole_url)
});
As I pass the values in my URL, I don't even need to pass some parameters through the ajax request. I just need to execute the code in the view.
The view is something like this:
def test_download(request):
print(request.GET.get('country'))
print(request.GET.get('regions'))
fileContent = "Your name is %s"
res = HttpResponse(fileContent)
res['Content-Disposition'] = 'attachment; filename=yourname.txt'
return res
EDITED
I have added the ajax GET request in my template as:
whole_url = "{% url 'test_download' %}"+id
$.ajax({
type: "GET",
url: whole_url,
success: function(data) {
alert('sd')
},
error: function(data) {
alert('error')
},
});
I get an error cause there is no corresponding template for this view. I think I need to add something in the urls.py file.
I read here that I need to modify urls.py as:
url(r'^link-to-fun1$', views.fun1),
But its not clear to me what should be the link-to-fun1.
I tried:
url(r'^create$', 'test_download', name='test_downlad'),
But gives an error: No Reverse Match.
You could use TemplateView add to your url and use JQuery to do something, like this:
views.py
class ajax_view(TemplateView):
def get(self, request, *args, **kwargs):
id_value = request.GET['id']
value = Model.objects.filter(id=id)
data = serializers.serialize('json', value, fields=('fieldone'))
return HttpResponse(data, content_type='application/json')
urls.py
url(r'^ajax/$', ajax_view.as_view()),
JQuery
$.ajax({
data: { 'id': id },
url: '/ajax/',
type: 'get',
success: function (data) {
// Do something with the data
}
})
That's in general how you can use Ajax with Django, the important is the use of TemplateView
Looking to get some insight and tips on using ajax with django.
Say I have a function:
def add_comment(request, pk):
if request.method == 'POST' and request.is_ajax():
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=True)
comment.save()
json = simplejson.dumps(comment, ensure_ascii=False)
return HttpResponse(json, mimetype='application/json')
return render_to_response({{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')
and I'm trying to post the comments to a page without a redirect with ajax function:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
$(document).click(function()
{
$('#comment_form').submit(function()
{
var dataString = $('#comment_form').serialize();
$.ajax({
type: 'POST',
url: '',
data: dataString,
success: function(data){
$('').html(data);
},
});
return false;
});
});
</script>
I believe I'm mixing up a few things here. I am trying to get the page to load comments without a redirect. I don't need an exact answer, maybe just steered in the right direction.
This can helps:
this could be your view:
import json
def add_comment(request, pk):
if request.method == 'POST' and request.is_ajax():
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=True)
comment.save()
json_response = json.dumps({"status":"Success"})
return HttpResponse(json_response)
errors = {}
for k, v in job_type_form.errors.items():
errors[k.capitalize()] = v
response = {
'success': False,
'errors': errors
}
return HttpResponse(json.dumps(response))
and your jquery could be like this:
$('#comment_form').submit(function() {
var dataString = $('#comment_form').serialize();
$.ajax({
type: 'POST',
url: '',// you need to put this to something like '{% url to_your_view %}'
data: dataString,
dataType: 'json'
success: function(data){
// you can access to your json object like data.status or data.something
$('').html(data.status);
},
});
return false;
});
Thanks for the posts I finally got things worked out. The jquery was the main issue.
$(document).ready(function() {
$('#comment_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url art.views.post %}',
data: $('#comment_form').serialize(),
dataType: 'json';
success: function(){
location.reload();
$('#comment_form').get(0).reset();
},
});
return false;
});
});
I was sending the DOM object not the actual form data to the view.
In the view I combined two functions to get the two sharing the same URL.
def post(request, pk):
post = Post.objects.get.(pk=int(pk))
comments = Comment.objects.filter(post=post)
_dict = dict(post=post, comments=comments, form=Comment_form(), user=request.user)
_dict.update(csrf(request))
cf_obj = Comment(post = Post.objects.get(pk=pk))
if request.method == 'POST' and request.is_ajax():
if comment_form.is_valid():
comment = comment_form.save(commit=True)
else:
raise Http404
response = serializers.serialize('json', [comment])
return HttpResponse(response, mimetype='application/json')
return render_to_response('post.html', d)
I have the following ajax call to update a particular field of a model
$("#updateLink").click(function(){
var dec_text = $('#desc_text').val();
$.ajax({
type: "POST",
url:"/users/update_desc/",
data: {
'val': dec_text,
},
success: function(){
$(".display, .edit").toggle();
$("#descText").html(dec_text);
},
error: function(){
alert("Error");
},
});
return false;
});
and my view is this
#csrf_exempt
def update_desc(request):
if request.is_ajax():
if request.method == 'POST':
desc_text = request.POST.get('val', False)
if desc_text:
profile = user.profile
profile.desc = desc_text
profile.save()
return_message = "Sent mail"
return HttpResponse(return_message,mimetype='application/javascript')
I am constantly getting an error message and I don't know how to solve this. I even used the csrf_exempt decorator to workaround if the problem was caused by a missing csrf token but still the problem persists.
Except one ajax post which in my base template all the ajax calls are failing. Can anybody please help to understand what is happening here. I can give some more details if required.
Edit:
I have added the a js file containing this https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax in my base template, so it means it is present in all my templates. And I am using django 1.3 version.
Firstly, you are using POST and not sending a csrf token. Try explicitly sending the csrf token rather than using the decorator csrf_exempt.
One way of doing this is with what I have done in data. That is to fetch the csrf token (or from your own method) and pass it in your arguments.
$.ajax({
url : url,
type: "POST",
data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value},
dataType : "json",
success: function( data ){
// do something
}
});