提交表单而不刷新页面

2024-04-26 12:45:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建的表单包含标题、内容和图像。你知道吗

我尝试提交表单,而不使用带有ajax的django刷新整个页面。你知道吗

当我提交表单POST方法是可以的,但我得到另一个get方法显示这个错误。你知道吗

GET http://127.0.0.1:8000/media/default.jpg [HTTP/1.1 404 Not Found 8ms]

我没有在我的文件中声明默认图像型号.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);
            },
        });
    });

我该怎么做才能在不刷新页面的情况下提交那篇文章呢?你知道吗


Tags: 方法图像form表单ifrequesthtmlargs