如何在Django和Jquery中使用带有model.Form的Ajax发送数据

时间:2011-04-28 02:00:27

标签: jquery ajax django modelform

嘿伙计们,你能帮我把帖子数据发送到表格吗?在这里我有: 机型:

class Test (models.Model):
    text    = models.TextField(blank=True, max_length=300)

的观点:

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'

模板:

<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'),

表格:

class TestForm (forms.ModelForm):
    class Meta:
        model = Test

它对我不起作用。我在这里找不到错误。你能给一个工作代码链接吗?请求工作正常。也许有一些方法可以创建简单的表单,它是从Models创建的,通过ajax发送数据,而无需重新加载页面。

谢谢

2 个答案:

答案 0 :(得分:2)

试试这个:

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')  

我强烈建议您在实施上述内容之前学习教程here

修改 你的urls.py应该是这样的:

from django.conf.urls.defaults import *
from test_project.main.views import post_test

urlpatterns = patterns('',
  url(r'^post/$', post_test, name = 'post_test'),
)

你的模板:

<script>
function click(){
    $.post('{% url post_test %}', {
        text: "eqweqeqeqweqw"
    }
)};
</script>

请注意{%url post_test%}在外部js文件中不起作用。

答案 1 :(得分:0)

我的主要问题是我的大脑)。我忘了包括:

<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>