Как я могу отправить значения моего шаблона в базу данных, используя Jquery, Ajax в django?
1.jquery
$(textbox).on('click','.save',function(e){
e.preventDefault();
var x = $('#input_msg').val();
$.ajax({
url:'newpostx/',
type: $(this).attr('method'),
data: x,
headers:{
'X-CSRFToken':'{{csrf_token}}'
}
}).done(function(msg) {
document.location = "http://127.0.0.1:8000/newpostx/"
alert("save data")
}).fail(function(err){
alert('no data was saved')
})
});
- home.html
$(container).on('click','.show', function () { //On click of link, textbox will open console.log(count[1]) msg_bubble = 1; $("div.popup").show(); var num = $(this).attr('value'); console.log(num,'num') $(textbox).append('Grid No_ '+ num +'
Bot Messages
Type any text here Add Message BubbleSelect InputText InputButtonsStar RatingsCalendar & TimeImage/File InputSelect User Input:Name
-->
Type Input:
File UploadTake PhotoFile Upload & Take PhotoButton
Add ButtonNumber of stars:
345Steps in stars:
0.51Type Input:
NameFull NameEmailMobilePasswordCustom TextCalendarData Limitation TypeAbsolute DateRelative DateMin Date
Max Date
TimeAppointment Duration15 minutes30 minutes1 hour2 hourStart Time
09:00 AM10:00 AM11:00 AM12:00 AMEnd Time
09:00 AM10:00 AM11:00 AM12:00 AMCancelSave') $("#input_msg").val() $("#input_msg"+num).text(window.localStorage.getItem(key+num)) console.log(count[num-1]) for(var i=2; iType any text here'); $(".container_inside").append(structure); $("#add_msg_"+num+i).text(window.localStorage.getItem(num+i)); } });
3.views.py
def post_new(request):
if request.method == "POST":
new_poll= text() #call model object
d= request.POST
new_poll.message= d['message']
new_poll.save()
print(new_poll)
return render(request, "loggedin.html")
4.models.py
class text(models.Model):
message = models.TextField(max_length=250)
time = models.DateTimeField(default=datetime.now)
5.urls.py
path('newpostx/',views.post_new,name='post_new'),
В основном вы пытаетесь отправить одно значение, поэтому jQuery отображает имя отправленной переменной в 'x' (поэтому вы получаете {'x': $('#input_msg').val()}
в request.POST
).
Чтобы решить эту проблему, вам нужно перезаписать атрибут data
в вызове AJAX
.
Так что измените эту строку:
data: x
В файл jQuery/JavaScript в:
data: {'message': x}
И это должно сработать. Также обратите внимание, что ваш первый алерт не будет работать, потому что вы изменяете document.location
и таким образом изменяете текущий сайт перед выполнением вызова alert()
.