python - 使用 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
我怎样才能使它只显示我添加的帖子+数据库中的内容而不显示多个相同的帖子?谢谢你的帮助。
解决方案
您可以让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){
}
})
推荐阅读
- shopify - 如何在我的网站顶部添加多个品牌的导航栏?
- javascript - 用于切换功能和启用/禁用的变量
- bar-chart - mpAndroidChart:条形图只接受固定高度
- python - Tensorflow 二进制分类成本不变
- bash - 重命名文件:更改
- css - 为什么线性渐变适用于我的 div,但不适用于我的身体?
- metal - 在两个金属计算编码器之间快速传递可变 MTLBuffer
- keras - 相同的代码在两台不同的机器上运行,准确率悬殊;来自 Deep Learning with Python Chapter 5.3 pretrained convnet
- jstree - jstree dnd插件 - 防止掉落后移动?
- php - MongoDB 使用 PHP 插入集合限制