Querying Django database with Jquery and AjaxDjango serializer for one objectIs there an “exists” function for jQuery?Add table row in jQueryHow do I check if an element is hidden in jQuery?Serializing to JSON in jQueryHow to manage a redirect request after a jQuery Ajax callSetting “checked” for a checkbox with jQuery?Abort Ajax requests using jQueryHow to check whether a checkbox is checked in jQuery?jQuery scroll to element“Thinking in AngularJS” if I have a jQuery background?
Why Does Mama Coco Look Old After Going to the Other World?
How to safely destroy (a large quantity of) valid checks?
The usage of kelvin in formulas
Is it safe to change the harddrive power feature so that it never turns off?
Can we completely replace inheritance using strategy pattern and dependency injection?
UTC timestamp format for launch vehicles
The origin of the Russian proverb about two hares
Java Servlet & JSP simple login
Why does this query, missing a FROM clause, not error out?
Increase speed altering column on large table to NON NULL
How long is it safe to leave marker on a Chessex battle map?
Ability To Change Root User Password (Vulnerability?)
How do i export activities related to an account with a specific recordtype?
Who won a Game of Bar Dice?
What aircraft was used as Air Force One for the flight between Southampton and Shannon?
Proving that a Russian cryptographic standard is too structured
How to prove a 4D vector is a 4-Vector?
Does the Nuka-Cola bottler actually generate nuka cola?
Separate SPI data
Was Self-modifying-code possible just using BASIC?
Grep Match and extract
Who is "He that flies" in Lord of the Rings?
How can I remove material from this wood beam?
How do we say "within a kilometer radius spherically"?
Querying Django database with Jquery and Ajax
Django serializer for one objectIs there an “exists” function for jQuery?Add table row in jQueryHow do I check if an element is hidden in jQuery?Serializing to JSON in jQueryHow to manage a redirect request after a jQuery Ajax callSetting “checked” for a checkbox with jQuery?Abort Ajax requests using jQueryHow to check whether a checkbox is checked in jQuery?jQuery scroll to element“Thinking in AngularJS” if I have a jQuery background?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have a POST request that passes data to my database when the form is submitted.
Photo of what I mean:
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post")
//POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm =$(this)
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
//I WANT TO PASS THE NEWLY ADDED DATA TO DISPLAY WITHOUT REFRESH
$.ajax(
type: 'GET',
url: '% url "postInfo" %',
dataType : 'json',
success: function(cdata)
$.each(cdata, function(id,posts)
$('#cb').append('<li>' +posts['fields'].title+ ' ' +posts['fields'].body+ '</li>');
);
);
,
error:function(errData)
)
)
)
</script>
As it is now it shows multiple of the same posts every time I add a post.
This is my views
views.py
def postInfo(request): # GET REQUEST
if request.method == 'GET' and request.is_ajax():
mytitle = Post.objects.all().order_by('-date_posted')
response = serializers.serialize("json", mytitle)
return HttpResponse(response, content_type='application/json')
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
return HttpResponse('')
models.py
class Post(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
How can I make it so it just shows the post that I have added + what's in the database without showing multiple of the same posts? Thanks for any help.
python jquery json ajax django
add a comment |
I have a POST request that passes data to my database when the form is submitted.
Photo of what I mean:
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post")
//POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm =$(this)
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
//I WANT TO PASS THE NEWLY ADDED DATA TO DISPLAY WITHOUT REFRESH
$.ajax(
type: 'GET',
url: '% url "postInfo" %',
dataType : 'json',
success: function(cdata)
$.each(cdata, function(id,posts)
$('#cb').append('<li>' +posts['fields'].title+ ' ' +posts['fields'].body+ '</li>');
);
);
,
error:function(errData)
)
)
)
</script>
As it is now it shows multiple of the same posts every time I add a post.
This is my views
views.py
def postInfo(request): # GET REQUEST
if request.method == 'GET' and request.is_ajax():
mytitle = Post.objects.all().order_by('-date_posted')
response = serializers.serialize("json", mytitle)
return HttpResponse(response, content_type='application/json')
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
return HttpResponse('')
models.py
class Post(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
How can I make it so it just shows the post that I have added + what's in the database without showing multiple of the same posts? Thanks for any help.
python jquery json ajax django
add a comment |
I have a POST request that passes data to my database when the form is submitted.
Photo of what I mean:
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post")
//POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm =$(this)
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
//I WANT TO PASS THE NEWLY ADDED DATA TO DISPLAY WITHOUT REFRESH
$.ajax(
type: 'GET',
url: '% url "postInfo" %',
dataType : 'json',
success: function(cdata)
$.each(cdata, function(id,posts)
$('#cb').append('<li>' +posts['fields'].title+ ' ' +posts['fields'].body+ '</li>');
);
);
,
error:function(errData)
)
)
)
</script>
As it is now it shows multiple of the same posts every time I add a post.
This is my views
views.py
def postInfo(request): # GET REQUEST
if request.method == 'GET' and request.is_ajax():
mytitle = Post.objects.all().order_by('-date_posted')
response = serializers.serialize("json", mytitle)
return HttpResponse(response, content_type='application/json')
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
return HttpResponse('')
models.py
class Post(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
How can I make it so it just shows the post that I have added + what's in the database without showing multiple of the same posts? Thanks for any help.
python jquery json ajax django
I have a POST request that passes data to my database when the form is submitted.
Photo of what I mean:
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post")
//POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm =$(this)
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
//I WANT TO PASS THE NEWLY ADDED DATA TO DISPLAY WITHOUT REFRESH
$.ajax(
type: 'GET',
url: '% url "postInfo" %',
dataType : 'json',
success: function(cdata)
$.each(cdata, function(id,posts)
$('#cb').append('<li>' +posts['fields'].title+ ' ' +posts['fields'].body+ '</li>');
);
);
,
error:function(errData)
)
)
)
</script>
As it is now it shows multiple of the same posts every time I add a post.
This is my views
views.py
def postInfo(request): # GET REQUEST
if request.method == 'GET' and request.is_ajax():
mytitle = Post.objects.all().order_by('-date_posted')
response = serializers.serialize("json", mytitle)
return HttpResponse(response, content_type='application/json')
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
return HttpResponse('')
models.py
class Post(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
How can I make it so it just shows the post that I have added + what's in the database without showing multiple of the same posts? Thanks for any help.
python jquery json ajax django
python jquery json ajax django
edited Mar 24 at 22:07
Michal
1,0191222
1,0191222
asked Mar 24 at 20:21
BadHabitsBadHabits
83
83
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You are getting multiples because you are asking for every post in the database to be sent upon the success of the POST request.
Assuming cdata
is an array, you could do something like
let innerHtml;
cdata.forEach(function(obj)
innerHtml.append(`<li>$data['fields'].title $data['fields'].body</li>`);
);
$('#cb').html(innerHtml);
$('#cb').html(...)
will replace the HTML content of the element rather than add to it so you will not get any duplicate entries. Also using a template literal in the append
method can make things a little cleaner.
Or you could simply send only the post you have just created in your posting
view in it's HttpResponse
. This will also be faster as you reduce the number of requests made when the form is submitted.
views.py
# Other endpoints
...
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
# Send new post as response
response = serializers.serialize('json', post)
return HttpResponse(response, content_type='application/json')
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post");
// POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm = $(this);
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success: function(data)
console.log(data);
$(".form-post")[0].reset();
// Add the new post to $('#cb')
$('#cb')
.append(`<li>$data['fields'].title $data['fields'].body</li>`);
,
error: function(errData)
// Do something
)
)
)
</script>
Thanks for the reply I changed to what you recommended sending the post in the HttpResponse but I am now getting TypeError: 'Post' object is not iterable. I am using - from django.core import serializers for the serialize. Same applies to @schillingt
– BadHabits
Mar 25 at 3:44
Looking at the docs for the serializer you are using,serialize
takes an iterator as its second argument, this is why you are seeing that error. If you have a look at this question stackoverflow.com/questions/2391002/… someone suggests thatserialize('json', [post])
should work. Remember that you will now get an array as a response.
– Jamie Williams
Mar 25 at 13:21
Also, you might want to look into using Django Rest Framework to build your API django-rest-framework.org.
– Jamie Williams
Mar 25 at 13:26
Thanks finally got it to work! Using ` post_arr = serializers.serialize('json', [post]) response = post_arr[1:-1]`
– BadHabits
Mar 25 at 13:40
add a comment |
You could have the POST
view return the serialized instance as follows. It may not be entirely correct as I don't know what you're using for serialization, but it should give you an idea.
If you don't like that, you could inject the id's of the post as a data-post-id
attribute in html, then only append it to $('#cb')
if it doesn't exist.
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
response = serializers.serialize("json", post)
return HttpResponse(response, content_type='application/json')
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
$('#cb').append('<li>' +data['fields'].title+ ' ' +data['fields'].body+ '</li>');
);
},
error:function(errData)
})
Thanks for reply, I have same problem as I stated below. I now get TypeError: 'Post' object is not iterable.
– BadHabits
Mar 25 at 3:58
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328190%2fquerying-django-database-with-jquery-and-ajax%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You are getting multiples because you are asking for every post in the database to be sent upon the success of the POST request.
Assuming cdata
is an array, you could do something like
let innerHtml;
cdata.forEach(function(obj)
innerHtml.append(`<li>$data['fields'].title $data['fields'].body</li>`);
);
$('#cb').html(innerHtml);
$('#cb').html(...)
will replace the HTML content of the element rather than add to it so you will not get any duplicate entries. Also using a template literal in the append
method can make things a little cleaner.
Or you could simply send only the post you have just created in your posting
view in it's HttpResponse
. This will also be faster as you reduce the number of requests made when the form is submitted.
views.py
# Other endpoints
...
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
# Send new post as response
response = serializers.serialize('json', post)
return HttpResponse(response, content_type='application/json')
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post");
// POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm = $(this);
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success: function(data)
console.log(data);
$(".form-post")[0].reset();
// Add the new post to $('#cb')
$('#cb')
.append(`<li>$data['fields'].title $data['fields'].body</li>`);
,
error: function(errData)
// Do something
)
)
)
</script>
Thanks for the reply I changed to what you recommended sending the post in the HttpResponse but I am now getting TypeError: 'Post' object is not iterable. I am using - from django.core import serializers for the serialize. Same applies to @schillingt
– BadHabits
Mar 25 at 3:44
Looking at the docs for the serializer you are using,serialize
takes an iterator as its second argument, this is why you are seeing that error. If you have a look at this question stackoverflow.com/questions/2391002/… someone suggests thatserialize('json', [post])
should work. Remember that you will now get an array as a response.
– Jamie Williams
Mar 25 at 13:21
Also, you might want to look into using Django Rest Framework to build your API django-rest-framework.org.
– Jamie Williams
Mar 25 at 13:26
Thanks finally got it to work! Using ` post_arr = serializers.serialize('json', [post]) response = post_arr[1:-1]`
– BadHabits
Mar 25 at 13:40
add a comment |
You are getting multiples because you are asking for every post in the database to be sent upon the success of the POST request.
Assuming cdata
is an array, you could do something like
let innerHtml;
cdata.forEach(function(obj)
innerHtml.append(`<li>$data['fields'].title $data['fields'].body</li>`);
);
$('#cb').html(innerHtml);
$('#cb').html(...)
will replace the HTML content of the element rather than add to it so you will not get any duplicate entries. Also using a template literal in the append
method can make things a little cleaner.
Or you could simply send only the post you have just created in your posting
view in it's HttpResponse
. This will also be faster as you reduce the number of requests made when the form is submitted.
views.py
# Other endpoints
...
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
# Send new post as response
response = serializers.serialize('json', post)
return HttpResponse(response, content_type='application/json')
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post");
// POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm = $(this);
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success: function(data)
console.log(data);
$(".form-post")[0].reset();
// Add the new post to $('#cb')
$('#cb')
.append(`<li>$data['fields'].title $data['fields'].body</li>`);
,
error: function(errData)
// Do something
)
)
)
</script>
Thanks for the reply I changed to what you recommended sending the post in the HttpResponse but I am now getting TypeError: 'Post' object is not iterable. I am using - from django.core import serializers for the serialize. Same applies to @schillingt
– BadHabits
Mar 25 at 3:44
Looking at the docs for the serializer you are using,serialize
takes an iterator as its second argument, this is why you are seeing that error. If you have a look at this question stackoverflow.com/questions/2391002/… someone suggests thatserialize('json', [post])
should work. Remember that you will now get an array as a response.
– Jamie Williams
Mar 25 at 13:21
Also, you might want to look into using Django Rest Framework to build your API django-rest-framework.org.
– Jamie Williams
Mar 25 at 13:26
Thanks finally got it to work! Using ` post_arr = serializers.serialize('json', [post]) response = post_arr[1:-1]`
– BadHabits
Mar 25 at 13:40
add a comment |
You are getting multiples because you are asking for every post in the database to be sent upon the success of the POST request.
Assuming cdata
is an array, you could do something like
let innerHtml;
cdata.forEach(function(obj)
innerHtml.append(`<li>$data['fields'].title $data['fields'].body</li>`);
);
$('#cb').html(innerHtml);
$('#cb').html(...)
will replace the HTML content of the element rather than add to it so you will not get any duplicate entries. Also using a template literal in the append
method can make things a little cleaner.
Or you could simply send only the post you have just created in your posting
view in it's HttpResponse
. This will also be faster as you reduce the number of requests made when the form is submitted.
views.py
# Other endpoints
...
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
# Send new post as response
response = serializers.serialize('json', post)
return HttpResponse(response, content_type='application/json')
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post");
// POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm = $(this);
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success: function(data)
console.log(data);
$(".form-post")[0].reset();
// Add the new post to $('#cb')
$('#cb')
.append(`<li>$data['fields'].title $data['fields'].body</li>`);
,
error: function(errData)
// Do something
)
)
)
</script>
You are getting multiples because you are asking for every post in the database to be sent upon the success of the POST request.
Assuming cdata
is an array, you could do something like
let innerHtml;
cdata.forEach(function(obj)
innerHtml.append(`<li>$data['fields'].title $data['fields'].body</li>`);
);
$('#cb').html(innerHtml);
$('#cb').html(...)
will replace the HTML content of the element rather than add to it so you will not get any duplicate entries. Also using a template literal in the append
method can make things a little cleaner.
Or you could simply send only the post you have just created in your posting
view in it's HttpResponse
. This will also be faster as you reduce the number of requests made when the form is submitted.
views.py
# Other endpoints
...
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
# Send new post as response
response = serializers.serialize('json', post)
return HttpResponse(response, content_type='application/json')
home.html
<script type="text/javascript">
$(document).ready(function()
var postForm = $(".form-post");
// POSTING DATA INTO DATABASE
postForm.submit(function(event)
event.preventDefault();
var thisForm = $(this);
var actionEndPoint = thisForm.attr("action");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success: function(data)
console.log(data);
$(".form-post")[0].reset();
// Add the new post to $('#cb')
$('#cb')
.append(`<li>$data['fields'].title $data['fields'].body</li>`);
,
error: function(errData)
// Do something
)
)
)
</script>
edited Mar 25 at 1:45
answered Mar 25 at 0:12
Jamie WilliamsJamie Williams
17118
17118
Thanks for the reply I changed to what you recommended sending the post in the HttpResponse but I am now getting TypeError: 'Post' object is not iterable. I am using - from django.core import serializers for the serialize. Same applies to @schillingt
– BadHabits
Mar 25 at 3:44
Looking at the docs for the serializer you are using,serialize
takes an iterator as its second argument, this is why you are seeing that error. If you have a look at this question stackoverflow.com/questions/2391002/… someone suggests thatserialize('json', [post])
should work. Remember that you will now get an array as a response.
– Jamie Williams
Mar 25 at 13:21
Also, you might want to look into using Django Rest Framework to build your API django-rest-framework.org.
– Jamie Williams
Mar 25 at 13:26
Thanks finally got it to work! Using ` post_arr = serializers.serialize('json', [post]) response = post_arr[1:-1]`
– BadHabits
Mar 25 at 13:40
add a comment |
Thanks for the reply I changed to what you recommended sending the post in the HttpResponse but I am now getting TypeError: 'Post' object is not iterable. I am using - from django.core import serializers for the serialize. Same applies to @schillingt
– BadHabits
Mar 25 at 3:44
Looking at the docs for the serializer you are using,serialize
takes an iterator as its second argument, this is why you are seeing that error. If you have a look at this question stackoverflow.com/questions/2391002/… someone suggests thatserialize('json', [post])
should work. Remember that you will now get an array as a response.
– Jamie Williams
Mar 25 at 13:21
Also, you might want to look into using Django Rest Framework to build your API django-rest-framework.org.
– Jamie Williams
Mar 25 at 13:26
Thanks finally got it to work! Using ` post_arr = serializers.serialize('json', [post]) response = post_arr[1:-1]`
– BadHabits
Mar 25 at 13:40
Thanks for the reply I changed to what you recommended sending the post in the HttpResponse but I am now getting TypeError: 'Post' object is not iterable. I am using - from django.core import serializers for the serialize. Same applies to @schillingt
– BadHabits
Mar 25 at 3:44
Thanks for the reply I changed to what you recommended sending the post in the HttpResponse but I am now getting TypeError: 'Post' object is not iterable. I am using - from django.core import serializers for the serialize. Same applies to @schillingt
– BadHabits
Mar 25 at 3:44
Looking at the docs for the serializer you are using,
serialize
takes an iterator as its second argument, this is why you are seeing that error. If you have a look at this question stackoverflow.com/questions/2391002/… someone suggests that serialize('json', [post])
should work. Remember that you will now get an array as a response.– Jamie Williams
Mar 25 at 13:21
Looking at the docs for the serializer you are using,
serialize
takes an iterator as its second argument, this is why you are seeing that error. If you have a look at this question stackoverflow.com/questions/2391002/… someone suggests that serialize('json', [post])
should work. Remember that you will now get an array as a response.– Jamie Williams
Mar 25 at 13:21
Also, you might want to look into using Django Rest Framework to build your API django-rest-framework.org.
– Jamie Williams
Mar 25 at 13:26
Also, you might want to look into using Django Rest Framework to build your API django-rest-framework.org.
– Jamie Williams
Mar 25 at 13:26
Thanks finally got it to work! Using ` post_arr = serializers.serialize('json', [post]) response = post_arr[1:-1]`
– BadHabits
Mar 25 at 13:40
Thanks finally got it to work! Using ` post_arr = serializers.serialize('json', [post]) response = post_arr[1:-1]`
– BadHabits
Mar 25 at 13:40
add a comment |
You could have the POST
view return the serialized instance as follows. It may not be entirely correct as I don't know what you're using for serialization, but it should give you an idea.
If you don't like that, you could inject the id's of the post as a data-post-id
attribute in html, then only append it to $('#cb')
if it doesn't exist.
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
response = serializers.serialize("json", post)
return HttpResponse(response, content_type='application/json')
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
$('#cb').append('<li>' +data['fields'].title+ ' ' +data['fields'].body+ '</li>');
);
},
error:function(errData)
})
Thanks for reply, I have same problem as I stated below. I now get TypeError: 'Post' object is not iterable.
– BadHabits
Mar 25 at 3:58
add a comment |
You could have the POST
view return the serialized instance as follows. It may not be entirely correct as I don't know what you're using for serialization, but it should give you an idea.
If you don't like that, you could inject the id's of the post as a data-post-id
attribute in html, then only append it to $('#cb')
if it doesn't exist.
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
response = serializers.serialize("json", post)
return HttpResponse(response, content_type='application/json')
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
$('#cb').append('<li>' +data['fields'].title+ ' ' +data['fields'].body+ '</li>');
);
},
error:function(errData)
})
Thanks for reply, I have same problem as I stated below. I now get TypeError: 'Post' object is not iterable.
– BadHabits
Mar 25 at 3:58
add a comment |
You could have the POST
view return the serialized instance as follows. It may not be entirely correct as I don't know what you're using for serialization, but it should give you an idea.
If you don't like that, you could inject the id's of the post as a data-post-id
attribute in html, then only append it to $('#cb')
if it doesn't exist.
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
response = serializers.serialize("json", post)
return HttpResponse(response, content_type='application/json')
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
$('#cb').append('<li>' +data['fields'].title+ ' ' +data['fields'].body+ '</li>');
);
},
error:function(errData)
})
You could have the POST
view return the serialized instance as follows. It may not be entirely correct as I don't know what you're using for serialization, but it should give you an idea.
If you don't like that, you could inject the id's of the post as a data-post-id
attribute in html, then only append it to $('#cb')
if it doesn't exist.
def posting(request): # POST REQUEST
if request.method == 'POST' and request.is_ajax():
title = request.POST.get('postTitle')
content = request.POST.get('postContent')
post = Post()
post.title = title
post.body = content
post.author = request.user
post.save()
response = serializers.serialize("json", post)
return HttpResponse(response, content_type='application/json')
$.ajax(
url: actionEndPoint,
method: httpMethod,
data: formData,
success:function(data)
console.log(data)
$(".form-post")[0].reset();
$('#cb').append('<li>' +data['fields'].title+ ' ' +data['fields'].body+ '</li>');
);
},
error:function(errData)
})
answered Mar 25 at 0:06
schillingtschillingt
6,69011824
6,69011824
Thanks for reply, I have same problem as I stated below. I now get TypeError: 'Post' object is not iterable.
– BadHabits
Mar 25 at 3:58
add a comment |
Thanks for reply, I have same problem as I stated below. I now get TypeError: 'Post' object is not iterable.
– BadHabits
Mar 25 at 3:58
Thanks for reply, I have same problem as I stated below. I now get TypeError: 'Post' object is not iterable.
– BadHabits
Mar 25 at 3:58
Thanks for reply, I have same problem as I stated below. I now get TypeError: 'Post' object is not iterable.
– BadHabits
Mar 25 at 3:58
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328190%2fquerying-django-database-with-jquery-and-ajax%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown