首页 > 解决方案 > 使用 Jquery 和 Ajax 查询 Django 数据库

问题描述

我有一个 POST 请求,在提交表单时将数据传递到我的数据库。

我的意思的照片:

][

主页.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>

就像现在一样,每次我添加帖子时它都会显示多个相同的帖子。

这是我的看法

视图.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('') 

模型.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

我怎样才能使它只显示我添加的帖子+数据库中的内容而不显示多个相同的帖子?谢谢你的帮助。

标签: pythonjqueryjsonajaxdjango

解决方案


您可以让POST视图返回序列化实例,如下所示。它可能不完全正确,因为我不知道您使用什么进行序列化,但它应该给您一个想法。

如果您不喜欢这样,您可以将帖子的 id 作为data-post-id属性注入 html 中,然后仅$('#cb')在它不存在时将其附加到。

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

    }

})

推荐阅读