Reputation: 597
Hey Guys, Could you help me to send post data to the form. Here what I have: models:
class Test (models.Model):
text = models.TextField(blank=True, max_length=300)
views:
def post_test(request):
print 'aesewewewew'
if request.is_ajax():
print 'ajax'
form = TestForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('success')
else:
return HttpResponse('failed')
else:
print 'aaaaa'
templates:
<div id="post"></div>
<a href="/" onclick=click()>Post</a>
<script>
function click(){
$.post("/post", {
text: "eqweqeqeqweqw"
},
function(data) {
alert(data);
}
)};
url:
(r'^post','test_propject.main.views.post_test'),
form:
class TestForm (forms.ModelForm):
class Meta:
model = Test
It doesn't work for me. I can't find an error here. Could you give a link maybe to working code. Get request works fine. Maybe some way exist to make simple form, that has been created from Models, sends data via ajax, without reloading a page.
Thank you
Upvotes: 2
Views: 3005
Reputation: 597
The main my problem was my brain). I forgot to enclude:
<script type="text/javascript">
$('html').ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
</script>
Upvotes: 0
Reputation: 183
Try this :
def post_test(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('success')
else:
return HttpResponse('failed')
I strongly suggest you study the tutorial here before implementing the above ..
Edit: Your urls.py should look something like this:
from django.conf.urls.defaults import *
from test_project.main.views import post_test
urlpatterns = patterns('',
url(r'^post/$', post_test, name = 'post_test'),
)
And your templates:
<script>
function click(){
$.post('{% url post_test %}', {
text: "eqweqeqeqweqw"
}
)};
</script>
Pls note that {% url post_test %}, doesn't work in external js files.
Upvotes: 3