使用Jquery和Ajax查询Django数据库

时间:2019-03-24 20:21:39

标签: python jquery json ajax django

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

我的意思的照片:

][

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>

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

这是我的观点

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

我如何做到这一点,使其仅显示我添加的帖子+数据库中的内容,而不显示多个相同的帖子?感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

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

如果您不喜欢这样做,可以将帖子的ID作为html中的data-post-id属性注入,然后仅将其附加到$('#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){

    }

})

答案 1 :(得分:0)

之所以得到倍数,是因为您要求在POST请求成功后发送数据库中的每个帖子。

假设cdata是一个数组,您可以做类似的事情

let innerHtml;
cdata.forEach(function(obj) {
    innerHtml.append(`<li>${data['fields'].title} ${data['fields'].body}</li>`);
});

$('#cb').html(innerHtml);

$('#cb').html(...)将替换元素的HTML内容,而不是添加到元素,因此您将不会获得任何重复的条目。另外,在append方法中使用template literal可以使事情更简洁。

或者您也可以只在posting的{​​{1}}视图中仅发送刚创建的帖子。随着您减少提交表单时的请求数量,这也将更快。

views.py

HttpResponse

home.html

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