提交表单而不刷新页面

时间:2019-08-03 09:56:21

标签: python django ajax

我创建的表单包含标题,内容和图像。

我尝试提交该表单而不使用带有ajax的django刷新整个页面。

当我提交表单POST方法是可以的,但是我得到了另一个显示此错误的GET方法。

  

获取   http://127.0.0.1:8000/media/default.jpg   [HTTP / 1.1 404找不到8ms]

我没有在model.py中声明默认图像。

这是我的观点。py

def posts(request):
    posts = Post.objects.filter(posted_date__lte=timezone.now()).order_by('-posted_date')
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
    else:
        form = PostForm()
    args = {
        'form': form,
        'posts': posts,
    }
    if request.is_ajax():
        html = render_to_string('posts/post-section.html', context=args, request=request)
        return JsonResponse({'pos':html})
    return render(request, 'posts/posts.html', args)

这也是我的ajax

$(document).on('submit', '.post-form', function(event){
        event.preventDefault();
        console.log($(this).serialize());
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response){
                $('.post-section').html(response['pos']);
            },
            error: function(rs, e){
            console.log(rs.responseText);
            },
        });
    });

我应该怎么做才能在不刷新页面的情况下提交该帖子?

1 个答案:

答案 0 :(得分:0)

您的模板'posts / post-section.html'试图在渲染图像内容$('.post-section').html(response['pos']);时错误加载图像